"""[2026-10-25] live EV3.entry_check with config.json (option 3: R3 + A3 + A20 buys, others record only) vs the sim_cache replay of
'R3 alone with A3+A20' on 2024-26 library days (refs = the library reference files, tick flow)."""
import gzip, json, sys, random
from datetime import timedelta
sys.path.insert(0, "/var/www/screener/trade/reports/ev3"); 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 v2_bar_replay as R
import ev3 as E
import sim_cache as S
cfg = json.load(open("/var/www/screener/trade/config.json"))["ev3"]
C = json.load(gzip.open(S.HERE / "cache_lib.json.gz", "rt"))
for k in ("R1A", "R1D", "R1E", "R4"):
    S.CFG["setups"][k] = {**S.CFG["setups"].get(k, {}), "enabled": False}
T, _ = S.replay(C, {"R3": ["A3", "A20"]})
want = {}
for t in T:
    want.setdefault(t["day"], set()).add(t["sym"])
days = sorted(want); random.seed(5); pick = sorted(random.sample(days, 20))
OW = R.OW; L = W = same = 0
for day in pick:
    d = json.load(gzip.open(OW / "bars" / f"bars_{day}.json.gz", "rt")); got = set()
    for s in d["top30_current"]:
        fp = OW / "flow_tick" / 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(cfg)
        for i in range(len(bars) - 1):
            m = R.minute(bars[i]["t"])
            if m >= 345:
                break
            items = [(t0 + timedelta(minutes=k), [fl["buy"][k], fl["sell"][k]]) for k in range(m + 1)]
            r = ev.entry_check(s, bars[:i + 1] + [bars[i + 1]], items, ref)
            if r:
                got.add(s)
                assert r["setup"] == "R3", r["setup"]
    w = want[day]; L += len(got); W += len(w); same += len(got & w)
    print(f"{day}: live {sorted(got)} sim {sorted(w)}", flush=True)
    R.REF._CACHE.clear()
print(f"\nlive R3 buy stocks {L} vs simulated trades {W}, same {same}; only R3 ever returned as a buy")
