import json
from datetime import datetime, timezone

def parse_time(ts_str):
    return datetime.strptime(ts_str, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)

def load_json(filepath):
    with open(filepath, 'r') as f:
        data = json.load(f)
        if isinstance(data, dict):
            if 'data' in data:
                return data['data']
            if 'bars' in data:
                return data['bars']
            for k, v in data.items():
                if isinstance(v, list) and len(v) > 0 and 'time' in v[0]:
                    return v
        return data

def get_bars_around(data, target_ts_str, before=5, after=5):
    if not data: return []
    target_dt = parse_time(target_ts_str)
    bars = []
    
    for bar in data:
        t = bar['time']
        if isinstance(t, str):
            # Assume it might be ISO string if not a timestamp string
            try:
                t = int(t)
            except ValueError:
                t = int(datetime.fromisoformat(t.replace('Z', '+00:00')).timestamp() * 1000)
                
        bar_dt = datetime.utcfromtimestamp(t / 1000).replace(tzinfo=timezone.utc)
        bars.append({'dt': bar_dt, 'bar': bar})
        
    bars.sort(key=lambda x: x['dt'])
    
    target_idx = -1
    for i, b in enumerate(bars):
        if b['dt'] == target_dt:
            target_idx = i
            break
        if b['dt'] > target_dt:
            target_idx = i - 1
            break
            
    if target_idx == -1:
        # If timestamp exactly doesn't match, find the closest before
        for i, b in enumerate(bars):
            if b['dt'] > target_dt:
                target_idx = i - 1
                break
        if target_idx == -1:
             target_idx = len(bars) - 1
        
    start_idx = max(0, target_idx - before)
    end_idx = min(len(bars), target_idx + after + 1)
    
    return [b['bar'] for b in bars[start_idx:end_idx]]

def print_bar_summary(bars, tf):
    print(f"--- {tf} Bars ---")
    for b in bars:
        t = b['time']
        if isinstance(t, str):
            try:
                t = int(t)
            except:
                t = int(datetime.fromisoformat(t.replace('Z', '+00:00')).timestamp() * 1000)
        dt = datetime.utcfromtimestamp(t / 1000).strftime('%Y-%m-%d %H:%M')
        print(f"{dt}: O={b['open']} H={b['high']} L={b['low']} C={b['close']}")

def evaluate():
    try:
        h4_data = load_json('hybrid/data/ohlcv_H4.json')
        h1_data = load_json('hybrid/data/ohlcv_H1.json')
        m30_data = load_json('hybrid/data/ohlcv_M30.json')
        m15_data = load_json('hybrid/data/ohlcv_M15.json')
        m5_data = load_json('hybrid/data/ohlcv_M5.json')
        
        candidates = [
            ("2026-02-17T23:15:00Z", "Short"),
            ("2026-02-18T11:45:00Z", "Long"),
            ("2026-02-18T17:45:00Z", "Short")
        ]
        
        for ts, d in candidates:
            print(f"\\nEvaluating {ts} {d}")
            print_bar_summary(get_bars_around(h4_data, ts, 2, 2), "H4")
            print_bar_summary(get_bars_around(h1_data, ts, 3, 3), "H1")
            print_bar_summary(get_bars_around(m30_data, ts, 4, 4), "M30")
            print_bar_summary(get_bars_around(m15_data, ts, 5, 5), "M15")
    except Exception as e:
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    evaluate()
