import json
from datetime import datetime, timezone

data_path = "/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026/hybrid/data"

def get_context(timestamp_str):
    target_dt = datetime.fromisoformat(timestamp_str.replace("Z", "+00:00"))
    target_ts = int(target_dt.timestamp())
    
    context = {}
    for tf in ["M5"]:
        with open(f"{data_path}/ohlcv_{tf}.json") as f:
            data = json.load(f)
            bars_data = data if isinstance(data, list) else data.get('bars', [])
            
        bars = []
        for b in bars_data:
            ts = b.get('time') if isinstance(b, dict) else b[0]
            if isinstance(ts, str):
                try:
                    ts_val = int(datetime.fromisoformat(ts.replace("Z", "+00:00")).timestamp())
                except:
                    continue
            else:
                ts_val = ts / 1000 if ts > 2e9 else ts

            if ts_val <= target_ts:
                bars.append(b)
        
        context[tf] = bars[-12:] if bars else []
        
    return context

items = [
  "2026-03-25T04:00:00Z",
  "2026-03-25T05:45:00Z",
  "2026-03-25T08:00:00Z"
]

for ts in items:
    print(f"\n--- Context for {ts} ---")
    ctx = get_context(ts)
    for tf, bars in ctx.items():
        print(f"  {tf}:")
        for b in bars:
             if isinstance(b, dict):
                 dt = b.get('time', 'unknown')
                 print(f"    {dt} - O:{b.get('open')} H:{b.get('high')} L:{b.get('low')} C:{b.get('close')}")
             else:
                 dt = datetime.fromtimestamp(b[0]/1000 if b[0] > 2e9 else b[0], tz=timezone.utc).strftime('%Y-%m-%d %H:%M')
                 print(f"    {dt} - O:{b[1]} H:{b[2]} L:{b[3]} C:{b[4]}")
