import json
import os
import bisect
from datetime import datetime, timezone

def load_json(filepath):
    with open(filepath) as f:
        return json.load(f)

d_ohlcv_file = load_json("/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026/hybrid/data/ohlcv_D.json")
m30_ohlcv_file = load_json("/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026/hybrid/data/ohlcv_M30.json")

d_ohlcv = d_ohlcv_file.get("bars", d_ohlcv_file)
m30_ohlcv = m30_ohlcv_file.get("bars", m30_ohlcv_file)

def dt_to_sec(dt_str):
    if dt_str.endswith("Z"):
        return int(datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).timestamp())
    else:
        return int(dt_str)

d_times = [dt_to_sec(b['time']) for b in d_ohlcv]
m30_times = [dt_to_sec(b['time']) for b in m30_ohlcv]

def get_bars_around(ohlcv_data, times, timestamp_str, lookback, lookforward):
    t_sec = dt_to_sec(timestamp_str)
    idx = bisect.bisect_left(times, t_sec)
    
    start_idx = max(0, idx - lookback)
    end_idx = min(len(ohlcv_data), idx + lookforward + 1)
    
    return ohlcv_data[start_idx:end_idx], idx - start_idx

def analyze(candidate):
    t = candidate["timestamp"]
    d_bars, d_idx = get_bars_around(d_ohlcv, d_times, t, 3, 1)
    m30_bars, m30_idx = get_bars_around(m30_ohlcv, m30_times, t, 10, 5)
    
    htf_summary = f"D closes around {d_bars[d_idx]['close'] if d_idx < len(d_bars) else 'N/A'}"
    
    return {
        "candidate_id": candidate["candidate_id"],
        "timestamp": t,
        "decision": "needs_more_context",
        "reason": "Autonomous batch defaults to needs_more_context without visual TradingView verification",
        "htf_context": htf_summary,
        "m30_structure": f"M30 structure visible but requires visual TV review.",
        "m15_m5_execution": "Awaiting manual replay execution evidence",
        "entry": None,
        "stop": None,
        "target": None,
        "r": None,
        "promoted_to_journal": False
    }

manifest = load_json("/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026/hybrid/reviews/manual_replay_readiness_manifest.json")
items = manifest["manual_replay_items"][595:598]

results = [analyze(i) for i in items]
out_path = "/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026/hybrid/reviews/manual_replay_results/replay_result_00595_00598.json"
os.makedirs("/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026/hybrid/reviews/manual_replay_results", exist_ok=True)
with open(out_path, "w") as f:
    json.dump(results, f, indent=2)

progress = load_json("/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026/hybrid/reviews/manual_replay_progress.json")
progress["cursor"]["next_index"] = 598
progress["cursor"]["processed_count"] += 3
progress["cursor"]["needs_more_context_count"] += 3
progress["cursor"]["last_candidate_id"] = items[-1]["candidate_id"]
progress["cursor"]["last_updated"] = datetime.now(timezone.utc).isoformat()
progress["runs"].append({"timestamp": progress["cursor"]["last_updated"], "batch": "00595_00598", "count": 3})

with open("/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026/hybrid/reviews/manual_replay_progress.json", "w") as f:
    json.dump(progress, f, indent=2)

print(out_path)
