import json

def load_data(file_name):
    path = f"/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026/hybrid/data/{file_name}"
    with open(path, "r") as f:
        data = json.load(f)
        if isinstance(data, dict) and "data" in data:
            return data["data"]
        elif isinstance(data, dict):
            # Try to find a list value
            for v in data.values():
                if isinstance(v, list):
                    return v
        return data

def get_bars_around(data, timestamp, num_before=10, num_after=5):
    for i, bar in enumerate(data):
        if isinstance(bar, dict) and 'time' in bar and str(bar['time']).startswith(timestamp[:16]):
            start = max(0, i - num_before)
            end = min(len(data), i + num_after + 1)
            return data[start:end]
        elif isinstance(bar, list) and len(bar) > 0 and str(bar[0]).startswith(timestamp[:16]):
            start = max(0, i - num_before)
            end = min(len(data), i + num_after + 1)
            return data[start:end]
    
    # Try finding the closest bar before the timestamp if exact match not found
    for i in range(len(data)-1, -1, -1):
        time_val = ""
        if isinstance(data[i], dict) and 'time' in data[i]:
            time_val = str(data[i]['time'])
        elif isinstance(data[i], list) and len(data[i]) > 0:
            time_val = str(data[i][0])
            
        if time_val and time_val <= timestamp:
            start = max(0, i - num_before)
            end = min(len(data), i + num_after + 1)
            return data[start:end]
            
    return []

# Timestamps to check
timestamps = [
    "2026-07-07T09:15:00Z",
    "2026-07-07T22:30:00Z",
    "2026-07-07T23:45:00Z"
]

files = ['ohlcv_H4.json', 'ohlcv_H1.json', 'ohlcv_M15.json', 'ohlcv_M5.json']
data = {}
for f in files:
    try:
        data[f] = load_data(f)
        print(f"Loaded {f}, format: type={type(data[f])}, length={len(data[f]) if isinstance(data[f], list) else 'N/A'}")
        if isinstance(data[f], list) and len(data[f]) > 0:
            print(f"  First item type: {type(data[f][0])}")
    except Exception as e:
        print(f"Failed to load {f}: {e}")

for ts in timestamps:
    print(f"\n--- Context for {ts} ---")
    print("H4 context:")
    h4 = get_bars_around(data.get('ohlcv_H4.json', []), ts[:13], 2, 2)
    for b in h4: print(b)
    
    print("\nM15 context:")
    m15 = get_bars_around(data.get('ohlcv_M15.json', []), ts, 3, 3)
    for b in m15: print(b)
    
    print("\nM5 context:")
    m5 = get_bars_around(data.get('ohlcv_M5.json', []), ts, 3, 3)
    for b in m5: print(b)
