"""loser_chart.py -- [2026-10-24] the user: one LOSER from the 2016-2018 simulation (sim10y_first2y) as a chart with the entry
and exit + a table of the indicators minute by minute.  python3 loser_chart.py DAY SYM  -> loser_<SYM>_<DAY>.pdf"""
import json, sys
from datetime import timedelta
from pathlib import Path
from zoneinfo import ZoneInfo
import gzip
import matplotlib; matplotlib.use("Agg")
import matplotlib.dates as mdates, matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE)); 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 ev3 as E
from queue_test import Day
from sim_2y import sim as exit_sim
ET = ZoneInfo("America/New_York"); OW = Path("/var/www/screener/trade/reports/open_window")
hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"
day, sym = sys.argv[1], sys.argv[2]
t = [x for x in json.load(open(HERE / "sim10y_first2y.json"))["trades"] if x["day"] == day and x["sym"] == sym][0]
top = json.loads((HERE / "top30_10y" / f"{day}.json").read_text()); ref = top["ref"][sym]
bars = [x for x in R.bars_of(json.load(gzip.open(OW / "bars10y" / day[:4] / f"{day}.json.gz", "rt"))["bars"][sym]) if 0 <= R.minute(x["t"]) < 390]
fl = json.loads((OW / "flow_tick" / day / f"{sym}.json").read_text())
M = [R.minute(b["t"]) for b in bars]; D = Day(bars, M, fl, ref)
bi = M.index(t["buy_m"]); ti = bi - 1; P = bars[bi]["o"]
cfg = E.EV3(json.load(open("/var/www/screener/trade/config.json"))["ev3"]).c; sc = cfg["setups"].get(t["setup"]) or {}
ok, info = E.MODS[t["setup"]].check(bars[:ti + 1], fl, ref, M[ti], {k: v for k, v in sc.items() if k not in E.CONTROL_KEYS} or None)
sup = info.get("support") or P * 0.99
stop = min(max(sup * 0.998, P * 0.96), P * 0.995)
pl, j, why = exit_sim(D, bi, P, stop, cfg["arm_pct"], "C3")
xp = P * (1 + (pl + 0.2) / 100)
tt = [b["t"].astimezone(ET) for b in bars]; vw = D.vw
fb, fs = fl["buy"], fl["sell"]
bs = lambda m, n: (lambda B, S: B / (B + S) if B + S else float("nan"))(sum(fb[max(0, m - n + 1):m + 1]), sum(fs[max(0, m - n + 1):m + 1]))
atrp = ref["atr14"] / ref["prev_close"] * 100
with PdfPages(HERE / f"loser_{sym}_{day}.pdf") as pdf:
    fig = plt.figure(figsize=(11.7, 8.3)); gs = fig.add_gridspec(3, 1, height_ratios=[1.2, 2.4, 0.9], hspace=0.3)
    a0, a1 = fig.add_subplot(gs[0]), fig.add_subplot(gs[1]); a2 = fig.add_subplot(gs[2], sharex=a1)
    a0.plot(tt, [b["c"] for b in bars], 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[j], color="#ffcdd2", alpha=0.6)
    a0.set_title(f"LOSER  {sym}  {day}   EV3 {t['setup']}   daily ATR {atrp:.1f}%   prev close {ref['prev_close']}  prev low {ref['prev_low']}   "
                 f"open {bars[0]['o']} ({(bars[0]['o'] / ref['prev_close'] - 1) * 100:+.1f}% gap)   trade {pl:+.2f}% [{why}]", fontsize=9.5, loc="left")
    a0.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M", tz=ET)); a0.tick_params(labelsize=7); a0.grid(alpha=0.25)
    lo, hi = 0, min(len(bars) - 1, j + 30); z = range(lo, hi + 1)
    for k in z:
        b = bars[k]; col = "#2e7d32" if b["c"] >= b["o"] else "#c62828"
        a1.plot([tt[k], tt[k]], [b["l"], b["h"]], color=col, lw=0.8)
        a1.plot([tt[k], tt[k]], [b["o"], b["c"]], color=col, lw=3)
    a1.plot([tt[k] for k in z], [vw[k] for k in z], color="#7b1fa2", lw=1, ls="--", label=f"VWAP")
    a1.axhline(ref["prev_close"], color="#9e9e9e", lw=0.7, ls=":", label=f"prev close {ref['prev_close']}")
    a1.plot([tt[bi], tt[j]], [stop, stop], color="#c62828", lw=1, ls=":", label=f"stop {stop:.3f} (support {sup:.3f} x0.998, {(1 - stop / P) * 100:.2f}% under)")
    a1.plot([tt[bi], tt[j]], [P * 1.02] * 2, color="#2e7d32", lw=0.8, ls=":", label=f"+2% (give-back / C3 arms) {P * 1.02:.3f}")
    if info.get("support_m") is not None and info["support_m"] in M:
        ks = M.index(info["support_m"]); a1.scatter([tt[ks]], [bars[ks]["l"]], s=70, facecolor="none", edgecolor="#c62828", zorder=5, label=f"support bar {hm(info['support_m'])}")
    a1.scatter([tt[bi]], [P], marker="^", s=180, color="#1565c0", edgecolor="white", zorder=6, label=f"BUY {hm(M[bi])} {P:.3f} (trigger bar {hm(M[ti])})")
    a1.scatter([tt[j]], [xp], marker="v", s=180, color="#c62828", edgecolor="white", zorder=6, label=f"SELL {hm(M[j])} {xp:.3f} {pl:+.2f}% [{why}]")
    hi_after = max(range(bi, j + 1), key=lambda k: bars[k]["h"])
    a1.annotate(f"best after the buy {bars[hi_after]['h']} ({(bars[hi_after]['h'] / P - 1) * 100:+.2f}%) {hm(M[hi_after])}", (tt[hi_after], bars[hi_after]["h"]),
                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[k] for k in z], [fb[M[k]] for k in z], width=timedelta(seconds=50), color="#43a047", label="buy volume (tick rule)")
    a2.bar([tt[k] for k in z], [-fs[M[k]] for k in z], width=timedelta(seconds=50), color="#e53935", label="sell volume")
    a2.axhline(0, color="black", lw=0.5); a2.legend(fontsize=6.5, loc="upper right"); a2.tick_params(labelsize=7); a2.grid(alpha=0.25)
    a2.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M", tz=ET))
    pdf.savefig(fig); plt.close(fig)
    # table pages
    rows = []
    for k in range(0, min(len(bars), j + 8)):
        b = bars[k]; m = M[k]
        av = sum(x["v"] for x in bars[max(0, k - 15):k]) / max(1, min(15, k)) if k else b["v"]
        tag = "BUY" if k == bi else "TRIGGER" if k == ti else "SELL" if k == j else ("support" if m == info.get("support_m") else "")
        rows.append([hm(m), f"{b['o']:.3f}", f"{b['h']:.3f}", f"{b['l']:.3f}", f"{b['c']:.3f}", f"{b['v']:,.0f}", f"{b['v'] / av:.2f}x" if av else "-",
                     f"{fb[m]:,.0f}", f"{fs[m]:,.0f}", f"{bs(m, 1):.0%}", f"{bs(m, 5):.0%}", f"{bs(m, 15):.0%}", f"{vw[k]:.3f}",
                     f"{(b['c'] / vw[k] - 1) * 100:+.2f}%", f"{(b['c'] / bars[0]['o'] - 1) * 100:+.2f}%", f"{(b['c'] / P - 1) * 100:+.2f}%" if k >= bi else "", tag])
    head = ["time", "open", "high", "low", "close", "volume", "vol/avg15", "buy vol", "sell vol", "buy% 1m", "buy% 5m", "buy% 15m", "VWAP", "vs VWAP", "vs open", "vs buy", ""]
    for p0 in range(0, len(rows), 36):
        fig = plt.figure(figsize=(11.7, 8.3)); ax = fig.add_subplot(111); ax.axis("off")
        ax.set_title(f"{sym} {day} -- indicators minute by minute (tick-rule buy/sell flow). R3 info at the trigger: "
                     + ", ".join(f"{k}={v}" for k, v in info.items() if not isinstance(v, (list, dict))), fontsize=7.5, loc="left", wrap=True)
        tb = ax.table(cellText=rows[p0:p0 + 36], colLabels=head, loc="upper center", cellLoc="center")
        tb.auto_set_font_size(False); tb.set_fontsize(6.6); tb.scale(1, 1.18)
        for (r_, c_), cell in tb.get_celld().items():
            if r_ == 0:
                cell.set_facecolor("#eceff1"); cell.set_text_props(weight="bold")
            elif rows[p0 + r_ - 1][-1] in ("BUY", "SELL", "TRIGGER", "support"):
                cell.set_facecolor({"BUY": "#bbdefb", "SELL": "#ffcdd2", "TRIGGER": "#fff9c4", "support": "#f3e5f5"}[rows[p0 + r_ - 1][-1]])
        pdf.savefig(fig); plt.close(fig)
print(json.dumps({"trade": t, "info": info, "stop": stop, "exit": [hm(M[j]), round(xp, 3), round(pl, 2), why]}, default=str))
for r_ in rows:
    print(" ".join(f"{x:>9}" for x in r_))
