"""group_charts.py -- [2026-10-25] the user (priority): cover every pattern style -- for each situation know WHEN to buy. Practice
charts per pattern group from the 2-year swings study (reports/ev3/swings.json), rises no setup caught, for the user to mark the
right entry (or "no entry"). Each page: the whole day (1-min bars, VWAP, open, previous close / low), the rise shaded (low L ->
high H), 15 bars of context table; bottom: buy / sell volume per minute.
    python3 group_charts.py G8 [N=15] [SEED]  -> groups/<G>_practice.pdf + groups/<G>_practice.json"""
import gzip, json, random, sys
from datetime import timedelta
from pathlib import Path
from zoneinfo import ZoneInfo
import matplotlib; matplotlib.use("Agg")
import matplotlib.dates as mdates, matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
sys.path.insert(0, "/var/www/screener/trade/reports/playbook"); sys.path.insert(0, "/var/www/screener/trade")
import v2_bar_replay as R
HERE = Path(__file__).resolve().parent; ET = ZoneInfo("America/New_York")
hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"
G = sys.argv[1]; N = int(sys.argv[2]) if len(sys.argv) > 2 else 15; seed = int(sys.argv[3]) if len(sys.argv) > 3 else 2510
X = [x for x in json.load(open("/var/www/screener/trade/reports/ev3/swings.json")) if x["group"].startswith(G + " ") and not x["setups"] and 4 <= x["rise"] <= 10 and x["dur"] >= 10 and x["win_end"] - x["low_m"] >= 3]
random.seed(seed); seen = set(); pick = []
for x in random.sample(X, len(X)):
    if (x["day"], x["sym"]) in seen or x["day"] in {p["day"] for p in pick}:
        continue
    seen.add((x["day"], x["sym"])); pick.append(x)
    if len(pick) == N:
        break
pick.sort(key=lambda x: x["day"])
with PdfPages(HERE / "groups" / f"{G}_practice.pdf") as pdf:
    for k, x in enumerate(pick, 1):
        d = json.load(gzip.open(R.OW / "bars" / f"bars_{x['day']}.json.gz", "rt")); s = x["sym"]
        b = [y for y in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(y["t"]) < 390]
        fl = json.loads((R.OW / "flow" / x["day"] / f"{s}.json").read_text()); ref = R.REF.load(x["day"], s) or {}
        M = [R.minute(y["t"]) for y in b]; tt = [y["t"].astimezone(ET) for y in b]
        pv = cv = 0.0; vw = []
        for y in b:
            pv += (y["h"] + y["l"] + y["c"]) / 3 * y["v"]; cv += y["v"]; vw.append(pv / cv)
        a = M.index(x["low_m"]); h = M.index(x["high_m"])
        fig = plt.figure(figsize=(11.7, 8.3)); gs = fig.add_gridspec(2, 1, height_ratios=[3, 1], hspace=0.12)
        a1 = fig.add_subplot(gs[0]); a2 = fig.add_subplot(gs[1], sharex=a1)
        for i, y in enumerate(b):
            col = "#2e7d32" if y["c"] >= y["o"] else "#c62828"
            a1.plot([tt[i], tt[i]], [y["l"], y["h"]], color=col, lw=0.6); a1.plot([tt[i], tt[i]], [y["o"], y["c"]], color=col, lw=2)
        a1.plot(tt, vw, color="#7b1fa2", lw=1.1, ls="--", label="VWAP")
        a1.axhline(b[0]["o"], color="#1565c0", lw=0.7, ls=":", label=f"open {b[0]['o']}")
        if ref.get("prev_close"):
            a1.axhline(ref["prev_close"], color="#9e9e9e", lw=0.8, ls=":", label=f"prev close {ref['prev_close']}")
        if ref.get("prev_low"):
            a1.axhline(ref["prev_low"], color="#ef6c00", lw=0.6, ls=":", label=f"prev low {ref['prev_low']}")
        a1.axvspan(tt[a], tt[h], color="#c8e6c9", alpha=0.45)
        a1.annotate(f"L {b[a]['c']} {hm(M[a])}", (tt[a], b[a]["l"]), xytext=(0, -14), textcoords="offset points", ha="center", fontsize=8, color="#c62828", weight="bold")
        a1.annotate(f"H {b[h]['c']} {hm(M[h])} (+{x['rise']:.1f}%)", (tt[h], b[h]["h"]), xytext=(0, 6), textcoords="offset points", ha="center", fontsize=8, color="#2e7d32", weight="bold")
        a1.set_title(f"#{k}  {s}  {x['day']}   {x['group']}   gap {x['gap']:+.1f}%  ATR {x['atr']:.1f}%   at the low: {x['vs_vwap']:+.1f}% vs VWAP, "
                     f"{x['vs_open']:+.1f}% vs open, buy share 15m {x['bs15'] if x['bs15'] is None else round(x['bs15'] * 100)}%", fontsize=9, loc="left")
        a1.legend(fontsize=7, loc="upper left"); a1.grid(alpha=0.25); plt.setp(a1.get_xticklabels(), visible=False); a1.tick_params(labelsize=7)
        a2.bar(tt, [fl["buy"][m] for m in M], width=timedelta(seconds=50), color="#43a047"); a2.bar(tt, [-fl["sell"][m] for m in M], width=timedelta(seconds=50), color="#e53935")
        a2.axhline(0, color="black", lw=0.5); a2.axvspan(tt[a], tt[h], color="#c8e6c9", alpha=0.45); a2.set_ylabel("buy / sell", fontsize=7)
        a2.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M", tz=ET)); a2.tick_params(labelsize=7); a2.grid(alpha=0.25)
        pdf.savefig(fig); plt.close(fig)
        R.REF._CACHE.clear()
json.dump(pick, open(HERE / "groups" / f"{G}_practice.json", "w"), indent=0)
for k, x in enumerate(pick, 1):
    print(f"#{k:<2} {x['sym']:6} {x['day']}  low {hm(x['low_m'])} -> high {hm(x['high_m'])}  +{x['rise']:.1f}%  gap {x['gap']:+.1f}%  vwap {x['vs_vwap']:+.1f}%  open {x['vs_open']:+.1f}%")
