import json
import datetime

def get_bars(filepath, start_time, end_time):
    with open(filepath, 'r') as f:
        data = json.load(f)
    
    start_ts = datetime.datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%SZ").timestamp()
    end_ts = datetime.datetime.strptime(end_time, "%Y-%m-%dT%H:%M:%SZ").timestamp()
    
    bars = []
    for b in data['bars']:
        b_time = b['time']
        # handle iso string or unix ts
        if isinstance(b_time, str):
             if b_time.endswith('Z'):
                  b_ts = datetime.datetime.strptime(b_time, "%Y-%m-%dT%H:%M:%SZ").timestamp()
             else:
                  # Just try to parse as iso if no Z
                  try:
                       b_ts = datetime.datetime.fromisoformat(b_time).timestamp()
                  except:
                       b_ts = 0
             if start_ts <= b_ts <= end_ts:
                  bars.append(b)
        else:
             # assuming unix timestamp
             # check if it's ms or s
             if b_time > 20000000000:
                  b_ts = b_time / 1000
             else:
                  b_ts = b_time
                  
             if start_ts <= b_ts <= end_ts:
                  bars.append(b)
                  
    return bars

start = "2026-06-23T00:00:00Z"
end = "2026-06-24T23:59:59Z"

h4 = get_bars('../data/ohlcv_H4.json', start, end)
h1 = get_bars('../data/ohlcv_H1.json', start, end)
m30 = get_bars('../data/ohlcv_M30.json', start, end)
m15 = get_bars('../data/ohlcv_M15.json', start, end)
m5 = get_bars('../data/ohlcv_M5.json', start, end)

out = {
    "h4": [{"time": b['time'], "o": b['open'], "h": b['high'], "l": b['low'], "c": b['close']} for b in h4],
    "h1": [{"time": b['time'], "o": b['open'], "h": b['high'], "l": b['low'], "c": b['close']} for b in h1],
    "m30": [{"time": b['time'], "o": b['open'], "h": b['high'], "l": b['low'], "c": b['close']} for b in m30],
    "m15": [{"time": b['time'], "o": b['open'], "h": b['high'], "l": b['low'], "c": b['close']} for b in m15],
    "m5": [{"time": b['time'], "o": b['open'], "h": b['high'], "l": b['low'], "c": b['close']} for b in m5]
}

print(json.dumps(out, indent=2))
