"""
ev3_dry_check.py -- [2026-10-23] weekend dry check of the LIVE EV3 code path (trade/ev3.py) before Monday 10/26:
replay past days minute by minute through EV3.entry_check exactly as monitor.py calls it (the stream's bars with a forming
last bar + the stream's per-minute day_flow keyed by minute datetimes) and compare its buys with the 2-year test's triggers
(giveback_2y.jsonl; one position per stock at a time is NOT modelled there either). Exits: EV3.exit_check fed tick-like prices
(open, high/low order, close of each bar) vs the test's giveback().
    nice -n 19 python3 ev3_dry_check.py [n_days]
"""
import gzip, json, sys, random
from datetime import timedelta
from collections import defaultdict
from pathlib import Path
sys.path.insert(0, "/var/www/screener/trade"); sys.path.insert(0, "/var/www/screener/trade/reports/playbook")
import v2_bar_replay as R
import ev3 as E
from exit_giveback import giveback

GB = Path("/var/www/screener/trade/reports/playbook/giveback_2y.jsonl")
want = defaultdict(set)
for l in open(GB):
    t = json.loads(l)
    if t["setup"] in ("R1A", "R1B", "R4") or (t["setup"] == "R3" and 6 <= t["atr"] < 10):
        want[t["day"]].add((t["sym"], t["setup"], t["m"]))
days = sorted(want)
random.seed(1026); pick = sorted(random.sample(days, int(sys.argv[1]) if len(sys.argv) > 1 else 12))
tot_live = tot_test = both = 0; xd = []
for day in pick:
    d = json.load(gzip.open(R.OW / "bars" / f"bars_{day}.json.gz", "rt")); got = set()
    for s in d["top30_current"]:
        fp = R.OW / "flow" / day / f"{s}.json"; ref = R.REF.load(day, s)
        if s not in d["symbols"] or not fp.exists() or not ref or not ref.get("atr14"):
            continue
        fl = json.loads(fp.read_text())
        bars = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]
        if len(bars) < 100:
            continue
        t0 = bars[0]["t"] - timedelta(minutes=R.minute(bars[0]["t"]))
        ev = E.EV3()
        for i in range(len(bars) - 1):
            m = R.minute(bars[i]["t"])
            if m >= 360:
                break
            items = [(t0 + timedelta(minutes=k), [fl["buy"][k], fl["sell"][k]]) for k in range(m + 1)]
            items.append((t0 + timedelta(minutes=m + 1), [0.0, 0.0]))          # the forming minute
            r = ev.entry_check(s, bars[:i + 1] + [bars[i + 1]], items, ref)
            if r:
                got.add((s, r["setup"], r["m"]))
                # exit comparison: live exit_check on tick-like prices vs the test's giveback()
                bi = i + 1; P = bars[bi]["o"]; mins = [R.minute(x["t"]) for x in bars]
                sup = r["info"].get("support") or P * 0.99
                stop = min(max(sup * 0.998, P * 0.96), P * 0.995)
                tpl, tj, twhy = giveback(bars, mins, bi, P, stop, 1.0, 0.25)
                pos = {"entry_price": P, "stop_price": stop, "entry_time": bars[bi]["t"].isoformat()}
                lpl = None
                for j in range(bi, len(bars)):
                    b = bars[j]
                    if mins[j] >= 385:
                        lpl, lwhy = (b["o"] / P - 1) * 100 - 0.2, "15:55"; break
                    seq = [b["o"], b["l"], b["h"], b["c"]] if b["c"] >= b["o"] else [b["o"], b["h"], b["l"], b["c"]]
                    forming = {**b, "h": b["o"], "l": b["o"], "c": b["o"]}
                    for px in seq:
                        forming = {**forming, "h": max(forming["h"], px), "l": min(forming["l"], px), "c": px}
                        go, why, risk = ev.exit_check(s, pos, bars[:j] + [forming], px)
                        if go:
                            lpl, lwhy = (px / P - 1) * 100 - 0.2, why.split(":")[0]; break
                    if lpl is not None:
                        break
                ev.forget(s)
                xd.append((day, s, r["setup"], round(tpl, 2), twhy, round(lpl, 2) if lpl is not None else None, lwhy if lpl is not None else "-"))
    w = want[day]; tot_live += len(got); tot_test += len(w); both += len(got & w)
    print(f"{day}: live {len(got)} test {len(w)} same {len(got & w)} | only live {sorted(got - w)[:4]} | only test {sorted(w - got)[:4]}", flush=True)
    R.REF._CACHE.clear(); del d
print(f"\nBUYS: live path {tot_live}, 2-year test {tot_test}, identical {both}")
import numpy as np
a = np.array([x[3] for x in xd]); b = np.array([x[5] for x in xd if x[5] is not None])
print(f"EXITS on the live-path buys: test giveback() {a.mean():+.3f}%/trade, live exit_check {b.mean():+.3f}%/trade (n {len(xd)})")
for x in xd[:40]:
    print("  ", x)
print("EV3DRY_DONE")
