"""board_day.py DAY SYM [SYM..] -- [2026-10-28] run stock_board.Board on one stock-day (Alpaca bars; flow = library quote flow if the stock
is in the library that day, else Massive tick flow; premarket high from pm_history if present) -> chart board_<SYM>_<DAY>.png + printout:
the board at key minutes and every BUY SIGNAL with what happened next (max rise 15/30/60 min, max drop, up after 15 min = prediction confirmed)."""
import sys, json, gzip
from datetime import datetime
from pathlib import Path
from zoneinfo import ZoneInfo
import numpy as np
import matplotlib; matplotlib.use("Agg")
import matplotlib.pyplot as plt
TR = Path("/var/www/screener/trade"); OW = TR / "reports/open_window"
for p in (str(TR), str(OW)): sys.path.insert(0, p)
import stock_board as SB
from opening_patterns import CATALOG, BIAS_UP, BIAS_DOWN
from config_loader import get_env
from alpaca.data.requests import StockBarsRequest
from alpaca.data.timeframe import TimeFrame
from alpaca.data.historical import StockHistoricalDataClient
ET = ZoneInfo("America/New_York"); env = get_env(); hc = StockHistoricalDataClient(env.api_key, env.secret_key)
mo = lambda t: (t.astimezone(ET).hour - 9) * 60 + t.astimezone(ET).minute - 30
hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"
import os
OPT = dict(levels=os.environ.get('LEVELS', 'avg'), vwap_rising=os.environ.get('VWAP_RISING', '1') == '1', above_support=bool(os.environ.get('ABOVE_SUP')), p41_own=os.environ.get('P41_OWN') == '1', pos_band=float(os.environ['POS_BAND']) if os.environ.get('POS_BAND') else None, rule=os.environ.get('RULE', 'v1'), vwap2=os.environ.get('VWAP2', 'rising'), brk_n=int(os.environ.get('BRK_N', '2')), v2_trigger=os.environ.get('V2_TRIGGER') == '1')
day = sys.argv[1]; d0 = datetime.fromisoformat(day)
pmh = {}
pp = OW / f"pm_history/{day}.json.gz"
if pp.exists(): pmh = {r["s"]: r.get("pm_high") for r in json.load(gzip.open(pp, "rt"))["rows"]}
for sym in sys.argv[2:]:
    if os.environ.get("LIB") == "1":
        # [2026-10-29] LIB=1: the simulator's own data (library 1-min bars + library reference), so the chart shows exactly what the test saw
        sys.path.insert(0, str(TR / "reports/playbook")); import gzip as _gz, v2_bar_replay as _R
        _d = json.load(_gz.open(_R.OW / "bars" / f"bars_{day}.json.gz", "rt"))
        bars = [dict(b) for b in _R.bars_of(_d["symbols"][sym]["bars"]) if 0 <= _R.minute(b["t"]) < 390]
        for b in bars:
            if not hasattr(b["t"], "astimezone"): b["t"] = datetime.fromisoformat(str(b["t"]).replace("Z", "+00:00"))
        ref = _R.REF.load(day, sym)
    else:
        raw = hc.get_stock_bars(StockBarsRequest(symbol_or_symbols=sym, timeframe=TimeFrame.Minute, start=d0.replace(hour=9, minute=30, tzinfo=ET), end=d0.replace(hour=16, tzinfo=ET))).data[sym]
        bars = [{"t": x.timestamp, "o": x.open, "h": x.high, "l": x.low, "c": x.close, "v": x.volume} for x in raw if 0 <= mo(x.timestamp) < 390]
        ref = json.load(open(TR / f"data/reference/{day}/{sym}.json"))
    fp = OW / f"flow/{day}/{sym}.json"
    if fp.exists(): fl = json.loads(fp.read_text()); src = "quote flow"
    else:
        from massive_trial import m_trades, tick_flow
        fb_, fs_ = tick_flow(m_trades(sym, day)); fl = {"buy": list(fb_), "sell": list(fs_)}; src = "tick flow"
    B = SB.Board(ref["prev_close"], ref["atr14"], bars[0]["o"], pm_high=pmh.get(sym), vpm=ref.get("vol_per_min"), **OPT); C = {mo(b["t"]): b for b in bars}; rows = []
    for i, b in enumerate(bars):
        t = mo(b["t"])
        if t > 135: break
        rows.append(B.update(b, t, fl["buy"][t], fl["sell"][t]))
    R = B.R
    print(f"\n=== {sym} {day} | {dict(GU='GAP UP', GD='GAP DOWN', FLAT='FLAT')[R.ctx]} {R.gap:+.1f}% | premarket high {pmh.get(sym) or 'n/a'} | flow: {src}")
    for r in rows:
        if r["new"] or r["buy"]:
            pats = ", ".join(f"#{p}" for p in r["new"])
            print(f"   {hm(r['t'])} {r['c']:7.2f} | res {r['res']:.2f} sup {r['sup']:.2f} (range {r['range_pct']:.1f}%, pos {r['pos']:.2f}) | vol acc {r['vacc']} "
                  f"| buy 3m/15m {r['s3']:.0%}/{r['s15']:.0%} | vs VWAP {r['vs_vwap']:+.1f}% | {pats:12} | {r['state']}")
    res_buys = []
    for bb in B.buys:
        t = bb["t"]; nb = [C[m] for m in range(t + 1, t + 61) if m in C]
        if not nb: continue
        P = nb[0]["o"]; rr = lambda n: (max(x["h"] for x in nb[:n]) / P - 1) * 100
        c15 = (nb[min(14, len(nb) - 1)]["c"] / P - 1) * 100; d30 = (min(x["l"] for x in nb[:30]) / P - 1) * 100
        res_buys.append((t, bb["pid"], P, rr(15), rr(30), rr(60), d30, c15))
        print(f"   >>> BUY {hm(t + 1)} @ {P:.2f} (#{bb['pid']} {CATALOG[bb['pid']][1]}) -> max rise 15m {rr(15):+.2f}% 30m {rr(30):+.2f}% 60m {rr(60):+.2f}% "
              f"| max drop 30m {d30:+.2f}% | 15 min later {c15:+.2f}% -> prediction {'CONFIRMED' if c15 > 0 else 'NOT confirmed'}")
    if not B.buys: print("   >>> no buy signal")
    # chart
    W = [b for b in bars if mo(b["t"]) <= 180]; M = np.array([mo(b["t"]) for b in W]); o, h, l, c, v = (np.array([b[k] for b in W]) for k in "ohlcv")
    fig = plt.figure(figsize=(18, 11)); gs = fig.add_gridspec(3, 2, width_ratios=[2.7, 1], height_ratios=[4, 1.2, 1.1], wspace=0.04, hspace=0.06)
    a = fig.add_subplot(gs[0, 0]); a2 = fig.add_subplot(gs[1, 0], sharex=a); a3 = fig.add_subplot(gs[2, 0], sharex=a); tx = fig.add_subplot(gs[:, 1]); tx.axis("off")
    col = np.where(c >= o, "#1a9850", "#d73027"); a.vlines(M, l, h, color=col, lw=0.9); a.bar(M, np.maximum(abs(c - o), (h.max() - l.min()) * 0.002), bottom=np.minimum(o, c), color=col, width=0.8)
    T = [r["t"] for r in rows]
    a.step(T, [r["res"] for r in rows], where="post", color="#c62828", lw=1.6, label="resistance (averaged swing highs)")
    a.step(T, [r["sup"] for r in rows], where="post", color="#1565c0", lw=1.6, label="support (averaged swing lows)")
    a.plot(T, [r["vwap"] for r in rows], color="#7b3294", lw=1.1, ls="--", label="VWAP"); a.axhline(R.pc, color="gray", ls=":", lw=1, label=f"prev close {R.pc:.2f}")
    if pmh.get(sym): a.axhline(pmh[sym], color="#ef6c00", ls=":", lw=1, label=f"premarket high {pmh[sym]:.2f}")
    for r in rows:
        for pid in r["new"]:
            clr = "#1a9850" if pid in BIAS_UP else "#d73027" if pid in BIAS_DOWN else "#777"
            a.annotate(str(pid), (r["t"], r["c"]), xytext=(0, -26), textcoords="offset points", ha="center", fontsize=7.5, color="white", bbox=dict(boxstyle="circle,pad=0.2", fc=clr, ec="none"))
    for t, pid, P, r15, r30, r60, d30, c15 in res_buys:
        a.scatter([t + 1], [P], marker="^", s=220, color="#00c853", edgecolor="k", zorder=7)
        a.annotate(f"BUY {hm(t + 1)}\n+{r60:.1f}% max 60m", (t + 1, P), xytext=(-40, 30), textcoords="offset points", fontsize=9, fontweight="bold", color="#1b5e20",
                   bbox=dict(boxstyle="round", fc="white", ec="#1b5e20"), arrowprops=dict(arrowstyle="->", color="#1b5e20"))
    a.axvline(120, color="#bbb", ls=":", lw=1); a.set_title(f"STOCK BOARD {sym} {day} | {dict(GU='GAP UP', GD='GAP DOWN', FLAT='FLAT')[R.ctx]} {R.gap:+.1f}% | "
                                                           f"circles = patterns (green bullish / red bearish), green triangle = BUY signal", loc="left", fontsize=10.5)
    a.legend(loc="upper left", fontsize=8); a.grid(alpha=0.25)
    a2.plot(T, [r["s3"] * 100 for r in rows], color="#2166ac", lw=1, label="buy share 3 min"); a2.plot(T, [r["s15"] * 100 for r in rows], color="k", lw=1.5, label="buy share 15 min")
    a2.axhline(50, color="gray", lw=0.7); a2.set_ylim(0, 100); a2.legend(loc="upper left", fontsize=8); a2.grid(alpha=0.25)
    a3.bar(M, v, color=col, width=0.85); a3b = a3.twinx(); a3b.plot(T, [r["vacc"] or np.nan for r in rows], color="#ef6c00", lw=1.1); a3b.axhline(1, color="#ef6c00", ls=":", lw=0.8)
    a3b.set_ylabel("vol accel (orange)", fontsize=8); a3.set_xticks(range(0, 181, 15)); a3.set_xticklabels([hm(x) for x in range(0, 181, 15)])
    for ax_ in (a, a2): plt.setp(ax_.get_xticklabels(), visible=False)
    y = 0.99; tx.text(0, y, "BOARD AT EACH EVENT", fontsize=11, fontweight="bold", va="top"); y -= 0.04
    for r in rows:
        if (r["new"] or r["buy"]) and y > 0.05:
            tx.text(0, y, f"{hm(r['t'])} {r['c']:.2f}  {r['state'][:40]}", fontsize=8.5, va="top", color="#1b5e20" if r["buy"] else "#000", fontweight="bold" if r["buy"] else "normal")
            tx.text(0, y - 0.022, f"   res {r['res']:.2f} sup {r['sup']:.2f} pos {r['pos']:.2f} | vol {r['vacc']} | 3m/15m {r['s3']:.0%}/{r['s15']:.0%} | VWAP {r['vs_vwap']:+.1f}%", fontsize=7.5, va="top", color="#444")
            y -= 0.05
    out = TR / f"reports/ev3/board_{sym}_{day}{os.environ.get('SUFFIX', '')}.png"; plt.savefig(out, dpi=95, bbox_inches="tight"); plt.close(); print("   chart:", out)
