import json
from pathlib import Path
from datetime import datetime, timezone
from dateutil import parser

# Base dir
base_dir = Path("/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026")

def load_data(tf):
    with open(base_dir / f"hybrid/data/ohlcv_{tf}.json") as f:
        return json.load(f)["bars"]

data_H4 = load_data("H4")
data_M30 = load_data("M30")
data_M15 = load_data("M15")
data_M5 = load_data("M5")

def get_context(data, timestamp, limit=10):
    ts = parser.parse(timestamp).replace(tzinfo=timezone.utc).timestamp()
    idx = -1
    for i, candle in enumerate(data):
        if 'time' in candle and isinstance(candle['time'], str):
            candle_ts = parser.parse(candle['time']).replace(tzinfo=timezone.utc).timestamp()
        elif 'time' in candle and isinstance(candle['time'], (int, float)):
            candle_ts = candle['time']
        else:
            candle_ts = 0
            
        if candle_ts <= ts:
            idx = i
        else:
            break
    if idx == -1: return []
    return data[max(0, idx - limit + 1):idx + 1]

candidates = [
    {"id": "candidate_2026-03-27T04-00-00Z_long_liquidity_sweep_reversal", "ts": "2026-03-27T04:00:00Z"},
    {"id": "candidate_2026-03-27T09-30-00Z_short_liquidity_sweep_reversal", "ts": "2026-03-27T09:30:00Z"},
    {"id": "candidate_2026-03-27T10-00-00Z_short_liquidity_sweep_reversal", "ts": "2026-03-27T10:00:00Z"},
]

for c in candidates:
    print(f"\n--- {c['id']} ({c['ts']}) ---")
    
    h4 = get_context(data_H4, c['ts'], limit=3)
    print("H4 context:")
    for candle in h4:
        print(f"  {candle.get('time', candle.get('timestamp'))}: O={candle['open']}, H={candle['high']}, L={candle['low']}, C={candle['close']}")
        
    m30 = get_context(data_M30, c['ts'], limit=4)
    print("M30 context:")
    for candle in m30:
        print(f"  {candle.get('time', candle.get('timestamp'))}: O={candle['open']}, H={candle['high']}, L={candle['low']}, C={candle['close']}")
        
    m15 = get_context(data_M15, c['ts'], limit=4)
    print("M15 context:")
    for candle in m15:
        print(f"  {candle.get('time', candle.get('timestamp'))}: O={candle['open']}, H={candle['high']}, L={candle['low']}, C={candle['close']}")

    m5 = get_context(data_M5, c['ts'], limit=8)
    print("M5 context:")
    for candle in m5:
        print(f"  {candle.get('timestamp', candle.get('time'))}: O={candle['open']}, H={candle['high']}, L={candle['low']}, C={candle['close']}")
