"""
sim_trades.py -- [2026-10-23] the user: pick ~10 random trades from the simulator test (premarket/data/star_exit_setups.jsonl:
the chart-setup buys exited with Star's sells, 1 year) and show the chart with the entry and exit points.
Each page: top = the whole day (1-min close, VWAP, open, prev close) with the trade window shaded; bottom = zoom on the trade:
  BUY (triangle up) at the next open after the setup's trigger bar
  STAR SELL (red triangle down) -- what the simulator did (Star sell / noise2 holds / 3% safety stop / 15:55)
  1% TRAILING STOP sell (orange x) -- the comparison exit on the same buy
  the 3% safety stop line, the high reached after the buy, buy/sell volume bars
    python3 sim_trades.py [N] [SEED]   -> sim_trades_<seed>.pdf
"""
import gzip
import json
import random
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

ET = ZoneInfo("America/New_York")
SRC = Path("/var/www/screener/premarket/data/star_exit_setups.jsonl")
NAMES = {"R1": "retest reversal", "R1A": "fast double bottom after a flush", "R3": "opening push -> first pullback",
         "R4": "runner's second leg", "R5": "opening sell-off -> base -> breakout", "R7": "pullback in a morning uptrend",
         "R8": "first pullback after a reversal", "R9": "reversal after a selling climax"}
hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"


def trail_exit(bars, bi, P):
    stop = P * 0.99; hi = P
    for j in range(bi, len(bars)):
        b = bars[j]
        if b["l"] <= stop:
            return j, stop
        if b["h"] > hi:
            hi = b["h"]; stop = max(stop, hi * 0.99)
    return len(bars) - 1, bars[-1]["c"]


def main():
    n = int(sys.argv[1]) if len(sys.argv) > 1 else 10
    seed = int(sys.argv[2]) if len(sys.argv) > 2 else 1023
    T = [json.loads(l) for l in open(SRC)]
    picks = sorted(random.Random(seed).sample(T, n), key=lambda t: (t["day"], t["m"]))
    rows = []
    with PdfPages(HERE / f"sim_trades_{seed}.pdf") as pdf:
        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]; 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"])
            bi = next(i for i, m in enumerate(M) if m >= t["buy_m"]); si = next((i for i, m in enumerate(M) if m >= t["sell_m"]), len(M) - 1)
            P = t["buy"]; tj, tp = trail_exit(bars, bi, P); tpl = (tp / P - 1) * 100 - 0.2
            peak_j = max(range(bi, max(si, tj) + 1), key=lambda j: H[j]); peak = H[peak_j]
            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[max(si, tj)], color="#ffe082", alpha=0.5)
            a0.set_title(f"#{k}  {s}  {day}   setup {t['setup']} ({NAMES.get(t['setup'], '')})   daily ATR {t['atr']}%   "
                         f"day {(C[-1] / bars[0]['o'] - 1) * 100:+.1f}%", 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 - 30), min(len(bars) - 1, max(si, tj) + 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.axhline(t["stop"], color="#c62828", lw=0.7, ls=":", label=f"3% safety stop {t['stop']:.2f}")
            a1.scatter([tt[bi]], [P], marker="^", s=160, color="#1565c0", edgecolor="white", zorder=6, label=f"BUY {hm(t['buy_m'])} {P:.2f}")
            a1.scatter([tt[si]], [t["sell"]], marker="v", s=160, color="#c62828", edgecolor="white", zorder=6,
                       label=f"STAR SELL {hm(t['sell_m'])} {t['sell']:.2f} ({t['pl']:+.2f}%) [{t['why']}]")
            a1.scatter([tt[tj]], [tp], marker="X", s=130, color="#ef6c00", edgecolor="white", zorder=6,
                       label=f"1% TRAIL SELL {hm(M[tj])} {tp:.2f} ({tpl:+.2f}%)")
            a1.annotate(f"high after the buy {peak:.2f} ({(peak / P - 1) * 100:+.1f}%) at {hm(M[peak_j])}", (tt[peak_j], peak),
                        xytext=(0, 8), textcoords="offset points", fontsize=7.5, ha="center", color="#2e7d32")
            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)
            rows.append(f"#{k:<2} {s:6} {day} {t['setup']:4} buy {hm(t['buy_m'])} {P:.2f} | high after +{(peak / P - 1) * 100:.1f}% at {hm(M[peak_j])} | "
                        f"STAR {hm(t['sell_m'])} {t['sell']:.2f} {t['pl']:+.2f}% [{t['why']}] | 1% TRAIL {hm(M[tj])} {tp:.2f} {tpl:+.2f}%")
            R.REF._CACHE.clear()
    print("\n".join(rows))


if __name__ == "__main__":
    main()
