"""p42_chart.py OUTDIR DAY:SYM.. -- [2026-10-29] chart #42 V-turn buys (A, dip >= 0.3 ATR): candles 9:30-11:00, VWAP, dip high, V low + stop, buy, +2%/-2%,
volume, 3m/15m buy share."""
import gzip, json, sys
from pathlib import Path
import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt
TR = Path("/var/www/screener/trade"); sys.path.insert(0, str(TR / "reports/playbook")); sys.path.insert(0, str(TR)); sys.path.insert(0, str(TR / "reports/ev3"))
import os
import v2_bar_replay as R
VAR = os.environ.get("VAR", "A"); KS = float(os.environ.get("K", "0.3"))
_a = sys.argv; sys.argv = ["x", "none"]
from p42_test import signals
sys.argv = _a
out = Path(sys.argv[1]); out.mkdir(parents=True, exist_ok=True)
for ds in sys.argv[2:]:
    day, s, *tt = ds.split(":")
    d = json.load(gzip.open(R.OW / f"bars/bars_{day}.json.gz", "rt")); ref = R.REF.load(day, s)
    bars = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]; M = [R.minute(x["t"]) for x in bars]
    fl = json.loads((R.OW / "flow" / day / f"{s}.json").read_text()); fb, fs = fl["buy"], fl["sell"]
    if tt:                                       # [10/29] signal minute given (p42c: deep dip + first 3m > 15m)
        i = M.index(int(tt[0])); h_ = max(range(0, i), key=lambda j: bars[j]["h"]); l_ = min(range(h_ + 1, i), key=lambda j: bars[j]["l"])
        lo = bars[l_]["l"]; dip = (bars[h_]["h"] / lo - 1) * 100
    else:
        sig = [x for x in signals(bars, M, fl, ref["atr14"], ks=(KS,)) if x[0] == VAR][0]; _, _, i, lo, dip = sig
    hi_i = max(range(0, i), key=lambda j: bars[j]["h"]); lo_i = min(range(hi_i + 1, i), key=lambda j: bars[j]["l"])
    P = bars[i + 1]["o"]; stop = lo * 0.998
    n = min(len(bars), 91); B = bars[:n]
    cv = pv = 0; VW = []
    for x in B: cv += x["v"]; pv += (x["h"] + x["l"] + x["c"]) / 3 * x["v"]; VW.append(pv / cv)
    sh = lambda t, k: sum(fb[max(0, t - k + 1):t + 1]) / max(sum(fb[max(0, t - k + 1):t + 1]) + sum(fs[max(0, t - k + 1):t + 1]), 1)
    res = "?"
    for z in bars[i + 1:]:
        if z["l"] <= stop: res = f"stopped {R.minute(z['t'])//60+9}:{(R.minute(z['t'])+30)%60:02d}" if False else "stop hit"; t_out = R.minute(z["t"]); break
        if z["h"] >= P * 1.02: res = "+2% hit"; t_out = R.minute(z["t"]); break
    f2t = None
    for z in bars[i + 1:i + 121]:
        if z["l"] <= P * 0.98: f2t = ("-2% first", R.minute(z["t"])); break
        if z["h"] >= P * 1.02: f2t = ("+2% first", R.minute(z["t"])); break
    hm = lambda m: f"{(m + 30) // 60 + 9}:{(m + 30) % 60:02d}"
    fig, ax = plt.subplots(3, 1, figsize=(13, 9), sharex=True, gridspec_kw=dict(height_ratios=[4, 1, 1.3]))
    for x, m in zip(B, M[:n]):
        c = "#2a9d4b" if x["c"] >= x["o"] else "#d64545"
        ax[0].plot([m, m], [x["l"], x["h"]], color=c, lw=0.8); ax[0].add_patch(plt.Rectangle((m - 0.35, min(x["o"], x["c"])), 0.7, max(abs(x["c"] - x["o"]), 1e-4), color=c))
        ax[1].bar(m, x["v"], color=c, width=0.7)
    ax[0].plot(M[:n], VW, color="#7b3fbf", lw=1.3, label="VWAP")
    ax[0].axhline(bars[hi_i]["h"], color="#999", ls=":", lw=1); ax[0].text(M[n - 1], bars[hi_i]["h"], " dip high", va="center", fontsize=8, color="#666")
    ax[0].axhline(stop, color="#d64545", ls="--", lw=1); ax[0].text(M[n - 1], stop, " stop (V low -0.2%)", va="center", fontsize=8, color="#d64545")
    ax[0].axhline(P * 0.98, color="#d64545", ls=":", lw=1); ax[0].text(M[n - 1], P * 0.98, " -2%", va="center", fontsize=8, color="#d64545")
    if f2t and f2t[1] < n: ax[0].axvline(f2t[1], color="#d64545" if f2t[0][0] == "-" else "#2a9d4b", lw=1.2, ls=":")
    ax[0].axhline(P * 1.02, color="#2a9d4b", ls="--", lw=1); ax[0].text(M[n - 1], P * 1.02, " +2%", va="center", fontsize=8, color="#2a9d4b")
    ax[0].axhline(ref["prev_close"], color="#e0a020", ls="-.", lw=1); ax[0].text(M[n - 1], ref["prev_close"], " prev close", va="center", fontsize=8, color="#b07a00", clip_on=True)
    ax[0].scatter([M[lo_i]], [lo], marker="o", s=60, facecolors="none", edgecolors="k", zorder=5); ax[0].annotate("V low", (M[lo_i], lo), (0, -16), textcoords="offset points", ha="center", fontsize=8)
    if VAR.startswith("HL"):                     # [10/29] higher-low entry: mark the bounce high and the higher low (+ its stop)
        bh_i = max(range(lo_i + 1, i), key=lambda j: bars[j]["h"]); l2_i = min(range(bh_i + 1, i), key=lambda j: bars[j]["l"])
        ax[0].scatter([M[bh_i]], [bars[bh_i]["h"]], marker="v", s=50, color="#e07b00", zorder=5); ax[0].annotate("bounce high", (M[bh_i], bars[bh_i]["h"]), (0, 8), textcoords="offset points", ha="center", fontsize=8, color="#b06000")
        ax[0].scatter([M[l2_i]], [bars[l2_i]["l"]], marker="o", s=60, facecolors="none", edgecolors="#e07b00", zorder=5); ax[0].annotate("higher low", (M[l2_i], bars[l2_i]["l"]), (0, -16), textcoords="offset points", ha="center", fontsize=8, color="#b06000")
    ax[0].scatter([M[i] + 1], [P], marker="^", s=140, color="#1f6feb", zorder=6); ax[0].annotate(f"BUY {hm(M[i]+1)} ${P:.2f}", (M[i] + 1, P), (8, 10), textcoords="offset points", fontsize=9, color="#1f6feb", weight="bold")
    if res != "?" and t_out < n: ax[0].axvline(t_out, color="#d64545" if "stop" in res else "#2a9d4b", lw=0.8, alpha=0.6)
    ax[0].set_ylim(min(min(x["l"] for x in B), stop) * 0.995, max(max(x["h"] for x in B), P * 1.02) * 1.005)
    ax[0].set_title(f"{s} {day} — #42 V turn{' + VWAP rising' if VAR == 'V' else ' deep dip + first 3m>15m' if VAR == 'P' else ' deep dip + first 3m>15m + 3m>=55%' if VAR == 'P55' else ' HIGHER LOW + 3m>=55%' if VAR == 'HL55' else ''} | dip {dip:.1f}% ({(bars[hi_i]['h']-lo)/ref['atr14']:.2f} ATR) | buy {(P/lo-1)*100:.1f}% above V low | {res}"
                    f" at {hm(t_out) if res!='?' else ''}" + (f" ({f2t[0]} at {hm(f2t[1])})" if f2t else "") + f" | gap {(bars[0]['o']/ref['prev_close']-1)*100:+.1f}%", fontsize=11)
    ax[0].legend(loc="upper left", fontsize=8); ax[1].set_ylabel("volume")
    ax[2].plot(M[:n], [sh(m, 3) for m in M[:n]], color="#1f6feb", lw=1.2, label="buy share 3m"); ax[2].plot(M[:n], [sh(m, 15) for m in M[:n]], color="#e07b00", lw=1.2, label="buy share 15m")
    ax[2].axhline(0.5, color="#999", lw=0.6); ax[2].axvline(M[i] + 1, color="#1f6feb", lw=0.8, ls=":"); ax[2].legend(loc="upper left", fontsize=8); ax[2].set_ylim(0, 1)
    ax[2].set_xticks(range(0, n, 10)); ax[2].set_xticklabels([hm(m) for m in range(0, n, 10)])
    for a in ax: a.grid(alpha=0.25)
    plt.tight_layout(); f = out / f"p42{VAR if VAR != 'A' else ''}_{s}_{day}.png"; plt.savefig(f, dpi=95); plt.close(); print(f, res)
    del d; R.REF._CACHE.clear()
