import json
import os
import sys
from datetime import datetime, timezone

def parse_time(t_str):
    if isinstance(t_str, int): return t_str
    return int(datetime.fromisoformat(t_str.replace('Z', '+00:00')).timestamp())

def analyze_candidates():
    project_root = "/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026"
    manifest_path = os.path.join(project_root, "hybrid/reviews/manual_replay_readiness_manifest.json")
    
    with open(manifest_path, 'r') as f:
        manifest = json.load(f)
        
    candidates = manifest['manual_replay_items'][114:117]
    
    with open(os.path.join(project_root, "hybrid/data/ohlcv_M30.json"), 'r') as f:
        m30_data = json.load(f)['bars']
        
    with open(os.path.join(project_root, "hybrid/data/ohlcv_M15.json"), 'r') as f:
        m15_data = json.load(f)['bars']
        
    with open(os.path.join(project_root, "hybrid/data/ohlcv_M5.json"), 'r') as f:
        m5_data = json.load(f)['bars']
        
    results = []
    
    for candidate in candidates:
        timestamp = candidate['timestamp']
        dt = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
        
        target_ts = int(dt.timestamp())
        
        m30_context = [c for c in m30_data if target_ts - 2*86400 <= parse_time(c['time']) <= target_ts]
        m5_execution = [c for c in m5_data if target_ts - 3600 <= parse_time(c['time']) <= target_ts + 4*3600]
        
        result = {
            "candidate_id": candidate['candidate_id'],
            "timestamp": timestamp,
            "direction": candidate['direction'],
            "decision": "needs_more_context",
            "reason": "Initial programmatic pass",
            "htf_context": f"M30 points checked: {len(m30_context)}",
            "m30_structure": "Pending visual or deeper programmatic analysis",
            "m15_m5_execution": f"M5 execution candles available: {len(m5_execution)}",
            "entry": None,
            "stop": None,
            "target": None,
            "r": None,
            "promoted_to_journal": False
        }
        
        if len(m5_execution) > 0:
            entry_price = m5_execution[0]['open']
            max_high = max(c['high'] for c in m5_execution)
            min_low = min(c['low'] for c in m5_execution)
            
            result['htf_context'] = f"Context available up to {m30_context[-1]['time'] if m30_context else 'N/A'}"
            result['m30_structure'] = f"Recent M30 range: {min(c['low'] for c in m30_context) if m30_context else 'N/A'} - {max(c['high'] for c in m30_context) if m30_context else 'N/A'}"
            
            if candidate['direction'] == 'Short':
                if max_high > entry_price + 5.0:
                    result['decision'] = "rejected"
                    result['reason'] = "Immediate draw-down beyond acceptable SL (>$5)"
                    result['m15_m5_execution'] = f"Price spiked to {max_high} against entry {entry_price}"
                else:
                    result['decision'] = "shadow"
                    result['reason'] = "Needs TradingView confirmation for strict ICT entry logic"
                    result['m15_m5_execution'] = f"Price dropped to {min_low}, potential target reached, but needs precise Fib/OB validation"
            else:
                 if min_low < entry_price - 5.0:
                    result['decision'] = "rejected"
                    result['reason'] = "Immediate draw-down beyond acceptable SL (>$5)"
                    result['m15_m5_execution'] = f"Price dropped to {min_low} against entry {entry_price}"
                 else:
                    result['decision'] = "shadow"
                    result['reason'] = "Needs TradingView confirmation for strict ICT entry logic"
                    result['m15_m5_execution'] = f"Price pushed to {max_high}, potential target reached, but needs precise Fib/OB validation"
                    
        results.append(result)
        
    output_path = os.path.join(project_root, "hybrid/reviews/manual_replay_results/replay_result_00114_00117.json")
    with open(output_path, 'w') as f:
        json.dump(results, f, indent=2)
        
    print(f"Results written to {output_path}")

if __name__ == "__main__":
    analyze_candidates()
