"""live_day_review.py DAY -- [2026-10-26] the user: after-close style review of the trade bot's watch list. (1) the EV3 signals the
gates blocked (from the bot log), bought anyway at the next open with the C3 exit on the real bars; (2) every watch-list stock that rose
>= 5% after it was listed: all EV3 setups replayed minute by minute (bars: Alpaca, flow: Massive trades / tick rule, refs: the bot's
data/reference), which setup came closest and why each said no."""
import json, glob, re, sys
from collections import Counter
from datetime import datetime
from zoneinfo import ZoneInfo
from pathlib import Path
sys.path.insert(0, "/var/www/screener/trade"); sys.path.insert(0, "/var/www/screener/trade/reports/open_window")
sys.path.insert(0, "/var/www/screener/trade/reports/ev3"); sys.path.insert(0, "/var/www/screener/trade/reports/playbook")
from alpaca.data.requests import StockBarsRequest
from alpaca.data.timeframe import TimeFrame
from alpaca.data.historical import StockHistoricalDataClient
from config_loader import get_env
from massive_trial import m_trades, tick_flow
import ev3 as E
from queue_test import Day
from sim_2y import sim as c3_sim
ET = ZoneInfo("America/New_York"); day = sys.argv[1] if len(sys.argv) > 1 else datetime.now(ET).date().isoformat()
TR = Path("/var/www/screener/trade"); env = get_env(); hc = StockHistoricalDataClient(env.api_key, env.secret_key)
CFG = E.EV3(json.load(open(TR / "config.json"))["ev3"]).c
hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"
listed = {}
for f in sorted(glob.glob(str(TR / f"data/candidates/{day}_scanner*.json"))):
    t = f.split("_scanner")[1].replace(".json", "").strip("_") or "0928"
    for c in json.load(open(f)):
        listed.setdefault(c["symbol"], max(0, (int(t[:2]) - 9) * 60 + int(t[2:]) - 30))
raw = hc.get_stock_bars(StockBarsRequest(symbol_or_symbols=list(listed), timeframe=TimeFrame.Minute,
                                         start=datetime.fromisoformat(day).replace(hour=9, minute=30, tzinfo=ET))).data
def bars_of(s):
    out = []
    for b in raw.get(s, []):
        t = b.timestamp.astimezone(ET); m = (t.hour - 9) * 60 + t.minute - 30
        if 0 <= m < 390:
            out.append({"t": b.timestamp, "o": b.open, "h": b.high, "l": b.low, "c": b.close, "v": b.volume, "m": m})
    return out
def ref_of(s):
    p = TR / "data" / "reference" / day / f"{s}.json"
    return json.loads(p.read_text()) if p.exists() else None
cache = {}
def load(s):
    if s not in cache:
        b = bars_of(s); fb, fs = tick_flow(m_trades(s, day)); ref = ref_of(s)
        cache[s] = Day(b, [x["m"] for x in b], {"buy": list(fb), "sell": list(fs)}, ref) if b and ref else None
    return cache[s]
log = (TR / f"logs/trade_bot_{day}.log").read_text()
print(f"=== {day}: watch list {len(listed)} stocks; EV3 log lines: BUY {log.count('[EV3] BUY')}, NO-TRADE {log.count('[EV3] NO-TRADE')}, SELL {log.count('[EV3] SELL')}")
print("\n(1) EV3 signals the gates blocked -- bought anyway at the next open, C3 exit on today's bars (0.2% cost):")
for mt in re.finditer(r"NO-TRADE (\w+): (\w+) triggered at the (\d+):(\d+) bar close ([\d.]+) -- blocked: (.*)", log):
    s, st, H, Mn, px, why = mt.groups(); m = (int(H) - 9) * 60 + int(Mn) - 30; D = load(s)
    if not D:
        print(f"   {s}: no data"); continue
    i = D.m.index(m); P = D.b[i + 1]["o"]
    ok, info = E.MODS[st].check(D.b[:i + 1], D.fl, D.ref, m, {k: v for k, v in (CFG["setups"].get(st) or {}).items() if k not in E.CONTROL_KEYS} or None)
    sup = (info or {}).get("support") or P * 0.99; stop = min(max(sup * 0.998, P * 0.96), P * 0.995)
    pl, j, wy = c3_sim(D, i + 1, P, stop, CFG["arm_pct"], "C3")
    print(f"   {s} {st} {hm(m)} buy {P:.3f} -> {hm(D.m[j])} {pl:+.2f}% [{wy}]  (live R3 setup check now: {'TRIGGER' if ok else (info or {}).get('why_not')}) | blocked by: {why}")
print("\n(2) watch-list stocks that rose >= 5% after being listed: did any EV3 setup fire (gates OFF), and why not")
runners = []
for s, lm in listed.items():
    b = [x for x in bars_of(s) if x["m"] >= lm]
    if not b: continue
    lo = b[0]; best = (0, 0, 0)
    for x in b:
        if x["l"] < lo["l"]: lo = x
        r = (x["h"] / lo["l"] - 1) * 100
        if r > best[0]: best = (r, lo["m"], x["m"])
    if best[0] >= 5: runners.append((s, lm, best))
runners.sort(key=lambda z: -z[2][0])
for s, lm, (r, a, z) in runners:
    D = load(s)
    if not D:
        print(f"   {s:5} +{r:4.1f}% ({hm(a)}->{hm(z)}) listed {hm(lm)}: no reference / data"); continue
    fired = []; why = Counter()
    for i in range(5, len(D.b) - 1):
        m = D.m[i]
        if m < lm or m >= 345: continue
        for st in ("R1A", "R1D", "R4", "R3"):
            sc = CFG["setups"].get(st) or {}
            if "atr_min" in sc:
                atr = D.ref["atr14"] / D.ref["prev_close"] * 100
                if not (sc["atr_min"] <= atr < sc["atr_max"]):
                    why[f"{st}: ATR {atr:.1f}% outside 6-10%"] += 1; continue
            ok, info = E.MODS[st].check(D.b[:i + 1], D.fl, D.ref, m, {k: v for k, v in sc.items() if k not in E.CONTROL_KEYS} or None)
            if ok: fired.append(f"{st} {hm(m)}")
            elif a <= m <= z and info.get("why_not"): why[f"{st}: {info['why_not'].split('(')[0].strip()[:40]}"] += 1
    top = "; ".join(f"{k} x{v}" for k, v in why.most_common(4))
    print(f"   {s:5} +{r:4.1f}% ({hm(a)}->{hm(z)}) listed {hm(lm)} | setups fired (no gates): {', '.join(fired[:5]) or 'NONE'} | during the rise: {top}")
print("REVIEW_DONE")
