"""
practice_r1.py -- [2026-10-22] run the user's R1 setup (r1_setup.py) on the 20 practice stock-days (practice_<seed>.json)
and draw where it triggers. A trigger at minute m (bar close) = buy at the next open; outcome: +1% / +2% reached before -1%
within 60 min, best price in 60 min, and where it would be at +30 / +60 min.
    python3 practice_r1.py [SEED]   -> practice_<seed>_r1.pdf (summary page + 20 charts)
"""
import gzip
import json
import sys
from datetime import timedelta
from pathlib import Path
from zoneinfo import ZoneInfo

import matplotlib
matplotlib.use("Agg")
import matplotlib.dates as mdates  # noqa: E402
import matplotlib.pyplot as plt  # noqa: E402
from matplotlib.backends.backend_pdf import PdfPages  # noqa: E402

HERE = Path(__file__).resolve().parent
sys.path.insert(0, "/var/www/screener/trade/reports/playbook"); sys.path.insert(0, "/var/www/screener/trade")
import v2_bar_replay as R  # noqa: E402
import r1_setup  # noqa: E402
import r2_setup  # noqa: E402
import r3_setup  # noqa: E402
import r1a_setup  # noqa: E402
import r4_setup  # noqa: E402
import r5_setup  # noqa: E402
import r6_setup  # noqa: E402
import r7_setup  # noqa: E402
import r8_setup  # noqa: E402
import r9_setup  # noqa: E402
SETUPS = [("R1", r1_setup, "#6a1b9a", "*"), ("R1A", r1a_setup, "#ad1457", "X"), ("R2", r2_setup, "#ef6c00", "D"), ("R3", r3_setup, "#00838f", "P"), ("R4", r4_setup, "#2e7d32", "h"), ("R5", r5_setup, "#1565c0", "s"), ("R6", r6_setup, "#5d4037", "v"), ("R7", r7_setup, "#c2185b", "^"), ("R8", r8_setup, "#f9a825", "<"), ("R9", r9_setup, "#424242", ">")]
from practice_charts import zones  # noqa: E402

ET = ZoneInfo("America/New_York")
hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"


def outcome(bars, i):
    P = bars[i + 1]["o"]; res = "neither"
    for j in range(i + 1, min(i + 61, len(bars))):
        if bars[j]["l"] <= P * 0.99:
            res = "-1% first"; break
        if bars[j]["h"] >= P * 1.02:
            res = "+2% first"; break
        if bars[j]["h"] >= P * 1.01 and res == "neither":
            res = "+1% (then?)"
    if res == "+1% (then?)":
        res = "+1% before -1%"
    best = max(b["h"] for b in bars[i + 1:min(i + 61, len(bars))])
    return P, res, (best / P - 1) * 100


def main():
    seed = int(sys.argv[1]) if len(sys.argv) > 1 else 2210
    picks = json.load(open(HERE / f"practice_{seed}.json"))
    rows, pages = [], []
    for p in picks:
        day, s = p["day"], p["sym"]
        d = json.load(gzip.open(R.OW / "bars" / f"bars_{day}.json.gz", "rt"))
        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]
        trig = []
        for nm, mod, col_, mk in SETUPS:
            last = -9999
            for i in range(len(bars) - 1):
                m = R.minute(bars[i]["t"])
                if m - last < mod.DEFAULTS["cooldown"]:
                    continue
                ok, info = mod.check(bars[:i + 1], fl, ref, m)
                if ok:
                    P, res, best = outcome(bars, i)
                    trig.append({"setup": nm, "col": col_, "mk": mk, "i": i, "m": m, "P": P, "res": res, "best": best, **info}); last = m
                    rows.append({"n": p["n"], "sym": s, "day": day, "setup": nm, "t": hm(m + 1), "buy": P, "res": res, "best": best,
                                 "support": info["support"], "sup_t": hm(info["support_m"]), "room": info["room"]})
        pages.append((p, d, ref, fl, bars, trig))
        R.REF._CACHE.clear()
    with PdfPages(HERE / f"practice_{seed}_setups.pdf") as pdf:
        fig = plt.figure(figsize=(11.7, 8.3)); fig.text(0.04, 0.95, f"R1 retest reversal / R2 calm-stock base -- {len(rows)} triggers on the 20 practice stock-days (seed {seed})",
                                                         fontsize=13, weight="bold")
        fig.text(0.04, 0.915, "Trigger = bar close; buy at the next open. Outcome within 60 min: +2% first / +1% before -1% / -1% first / neither.", fontsize=8.5)
        y = 0.88
        for r in rows:
            col = "#2e7d32" if r["res"].startswith("+") else "#c62828" if r["res"].startswith("-") else "#555555"
            fig.text(0.04, y, f"{r['setup']}  #{r['n']:<3} {r['sym']:6} {r['day']}  {r['t']}  buy {r['buy']:.2f}  support {r['support']:.2f} ({r['sup_t']})  "
                              f"room {r['room']:.1f}%  ->", fontsize=8, family="monospace")
            fig.text(0.80, y, f"{r['res']}  (best +{r['best']:.1f}%)", fontsize=8, family="monospace", color=col)
            y -= 0.03
            if y < 0.05:
                break
        no = [p['n'] for p, *_rest, trig in [(x[0], x[5]) for x in pages] if not trig]
        fig.text(0.04, max(y - 0.02, 0.02), f"No R1 trigger on charts: {', '.join('#' + str(x) for x in no)}", fontsize=8)
        pdf.savefig(fig); plt.close(fig)
        for p, d, ref, fl, bars, trig in pages:
            t = [b["t"].astimezone(ET) for b in bars]; C = [b["c"] for b in bars]; H = [b["h"] for b in bars]; L = [b["l"] for b in bars]
            pv = cv = 0.0; vw = []
            for b in bars:
                pv += (b["h"] + b["l"] + b["c"]) / 3 * b["v"]; cv += b["v"]; vw.append(pv / cv if cv else b["c"])
            z = zones(bars)
            M = [R.minute(b["t"]) for b in bars]
            fig = plt.figure(figsize=(11.7, 8.3)); gs = fig.add_gridspec(2, 1, height_ratios=[3.2, 1.2], hspace=0.08)
            a1 = fig.add_subplot(gs[0]); a2 = fig.add_subplot(gs[1], sharex=a1)
            a1.fill_between(t, L, H, color="#b0bec5", alpha=0.45, lw=0)
            a1.plot(t, C, color="#263238", lw=1.0); a1.plot(t, vw, color="#7b1fa2", lw=1.0, ls="--", label="VWAP")
            a1.axhline(bars[0]["o"], color="#1565c0", lw=0.8, ls=":", label="open")
            if ref.get("prev_close"):
                a1.axhline(ref["prev_close"], color="#ef6c00", lw=0.8, ls=":", label="prev close")
            z2 = [i for i in z if z[i] == 2]
            a1.scatter([t[i] for i in z2], [C[i] for i in z2], s=7, color="#2e7d32", alpha=0.6, label="+2% before -1% zone")
            for tr in trig:
                i = tr["i"]
                si = next((q for q, mm in enumerate(M) if mm >= tr["support_m"]), 0)
                a1.hlines(tr["support"], t[si], t[i], color=tr["col"], lw=0.9)
                col = "#2e7d32" if tr["res"].startswith("+") else "#c62828" if tr["res"].startswith("-") else "#555555"
                a1.scatter([t[i]], [C[i]], marker=tr["mk"], s=230 if tr["mk"] == "*" else 90, color=tr["col"], edgecolor="white", zorder=7)
                a1.annotate(f"{tr['setup']} {hm(tr['m'] + 1)} buy {tr['P']:.2f}\n{tr['res']} (best +{tr['best']:.1f}%)", (t[i], C[i]),
                            xytext=(8, -26), textcoords="offset points", fontsize=7.5, color=col,
                            bbox=dict(boxstyle="round,pad=0.2", fc="white", ec=col, lw=0.6))
            a1.set_title(f"#{p['n']}  {p['sym']}  {p['day']}   day {p['day_pct']:+.1f}%   ATR {p['atr']}%   R1 triggers: {sum(1 for x in trig if x['setup'] == 'R1')}, R2 triggers: {sum(1 for x in trig if x['setup'] == 'R2')}", loc="left", fontsize=10)
            a1.legend(fontsize=7, loc="upper left"); a1.grid(alpha=0.25); plt.setp(a1.get_xticklabels(), visible=False)
            buy = [fl["buy"][m] for m in M]; sell = [fl["sell"][m] for m in M]
            a2.bar(t, buy, width=timedelta(seconds=50), color="#43a047"); a2.bar(t, [-x for x in sell], width=timedelta(seconds=50), color="#e53935")
            a2.axhline(0, color="black", lw=0.5); a2.grid(alpha=0.25); a2.set_ylabel("buy / sell", fontsize=7)
            a2.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M", tz=ET))
            for a in (a1, a2):
                a.tick_params(labelsize=7)
            pdf.savefig(fig); plt.close(fig)
    for r in rows:
        print(f"{r['setup']} #{r['n']:<3} {r['sym']:6} {r['day']} {r['t']} buy {r['buy']:.2f} support {r['support']:.2f} ({r['sup_t']}) "
              f"room {r['room']:.1f}% -> {r['res']} best +{r['best']:.1f}%")
    print(len(rows), "triggers")


if __name__ == "__main__":
    main()
