import json
from datetime import datetime, timezone
import os

base_dir = "/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026/hybrid/data"

def parse_time(time_val):
    if isinstance(time_val, int):
        return time_val
    dt = datetime.strptime(time_val, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
    return int(dt.timestamp()) * 1000

def parse_time_m5(time_val):
    # m5 time is a number but let's check
    return time_val

def analyze_item(timestamp_str, direction):
    dt = datetime.strptime(timestamp_str, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
    target_ts = int(dt.timestamp()) * 1000

    print(f"\n--- Analyzing {timestamp_str} {direction} ---")

    # M30 data for structure
    try:
        with open(os.path.join(base_dir, 'ohlcv_M30.json'), 'r') as f:
            m30_data = json.load(f)["bars"]
        m30_bars = [b for b in m30_data if parse_time(b['time']) <= target_ts][-10:]
        if not m30_bars:
            print("No M30 data found")
        else:
            print(f"M30 Current Price roughly: {m30_bars[-1]['close']}")
            highs = [b['high'] for b in m30_bars]
            lows = [b['low'] for b in m30_bars]
            print(f"M30 Recent Range: {min(lows)} - {max(highs)}")
    except Exception as e:
        print(f"Error reading M30: {e}")

    # M5 data for execution
    try:
        with open(os.path.join(base_dir, 'ohlcv_M5.json'), 'r') as f:
            m5_data = json.load(f)["bars"]
            
        # check m5 time format from first bar
        if isinstance(m5_data[0]['time'], str):
             m5_bars = [b for b in m5_data if parse_time(b['time']) <= target_ts][-15:]
        else:
             # assuming m5 time in seconds or ms? Wait, 1970 print above means it was not scaled correctly.
             # actually let's just parse the string if it's string.
             m5_bars = [b for b in m5_data if (parse_time(b['time']) if isinstance(b['time'], str) else (b['time']*1000 if b['time'] < 20000000000 else b['time'])) <= target_ts][-15:]

        if not m5_bars:
            print("No M5 data found")
        else:
            print("\nM5 Execution context (last 5 bars):")
            for b in m5_bars[-5:]:
                t_val = b['time']
                if isinstance(t_val, str):
                    dt_bar = t_val
                else:
                    if t_val < 20000000000: t_val *= 1000
                    dt_bar = datetime.fromtimestamp(t_val/1000, tz=timezone.utc).isoformat()
                print(f"  {dt_bar}: O={b['open']} H={b['high']} L={b['low']} C={b['close']}")
    except Exception as e:
        print(f"Error reading M5: {e}")

if __name__ == "__main__":
    analyze_item("2026-01-23T14:30:00Z", "Long")
    analyze_item("2026-01-23T18:15:00Z", "Short")
    analyze_item("2026-01-26T12:00:00Z", "Long")
