import json

def load_data(path):
    with open(path, "r") as f:
        d = json.load(f)
        return d.get("bars", d)

h4 = load_data("hybrid/data/ohlcv_H4.json")
m30 = load_data("hybrid/data/ohlcv_M30.json")
m15 = load_data("hybrid/data/ohlcv_M15.json")
m5 = load_data("hybrid/data/ohlcv_M5.json")

timestamps = [
    "2026-07-01T07:15:00Z",
    "2026-07-01T22:15:00Z",
    "2026-07-02T01:45:00Z"
]

def extract_window(data, target_ts, before=10, after=5):
    for i, row in enumerate(data):
        ts = row.get("time", row.get("timestamp"))
        if isinstance(ts, int):
            # Fallback if somehow integer timestamp
            import datetime
            ts = datetime.datetime.utcfromtimestamp(ts).isoformat() + "Z"
        if ts == target_ts or str(ts) > target_ts:
            return data[max(0, i-before):i+after]
    return []

out = {}
for ts in timestamps:
    out[ts] = {
        "H4": extract_window(h4, ts[:13]+":00:00Z", 3, 2),
        "M30": extract_window(m30, ts[:14]+("00" if int(ts[14:16]) < 30 else "30")+":00Z", 6, 4),
        "M15": extract_window(m15, ts, 8, 6),
        "M5": extract_window(m5, ts, 12, 10)
    }

with open("hybrid/reviews/data_737_740.json", "w") as f:
    json.dump(out, f, indent=2)
print("Data extracted.")
