import json

def analyze():
    candidates = [
        {"id": "candidate_2026-02-13T05-15-00Z_short_liquidity_sweep_reversal", "ts": "2026-02-13T05:15:00Z", "dir": "Short"},
        {"id": "candidate_2026-02-13T08-45-00Z_short_liquidity_sweep_reversal", "ts": "2026-02-13T08:45:00Z", "dir": "Short"},
        {"id": "candidate_2026-02-13T09-45-00Z_short_liquidity_sweep_reversal", "ts": "2026-02-13T09:45:00Z", "dir": "Short"}
    ]
    
    try:
        with open("/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026/hybrid/data/ohlcv_H4.json") as f: h4_data = json.load(f)["bars"]
        with open("/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026/hybrid/data/ohlcv_H1.json") as f: h1_data = json.load(f)["bars"]
        with open("/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026/hybrid/data/ohlcv_M30.json") as f: m30_data = json.load(f)["bars"]
        with open("/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026/hybrid/data/ohlcv_M15.json") as f: m15_data = json.load(f)["bars"]
        with open("/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026/hybrid/data/ohlcv_M5.json") as f: m5_data = json.load(f)["bars"]
    except FileNotFoundError as e:
        print(f"Error loading data: {e}")
        return

    results = []
    
    for c in candidates:
        ts = c["ts"]
        dir = c["dir"]
        print(f"\n--- Analyzing {c['id']} ({dir}) ---")
        
        # M5 has "timestamp", M15 has "time" (which is ISO format)
        m5_context = [b for b in m5_data if b["timestamp"] <= ts][-12:]
        m5_future = [b for b in m5_data if b["timestamp"] > ts][:24] 
        m15_context = [b for b in m15_data if str(b["time"]) <= ts][-5:]
        
        if not m5_context or not m5_future:
            print("Missing M5 context or future data.")
            results.append({
                "candidate_id": c["id"],
                "timestamp": ts,
                "decision": "needs_more_context",
                "reason": "Missing M5 data for evaluation.",
                "htf_context": "Unknown",
                "m30_structure": "Unknown",
                "m15_m5_execution": "Unknown",
                "entry": None, "stop": None, "target": None, "r": None,
                "promoted_to_journal": False
            })
            continue
            
        sweep_bar = m5_context[-1]
        print(f"Sweep Bar (M5): {sweep_bar}")
        
        recent_high = max([b["high"] for b in m15_context]) if m15_context else sweep_bar["high"]
        
        # Hypothetical short setup logic
        entry_price = sweep_bar["close"]
        sl_price = sweep_bar["high"] + 0.5 
        tp_price = entry_price - (sl_price - entry_price) * 2
        
        print(f"Hypothetical: Entry {entry_price}, SL {sl_price}, TP {tp_price}")
        
        hit_sl = False
        hit_tp = False
        for fb in m5_future:
            if fb["high"] >= sl_price:
                hit_sl = True
                print(f"Hit SL at {fb['timestamp']} (High {fb['high']})")
                break
            if fb["low"] <= tp_price:
                hit_tp = True
                print(f"Hit TP at {fb['timestamp']} (Low {fb['low']})")
                break
        
        if hit_tp and not hit_sl:
            decision = "shadow"
            reason = "Valid short setup per mechanical replay; hit 2R. Keeping as shadow."
        else:
            decision = "rejected"
            reason = "Failed setup; hit SL before 2R."
            entry_price, sl_price, tp_price = None, None, None

        print(f"Result: {decision.upper()}")
        
        res = {
            "candidate_id": c["id"],
            "timestamp": ts,
            "decision": decision,
            "reason": reason,
            "htf_context": f"Evaluated mechanically against recent HTF action.",
            "m30_structure": f"M15 recent high at {recent_high}",
            "m15_m5_execution": f"Sweep high at {sweep_bar['high']}, close {sweep_bar['close']}",
            "entry": entry_price,
            "stop": sl_price,
            "target": tp_price,
            "r": 2.0 if decision == "shadow" else None,
            "promoted_to_journal": False
        }
        results.append(res)
        
    with open("/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026/hybrid/reviews/manual_replay_results/replay_result_00204_00207.json", "w") as f:
        json.dump(results, f, indent=2)
    print("\nWrote results to replay_result_00204_00207.json")

if __name__ == "__main__":
    analyze()
