"""p42b_test.py A..B OUT | summary OUT.. -- [2026-10-29] the user's #42 through the SAME stock board as #41 (same stocks: library old-score top 30,
quote flow, pm_history premarket high; same board: rule v2, position/breakout, spike, liquidity, room 1%) with #42's own filters: a DEEP DIP
(>= 0.5u) -> V turn, VWAP NOT sloping down, entry from the open to 9:45 only. Only #42 arms the board (only_pids={42}); liquidity judged on the
bars so far (>= 3) because the 15-bar rule would block everything before 9:44.
Measured from the next open: max rise 15/60 min, max drop 30 min, higher after 15 min, +2% vs -2% first; exits with the stop under the V low."""
import gzip, json, sys
from pathlib import Path
import numpy as np
TR = Path("/var/www/screener/trade"); sys.path.insert(0, str(TR / "reports/playbook")); sys.path.insert(0, str(TR))
BASE = dict(rule="v2", only_pids={42}, liq_n_min=3)
VAR_MAIN = {"F full #41 board, VWAP not falling": dict(BASE, vwap2="flat"),
       "R full #41 board, VWAP rising": dict(BASE, vwap2="rising"),
       "N #41 board w/o volume-accel + 3m/15m, VWAP not falling": dict(BASE, vwap2="flat", v2_vol=False, v2_share=False)}
F = dict(BASE, vwap2="flat")
VAR = {"F full #41 board, VWAP not falling": F, "-vwap  F without the VWAP check": dict(F, vwap2="off"), "-vol   F without volume acceleration": dict(F, v2_vol=False),
       "-share F without 3m>15m both rising": dict(F, v2_share=False), "-liq   F without liquidity": dict(F, liq_min=None), "-room  F without room 1%": dict(F, room_min=None),
       "-spike F without the spike rule": dict(F, spike_x=None)} if __import__("os").environ.get("ABL") else VAR_MAIN
COST = 0.2
def meas(b, bi, P):
    f2 = 0
    for z in b[bi:bi + 120]:
        if z["l"] <= P * 0.98: f2 = -1; break
        if z["h"] >= P * 1.02: f2 = 1; break
    r = lambda n: round((max(z["h"] for z in b[bi:bi + n]) / P - 1) * 100, 3)
    return dict(r15=r(15), r60=r(60), d30=round((min(z["l"] for z in b[bi:bi + 30]) / P - 1) * 100, 3), c15=round((b[min(bi + 14, len(b) - 1)]["c"] / P - 1) * 100, 3), f2=f2)
def play(b, bi, P, stop, tgt):
    for j in range(bi, len(b)):
        x = b[j]
        if x["l"] <= stop: return (min(stop, x["o"]) if j > bi else stop) / P * 100 - 100 - COST
        if tgt and x["h"] >= P * (1 + tgt / 100): return tgt - COST
    return b[-1]["c"] / P * 100 - 100 - COST
if sys.argv[1] != "summary":
    import v2_bar_replay as R
    import stock_board as SB
    from opening_patterns import Recognizer
    a, b_ = sys.argv[1].split(".."); out = open(sys.argv[2], "w")
    for p in sorted(R.OW.glob("bars/bars_20*.json.gz")):
        day = p.name[5:15]
        if not (a <= day <= b_): continue
        d = json.load(gzip.open(p, "rt")); pp = R.OW / f"pm_history/{day}.json.gz"
        pmh = {r["s"]: r.get("pm_high") for r in json.load(gzip.open(pp, "rt"))["rows"]} if pp.exists() else {}
        for s in d["top30_current"]:
            fp = R.OW / "flow" / day / f"{s}.json"; ref = R.REF.load(day, s)
            if s not in d["symbols"] or not fp.exists() or not ref or not ref.get("prev_close") or not ref.get("atr14"): continue
            bars = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]
            if len(bars) < 150 or R.minute(bars[0]["t"]) != 0: continue
            fl = json.loads(fp.read_text()); Bs = {k: SB.Board(ref["prev_close"], ref["atr14"], bars[0]["o"], pm_high=pmh.get(s), vpm=ref.get("vol_per_min"), **o) for k, o in VAR.items()}
            P0 = Recognizer(ref["prev_close"], ref["atr14"], bars[0]["o"]); done = set()
            for i, x in enumerate(bars[:-1]):
                t = R.minute(x["t"])
                if t > 15: break
                P = bars[i + 1]["o"]; rows = []
                if 42 in P0.update(x, t) and "P" not in done: rows.append(("P #42 pattern only (no board)", P0.v42_low)); done.add("P")
                for k, B in Bs.items():
                    if B.update(x, t, fl["buy"][t], fl["sell"][t])["buy"] and k not in done: rows.append((k, B.R.v42_low)); done.add(k)
                for k, low in rows:
                    st = low * 0.998
                    ex = {f"t{tg}": round(play(bars, i + 1, P, st, tg), 3) for tg in (2, 3)} if st < P else {}
                    if ex: ex["hold"] = round(play(bars, i + 1, P, st, None), 3)
                    out.write(json.dumps(dict(kind=k, day=day, sym=s, t=t, above_low=round((P / low - 1) * 100, 3), **meas(bars, i + 1, P), **ex)) + "\n")
                if 5 <= t <= 15 and t % 2 == 1: out.write(json.dumps(dict(kind="RANDOM", day=day, sym=s, t=t, **meas(bars, i + 1, P))) + "\n")
        del d; R.REF._CACHE.clear(); out.flush()
    out.close(); print("P42ABL_DONE")
else:
    X = [json.loads(l) for f in sys.argv[2:] for l in open(f)]
    Y = lambda Z, h: [z for z in Z if (z["day"] < "2026-07-28") == (h == 1)]
    def f(Z):
        if not Z: return "n     0"
        a = lambda k: np.mean([z[k] for z in Z])
        return (f"n {len(Z):5} | max rise 15m {a('r15'):+.2f}% 60m {a('r60'):+.2f}% | max drop 30m {a('d30'):+.2f}% | higher after 15m {np.mean([z['c15'] > 0 for z in Z]):3.0%} "
                f"| +2% first {np.mean([z['f2'] == 1 for z in Z]):3.0%} / -2% first {np.mean([z['f2'] == -1 for z in Z]):3.0%}")
    def g(Z, k):
        v = np.sort([z[k] for z in Z if k in z])
        return f"{v.mean():+.3f}% (w/o top5 {v[:-5].mean():+.3f})" if len(v) > 10 else "-"
    print("#42 through the #41 stock board, 9:32-9:45, 6 months: first 3m 2026-04-28..07-27 | last 3m 07-28..10-27; from the next open\n")
    for k in ["RANDOM", "P #42 pattern only (no board)"] + list(VAR):
        Z = [x for x in X if x["kind"] == k]
        med = f"   (buy median {np.median([z['above_low'] for z in Z]):+.2f}% above the V low)" if Z and k != "RANDOM" else ""
        print(f"{k}{med}\n   first 3m {f(Y(Z, 1))}\n   last 3m  {f(Y(Z, 2))}")
        if k != "RANDOM":
            for e, lab in (("t2", "target +2%"), ("t3", "target +3%"), ("hold", "hold to close")):
                print(f"      stop under V low, {lab:13} after cost: first 3m {g(Y(Z, 1), e)} | last 3m {g(Y(Z, 2), e)}")
    print("P42ABL_SUMMARY_DONE")
