"""c3_live_check.py -- [2026-10-23] the LIVE ev3.exit_check (GB2 + C3 controller + X1, config.json "ev3") vs the tested C3 (ctrl_test.json)
on every trade where X1 took control + random others; each bar fed as a price path (8 steps per leg) with a forming bar."""
import gzip, json, sys, random
from collections import defaultdict
from datetime import timedelta
sys.path.insert(0, "/var/www/screener/trade/reports/playbook"); sys.path.insert(0, "/var/www/screener/trade")
import logging; logging.basicConfig(level=logging.WARNING)
import numpy as np
import v2_bar_replay as R
import r1b_setup
from exit_pepg import MODS
import ev3 as E
MODS = {**MODS, "R1B": r1b_setup}
cfg = json.load(open("/var/www/screener/trade/config.json"))["ev3"]
rows = json.load(open("ctrl_test.json"))
took = [r for r in rows if r["C3_why"] == "X1 took control"]; random.seed(3)
pick = took + random.sample([r for r in rows if r not in took], 60)
by = defaultdict(list)
for r in pick:
    by[r["day"]].append(r)
out = []
for day in sorted(by):
    d = json.load(gzip.open(R.OW / "bars" / f"bars_{day}.json.gz", "rt"))
    for r in by[day]:
        s = r["sym"]; ref = R.REF.load(day, s); fl = json.loads((R.OW / "flow" / day / f"{s}.json").read_text())
        bars = [b for b in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(b["t"]) < 390]
        M = [R.minute(b["t"]) for b in bars]; ti = M.index(r["m"]); bi = ti + 1; P = bars[bi]["o"]
        ok, info = MODS[r["setup"]].check(bars[:ti + 1], fl, ref, r["m"])
        sup = (info or {}).get("support") or P * 0.99
        stop = min(max(sup * 0.998, P * 0.96), P * 0.995)
        t0 = bars[0]["t"] - timedelta(minutes=M[0])
        ev = E.EV3(cfg); pos = {"entry_price": P, "stop_price": stop, "entry_time": bars[bi]["t"].isoformat()}
        res = None; took_live = False
        for j in range(bi, len(bars)):
            b = bars[j]
            if M[j] >= 385:
                res = (b["o"] / P - 1) * 100 - 0.2; break
            flow = [(t0 + timedelta(minutes=k), [fl["buy"][k], fl["sell"][k]]) for k in range(M[j])]
            a, c_ = (b["l"], b["h"]) if b["c"] >= b["o"] else (b["h"], b["l"])
            path = []
            for x0, x1 in ((b["o"], a), (a, c_), (c_, b["c"])):
                path += [x0 + (x1 - x0) * i / 8 for i in range(1, 9)]
            f = {**b, "h": b["o"], "l": b["o"], "c": b["o"]}
            for px in [b["o"]] + path:
                f = {**f, "h": max(f["h"], px), "l": min(f["l"], px), "c": px}
                go, why, risk = ev.exit_check(s, pos, bars[:j] + [f], px, flow)
                if ev._peak.get(s, {}).get("mode") == "X1":
                    took_live = True
                if go:
                    res = (px / P - 1) * 100 - 0.2; break
            if res is not None:
                break
        out.append((r["C3"], res if res is not None else (bars[-1]["c"] / P - 1) * 100 - 0.2, r["C3_why"] == "X1 took control", took_live, s, day))
    R.REF._CACHE.clear(); del d
a = np.array([x[0] for x in out]); b = np.array([x[1] for x in out])
print(f"{len(out)} trades ({len(took)} where the test's X1 took control): tested C3 {a.mean():+.3f}%/trade, live {b.mean():+.3f}%/trade; "
      f"same within 0.25%: {np.mean(abs(a - b) < 0.25):.0%}; X1 took control in the test {sum(x[2] for x in out)}, live {sum(x[3] for x in out)}, both {sum(x[2] and x[3] for x in out)}")
for x in sorted(out, key=lambda x: -abs(x[0] - x[1]))[:10]:
    print(f"   {x[4]} {x[5]} test {x[0]:+.2f} live {x[1]:+.2f}  X1 control test {x[2]} live {x[3]}")
