"""
ev3_samples.py -- [2026-10-23] the user: 10 random trades from YEAR 1 (2024-10-01..2025-09-30) of each EV3 entry module
(R1A, R1B, R3 on daily ATR 6-10%, R4 -- the setups the bot buys with from 10/26), chart with the EV3 BUY and the 1/4 GIVE-BACK sell.
Buys = giveback_2y.jsonl triggers, bought at the next open. Stop = support x 0.998 clamped 0.5-4% under the buy.
SELL (red) = the give-back as the LIVE bot does it (no look-ahead): armed once the high since the buy is +1%, then sold when
the price reaches peak - 1/4 x (peak - buy) while under the last finished close; or the stop; or 15:55.
Grey hollow mark = where the old 2-year test (with the bar-close look-ahead) sold, when different.
[v2 2026-10-23] each page now shows three exits, all without look-ahead (x1_test.sim): GB1 = give-back armed at +1% (live
now, grey), GB2 = armed at +2% (orange), X1 = stall at the top / fade into resistance, armed +2%, break-even after (red,
decided at a bar close, sold at the next open); and whether the N2+N3 no-trade gate would have blocked the buy.
    python3 ev3_samples.py [SEED]  -> ev3_samples_y1.pdf
"""
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
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
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
import r1b_setup
from exit_pepg import MODS
from x1_test import sim as xsim
MODS = {**MODS, "R1B": r1b_setup}
ET = ZoneInfo("America/New_York"); COST = 0.2
NAMES = {"R1A": "fast double bottom after a flush", "R1B": "undercut & reclaim (deep V)",
         "R3": "opening push -> first pullback (ATR 6-10%)", "R4": "runner's second leg"}
hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"


def exit_live(bars, mins, bi, P, stop, arm=1.0, g=0.25):
    """-> j, price, why, peak, level (the live EV3 exit, no look-ahead)"""
    peak = P
    for j in range(bi, len(bars)):
        b = bars[j]
        if b["l"] <= stop:
            return j, (min(stop, b["o"]) if j > bi else stop), "stop", peak, None
        gain = peak - P
        if gain >= P * arm / 100 and j > bi:
            lvl = peak - g * gain; x = min(lvl, bars[j - 1]["c"] * 0.9999)
            if b["l"] <= x:
                return j, min(x, b["o"]), "give-back", peak, lvl
        peak = max(peak, b["h"])
        if mins[j] >= 385:
            return j, b["c"], "15:55", peak, None
    return len(bars) - 1, bars[-1]["c"], "end", peak, None


def exit_test(bars, mins, bi, P, stop, arm=1.0, g=0.25):
    peak = P
    for j in range(bi, len(bars)):
        b = bars[j]
        if b["l"] <= stop:
            return j, (min(stop, b["o"]) if j > bi else stop)
        gain = peak - P
        if gain >= P * arm / 100:
            lvl = peak - g * gain
            if b["l"] <= lvl and j > bi and b["c"] < bars[j - 1]["c"]:
                return j, min(lvl, b["o"])
        peak = max(peak, b["h"])
        if mins[j] >= 385:
            return j, b["c"]
    return len(bars) - 1, bars[-1]["c"]


NT = {}
r_m = None


def main():
    seed = int(sys.argv[1]) if len(sys.argv) > 1 else 1024
    T = [json.loads(l) for l in open("/var/www/screener/trade/reports/playbook/giveback_2y.jsonl")]
    T = [t for t in T if t["day"] < "2025-10-01" and (t["setup"] in ("R1A", "R1B", "R4") or (t["setup"] == "R3" and 6 <= t["atr"] < 10))]
    picks = []
    for s in ("R1A", "R1B", "R3", "R4"):
        X = [t for t in T if t["setup"] == s]
        picks += sorted(random.Random(seed).sample(X, min(10, len(X))), key=lambda t: (t["day"], t["m"]))
    rows = []; pages = []
    global NT
    NT = {(r["day"], r["sym"], r["m"]): [n for n in ("N2", "N3") if r["f"][n]] for r in json.load(open(HERE / "notrade.json"))}
    for k, t in enumerate(picks, 1):
        day, s = t["day"], t["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]
        M = [R.minute(b["t"]) for b in bars]
        ti = M.index(t["m"]); bi = ti + 1; P = bars[bi]["o"]
        ok, info = MODS[t["setup"]].check(bars[:ti + 1], fl, ref, t["m"])
        sup = (info or {}).get("support") or P * 0.99
        stop = min(max(sup * 0.998, P * 0.96), P * 0.995)
        global r_m
        r_m = lambda e, M=None: e[4]
        ex = {}
        for v in ("GB1", "GB2", "X1"):
            pl_, why_, j_ = xsim(v, bars, M, fl, bi, P, stop)
            ex[v] = (j_, P * (1 + (pl_ + COST) / 100), why_, pl_, M[j_])
        nt_ = NT.get((day, s, t["m"]))
        pages.append((k, t, bars, M, fl, bi, P, stop, sup, info, ex, nt_))
        rows.append((t["setup"], k, s, day, hm(M[bi]), P, ex, nt_))
        R.REF._CACHE.clear(); del d
    COL = {"GB1": "#757575", "GB2": "#ef6c00", "X1": "#c62828"}
    LAB = {"GB1": "GB1 give-back +1% (live now)", "GB2": "GB2 give-back armed +2%", "X1": "X1 stall / fade, armed +2%"}
    with PdfPages(HERE / "ev3_samples_y1.pdf") as pdf:
        fig = plt.figure(figsize=(11.7, 8.3))
        fig.text(0.03, 0.965, "EV3 sample trades -- YEAR 1 (2024-10 .. 2025-09), 10 per entry module  [updated 2026-10-23]", fontsize=13, weight="bold")
        fig.text(0.03, 0.94, "No look-ahead. GB1 = 1/4 give-back armed at +1% (live now) | GB2 = armed at +2% | X1 = stall at the top / fade "
                 "into resistance, armed +2%, break-even after (decided at a bar close, sold at the next open) | 0.2% cost | "
                 "NO-TRADE = the N2+N3 gate (live from 10/26) would skip the buy", fontsize=7.2, wrap=True)
        y = 0.905
        for st in ("R1A", "R1B", "R3", "R4"):
            R_ = [r for r in rows if r[0] == st]; K = [r for r in R_ if not r[7]]
            avg = lambda X, v: sum(r[6][v][3] for r in X) / len(X) if X else 0
            fig.text(0.03, y, f"{st}  {NAMES[st]} -- 10 trades: GB1 {avg(R_, 'GB1'):+.2f}%  GB2 {avg(R_, 'GB2'):+.2f}%  X1 {avg(R_, 'X1'):+.2f}%   |   "
                     f"{len(K)} kept by N2+N3: GB1 {avg(K, 'GB1'):+.2f}%  GB2 {avg(K, 'GB2'):+.2f}%  X1 {avg(K, 'X1'):+.2f}%",
                     fontsize=8.6, weight="bold"); y -= 0.019
            for r in R_:
                e = r[6]
                fig.text(0.04, y, f"#{r[1]:<2} {r[2]:6} {r[3]} buy {r[4]} {r[5]:7.3f} | GB1 {hm(r_m(e['GB1']))} {e['GB1'][3]:+6.2f}% | "
                         f"GB2 {hm(r_m(e['GB2']))} {e['GB2'][3]:+6.2f}% | X1 {hm(r_m(e['X1']))} {e['X1'][3]:+6.2f}% [{e['X1'][2]}]"
                         + (f"  NO-TRADE ({'+'.join(r[7])})" if r[7] else ""), fontsize=6.9, family="monospace"); y -= 0.0172
            y -= 0.006
        pdf.savefig(fig); plt.close(fig)
        for (k, t, bars, M, fl, bi, P, stop, sup, info, ex, nt_) in pages:
            s, day = t["sym"], t["day"]
            tt = [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"])
            end = max(e[0] for e in ex.values())
            fig = plt.figure(figsize=(11.7, 8.3)); gs = fig.add_gridspec(3, 1, height_ratios=[1.3, 2.4, 0.8], hspace=0.28)
            a0 = fig.add_subplot(gs[0]); a1 = fig.add_subplot(gs[1]); a2 = fig.add_subplot(gs[2], sharex=a1)
            a0.plot(tt, C, color="#263238", lw=0.8); a0.plot(tt, vw, color="#7b1fa2", lw=0.8, ls="--")
            a0.axhline(bars[0]["o"], color="#1565c0", lw=0.6, ls=":"); a0.axvspan(tt[bi], tt[end], color="#ffe082", alpha=0.5)
            a0.set_title(f"#{k}  {s}  {day}   EV3 {t['setup']} ({NAMES[t['setup']]})   daily ATR {t['atr']}%   "
                         f"day {(C[-1] / bars[0]['o'] - 1) * 100:+.1f}%   GB1 {ex['GB1'][3]:+.2f}%  GB2 {ex['GB2'][3]:+.2f}%  X1 {ex['X1'][3]:+.2f}%"
                         + (f"\nNO-TRADE from 10/26: {' + '.join(nt_)} would block this buy" if nt_ else ""),
                         fontsize=9.5, loc="left", color="#b71c1c" if nt_ else "black")
            a0.tick_params(labelsize=7); a0.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M", tz=ET)); a0.grid(alpha=0.25)
            lo, hi_ = max(0, bi - 40), min(len(bars) - 1, end + 25); z = range(lo, hi_ + 1)
            a1.fill_between([tt[j] for j in z], [L[j] for j in z], [H[j] for j in z], color="#b0bec5", alpha=0.5, lw=0)
            a1.plot([tt[j] for j in z], [C[j] for j in z], color="#263238", lw=1.1, label="close")
            a1.plot([tt[j] for j in z], [vw[j] for j in z], color="#7b1fa2", lw=1, ls="--", label="VWAP")
            a1.plot([tt[bi], tt[end]], [stop, stop], color="#c62828", lw=0.9, ls=":", label=f"stop {stop:.3f} ({(1 - stop / P) * 100:.2f}% under, support {sup:.3f})")
            a1.plot([tt[bi], tt[end]], [P * 1.01] * 2, color="#9e9e9e", lw=0.6, ls=":", label=f"+1% (GB1 arms) {P * 1.01:.3f}")
            a1.plot([tt[bi], tt[end]], [P * 1.02] * 2, color="#2e7d32", lw=0.7, ls=":", label=f"+2% (GB2 / X1 arm) {P * 1.02:.3f}")
            if (info or {}).get("support_m") is not None and info["support_m"] in M:
                js = M.index(info["support_m"]); a1.scatter([tt[js]], [L[js]], marker="o", s=50, facecolor="none", edgecolor="#c62828", zorder=5)
            a1.scatter([tt[bi]], [P], marker="^", s=170, color="#1565c0", edgecolor="white", zorder=6,
                       label=f"EV3 BUY {hm(M[bi])} {P:.3f} (trigger bar {hm(t['m'])})")
            for v, sz in (("GB1", 120), ("GB2", 150), ("X1", 170)):
                j_, px_, why_, pl_, _m = ex[v]
                kw = dict(facecolor="none", edgecolor=COL[v], linewidths=1.6) if v == "GB1" else dict(color=COL[v], edgecolor="white")
                a1.scatter([tt[j_]], [px_], marker="v", s=sz, zorder=7, **kw,
                           label=f"{LAB[v]}: {hm(M[j_])} {px_:.3f} {pl_:+.2f}% [{why_}]")
            a1.legend(fontsize=6.6, loc="best", framealpha=0.9); a1.grid(alpha=0.25); plt.setp(a1.get_xticklabels(), visible=False)
            a1.tick_params(labelsize=7)
            a2.bar([tt[j] for j in z], [fl["buy"][M[j]] for j in z], width=timedelta(seconds=50), color="#43a047")
            a2.bar([tt[j] for j in z], [-fl["sell"][M[j]] for j in z], width=timedelta(seconds=50), color="#e53935")
            a2.axhline(0, color="black", lw=0.5); a2.set_ylabel("buy / sell", fontsize=7); a2.tick_params(labelsize=7)
            a2.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M", tz=ET)); a2.grid(alpha=0.25)
            pdf.savefig(fig); plt.close(fig)
    for st in ("R1A", "R1B", "R3", "R4"):
        R_ = [r for r in rows if r[0] == st]; K = [r for r in R_ if not r[7]]
        for lab, X in (("all", R_), ("kept", K)):
            if X:
                print(f"{st} {lab:4} n {len(X):2}: " + "  ".join(f"{v} {sum(r[6][v][3] for r in X) / len(X):+.2f}%" for v in ("GB1", "GB2", "X1")))
        for r in R_:
            print(f"  #{r[1]:<2} {r[2]:6} {r[3]} " + " ".join(f"{v} {r[6][v][3]:+.2f}@{hm(r_m(r[6][v]))}" for v in ("GB1", "GB2", "X1"))
                  + (f"  NO-TRADE {r[7]}" if r[7] else ""))

if __name__ == "__main__":
    main()
