import json
from datetime import datetime, timezone

def parse_time(val):
    if isinstance(val, (int, float)):
        return float(val)
    if isinstance(val, str):
        if 'T' in val:
            return datetime.strptime(val, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).timestamp()
        return float(val)
    return float(val)

def load_json(filepath):
    with open(filepath, 'r') as f:
        data = json.load(f)
        if isinstance(data, dict):
            if 't' in data and 'o' in data:
                bars = []
                for i in range(len(data['t'])):
                    bars.append({
                        'time': parse_time(data['t'][i]),
                        'open': float(data['o'][i]),
                        'high': float(data['h'][i]),
                        'low': float(data['l'][i]),
                        'close': float(data['c'][i]),
                    })
                return bars
            for k, v in data.items():
                if isinstance(v, list) and len(v) > 0 and isinstance(v[0], dict) and 'time' in v[0]:
                    return v
        return data

def get_bars_around(data, timestamp_str, hours_before=24, hours_after=12):
    target_dt = datetime.strptime(timestamp_str, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
    target_ts = target_dt.timestamp()
    
    start_ts = target_ts - (hours_before * 3600)
    end_ts = target_ts + (hours_after * 3600)
    
    bars = []
    for bar in data:
        t = parse_time(bar['time'])
        if start_ts <= t <= end_ts:
            bar_copy = bar.copy()
            bar_copy['time'] = t
            bars.append(bar_copy)
    return bars

m30_data = load_json('hybrid/data/ohlcv_M30.json')
m5_data = load_json('hybrid/data/ohlcv_M5.json')

c1 = "2026-06-30T07:45:00Z"
c2 = "2026-06-30T08:30:00Z"
c3 = "2026-06-30T11:15:00Z"

decisions = {}

# C1: Long at 07:45
# HTF Context: H1 dropped from 4070 (June 29) to 3942 (June 30 01:00) then started reversing.
# 06:00 H1 was strong bullish (3978 -> 4029) and 07:00 H1 (4029 -> 4032).
# M30 shows a bullish run from 3942 up to 4034.
# At 07:45, price is around 4030. M5 shows a dip to 4020.27 (07:50-08:00) then rebound.
# However, this looks like a momentum continuation, not a clear liquidity sweep on HTF structure.
# M30 swing low is way down at 3942, or intermediate at 3978. Price is extended.
decisions[c1] = {
    "decision": "rejected",
    "reason": "Price is extended after a massive bullish M30 run (3942 to 4034). No clear HTF pullback to a discount PD array or deep liquidity sweep at 07:45.",
    "htf_context": "H1/M30 massive bullish recovery from 3942 to 4034.",
    "m30_structure": "Bullish momentum, extended, no discount pullback.",
    "m15_m5_execution": "M5 shows minor consolidation around 4030, but entry here is chasing price.",
    "promoted_to_journal": False
}

# C2: Short at 08:30
# M30 Context: High at 07:00 is 4034.86, High at 08:00 is 4037.665.
# 08:00 M30 closed bearish at 4025.945 (Sweep of 4034.86).
# 08:30 M5 open is 4025.955. Price drops to 4013.80.
# This looks like a valid sweep of the Asian/early London high (4034.86).
# Let's check entry details. 
# M5 at 08:20 high was 4027.81, low 4020.27.
# M5 at 08:25 high 4026.865.
# At 08:30, price drops immediately.
# Let's mark as needs_more_context to check precise entry model (MSS/FVG).
decisions[c2] = {
    "decision": "needs_more_context",
    "reason": "Valid M30 liquidity sweep of 4034.86 (peaked at 4037.665) followed by bearish close. Need more detailed M1/M5 analysis for exact MSS and FVG entry.",
    "htf_context": "H1/M30 swept previous high 4034.86 and rejected.",
    "m30_structure": "Bearish rejection after sweeping local high.",
    "m15_m5_execution": "M5 shows immediate drop after 08:30. Requires M1 for precise entry validation.",
    "promoted_to_journal": False
}

# C3: Short at 11:15
# M30 Context: 11:00 M30 high is 4034.325. 11:30 M30 high is 4037.43.
# 11:15 M5: 11:10 H 4033.79. 11:15 H 4034.325. 11:20 H 4033.91. 11:45 H 4037.43.
# If Short at 11:15, price goes up to 4037.43 at 11:45 before dropping heavily to 4009 at 12:30.
# So an 11:15 entry would likely suffer drawdown or get stopped out if SL was tight above 4034.325.
# The true sweep happened at 11:45 (sweeping 4034.325).
decisions[c3] = {
    "decision": "rejected",
    "reason": "Premature entry. Price sweeps 4034.325 high later at 11:45 (reaching 4037.43) before the real drop. 11:15 entry would face drawdown or stop out.",
    "htf_context": "H1 consolidating near local highs around 4030-4037.",
    "m30_structure": "Choppy price action, sweeping highs before dropping.",
    "m15_m5_execution": "Entering at 11:15 is before the final liquidity sweep at 11:45.",
    "promoted_to_journal": False
}

results = []
results.append({
    "candidate_id": "candidate_2026-06-30T07-45-00Z_long_liquidity_sweep_reversal",
    "timestamp": c1,
    "decision": decisions[c1]["decision"],
    "reason": decisions[c1]["reason"],
    "htf_context": decisions[c1]["htf_context"],
    "m30_structure": decisions[c1]["m30_structure"],
    "m15_m5_execution": decisions[c1]["m15_m5_execution"],
    "entry": None,
    "stop": None,
    "target": None,
    "r": None,
    "promoted_to_journal": decisions[c1]["promoted_to_journal"]
})
results.append({
    "candidate_id": "candidate_2026-06-30T08-30-00Z_short_liquidity_sweep_reversal",
    "timestamp": c2,
    "decision": decisions[c2]["decision"],
    "reason": decisions[c2]["reason"],
    "htf_context": decisions[c2]["htf_context"],
    "m30_structure": decisions[c2]["m30_structure"],
    "m15_m5_execution": decisions[c2]["m15_m5_execution"],
    "entry": None,
    "stop": None,
    "target": None,
    "r": None,
    "promoted_to_journal": decisions[c2]["promoted_to_journal"]
})
results.append({
    "candidate_id": "candidate_2026-06-30T11-15-00Z_short_liquidity_sweep_reversal",
    "timestamp": c3,
    "decision": decisions[c3]["decision"],
    "reason": decisions[c3]["reason"],
    "htf_context": decisions[c3]["htf_context"],
    "m30_structure": decisions[c3]["m30_structure"],
    "m15_m5_execution": decisions[c3]["m15_m5_execution"],
    "entry": None,
    "stop": None,
    "target": None,
    "r": None,
    "promoted_to_journal": decisions[c3]["promoted_to_journal"]
})

with open('hybrid/reviews/manual_replay_results/replay_result_00725_00728.json', 'w') as f:
    json.dump(results, f, indent=2)

print("Saved replay_result_00725_00728.json")
