"""
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.
    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
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"]


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 = []
    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)
        sj, sp, why, peak, lvl = exit_live(bars, M, bi, P, stop)
        aj, ap = exit_test(bars, M, bi, P, stop)
        pl = (sp / P - 1) * 100 - COST; apl = (ap / P - 1) * 100 - COST
        pages.append((k, t, bars, M, fl, bi, P, stop, sup, info, sj, sp, why, peak, lvl, aj, ap, pl, apl))
        rows.append((t["setup"], k, s, day, hm(M[bi]), P, hm(M[sj]), sp, why, pl, apl))
        R.REF._CACHE.clear(); del d
    with PdfPages(HERE / "ev3_samples_y1.pdf") as pdf:
        fig = plt.figure(figsize=(11.7, 8.3)); fig.text(0.04, 0.95, "EV3 sample trades -- YEAR 1 (2024-10 .. 2025-09), 10 per entry module",
                                                        fontsize=14, weight="bold")
        fig.text(0.04, 0.915, "BUY = next open after the setup's trigger bar | SELL = 1/4 give-back as the live bot does it (armed at +1%, "
                 "no look-ahead) / stop under the support / 15:55 | 0.2% cost", fontsize=8.5)
        y = 0.87
        for st in ("R1A", "R1B", "R3", "R4"):
            R_ = [r for r in rows if r[0] == st]
            avg = sum(r[9] for r in R_) / len(R_); avg_a = sum(r[10] for r in R_) / len(R_)
            fig.text(0.04, y, f"{st}  {NAMES[st]}   -- {len(R_)} trades, live give-back avg {avg:+.2f}%  "
                     f"(old test exit {avg_a:+.2f}%), wins {sum(r[9] > 0 for r in R_)}/{len(R_)}", fontsize=9.5, weight="bold"); y -= 0.02
            for r in R_:
                fig.text(0.06, y, f"#{r[1]:<2} {r[2]:6} {r[3]}  buy {r[4]} {r[5]:.2f}  ->  sell {r[6]} {r[7]:.2f} [{r[8]}]  "
                         f"{r[9]:+.2f}%   (old test {r[10]:+.2f}%)", fontsize=7.8, family="monospace"); y -= 0.0185
            y -= 0.008
        pdf.savefig(fig); plt.close(fig)
        for (k, t, bars, M, fl, bi, P, stop, sup, info, sj, sp, why, peak, lvl, aj, ap, pl, apl) 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(sj, aj)
            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}%   trade {pl:+.2f}%", fontsize=10, loc="left")
            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[sj]], [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[sj]], [P * 1.01] * 2, color="#2e7d32", lw=0.7, ls=":", label=f"+1% arms the give-back {P * 1.01:.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'])})")
            lab = f"SELL {hm(M[sj])} {sp:.3f} [{why}] {pl:+.2f}%"
            if lvl:
                lab += f" | peak {peak:.3f} (+{(peak / P - 1) * 100:.2f}%), 1/4 back = {lvl:.3f}"
            a1.scatter([tt[sj]], [sp], marker="v", s=170, color="#c62828", edgecolor="white", zorder=6, label=lab)
            if aj != sj or abs(ap - sp) > 1e-6:
                a1.scatter([tt[aj]], [ap], marker="v", s=110, facecolor="none", edgecolor="#757575", zorder=6,
                           label=f"old test sell (look-ahead) {hm(M[aj])} {ap:.3f} {apl:+.2f}%")
            a1.legend(fontsize=7, 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]
        print(f"{st}: n {len(R_)} live avg {sum(r[9] for r in R_) / len(R_):+.2f}% old {sum(r[10] for r in R_) / len(R_):+.2f}% wins {sum(r[9] > 0 for r in R_)}")
        for r in R_:
            print(f"  #{r[1]:<2} {r[2]:6} {r[3]} buy {r[4]} {r[5]:.2f} -> {r[6]} {r[7]:.2f} [{r[8]}] {r[9]:+.2f}% (old {r[10]:+.2f}%)")


if __name__ == "__main__":
    main()
