"""star_vwap_down_test.py -- [2026-11-03] follow-up: BLOCK when VWAP is sloping DOWN over the last 30 / 60 min
(VWAP now < VWAP n bars ago, or the first bar's VWAP if the day is younger; optional minimum drop %).
Original docstring of star_vwap_rise_test.py: the user: "Star is buying stocks where the VWAP is sloping down; VWAP has to be increasing for at
least 3 bars". 2-year test on the per-minute check results saved by star_entry_ablation.py (abl_y1/_y2_masks.jsonl.gz) with the Star bot's
LIVE checks (5 checks off since 10/28) + a VWAP-rising rule decided on FINISHED bars only (VWAP after bar i vs after bar i-1 ..., no look-ahead;
buy at the next bar's open). Same trade logic as the ablation (one position per stock, re-entry after a loss only above that buy, C3 exit +
3% Star stop, 0.2% cost) -- Star's own sell can't be replayed, so P/L is a side note; the entry is judged by the RISE after the buy.
Part 1: the baseline buys split into "rule passes" vs "rule would block" (rise after the buy). Part 2: full replay per variant."""
import gzip, json, sys
from pathlib import Path
import numpy as np
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
from queue_test import Day
from sim_2y import sim
CATS = ["TIMING", "RVOL", "VOL_SPIKE", "ROOM", "BUYSHARE", "FALLING", "SMOOTH", "STRAIGHT", "EXT_OPEN", "EXT_ATR", "EXT_PREVCLOSE",
        "EXT_MOVE", "B1", "VWAP", "ACCEL", "LIQ", "STRETCH", "STOP"]
BIT = {c: 1 << i for i, c in enumerate(CATS)}
LIVE_OFF = BIT["VOL_SPIKE"] | BIT["SMOOTH"] | BIT["ACCEL"] | BIT["STRETCH"] | BIT["FALLING"]     # Star live since 10/28
MK = {}
for f in ("abl_y1_masks.jsonl.gz", "abl_y2_masks.jsonl.gz"):
    for l in gzip.open(HERE / f, "rt"):
        r = json.loads(l); MK.setdefault(r["day"], {})[r["sym"]] = {int(i): (v[0], v[1]) for i, v in r["mk"].items()}


def vw_series(bars):
    out, pv, v = [], 0.0, 0.0
    for b in bars:
        pv += (b["h"] + b["l"] + b["c"]) / 3 * b["v"]; v += b["v"]; out.append(pv / v if v else b["c"])
    return out


def rule(vw, i, kind, n, thr=0.0):
    """True = the buy is allowed. kind 'down': blocked when VWAP fell over the last n bars by more than thr %."""
    if kind == "down":
        return not (vw[i] < vw[max(0, i - n)] * (1 - thr / 100))
    if kind == "down_full":                      # only judged once n bars exist (earlier buys allowed)
        return i < n or not (vw[i] < vw[i - n] * (1 - thr / 100))
    return True


VARS = [("off", None, 0, 0.0), ("down", "down", 30, 0.0), ("down", "down", 30, 0.5), ("down", "down", 30, 1.0),
        ("down", "down", 60, 0.0), ("down", "down", 60, 0.5), ("down", "down", 60, 1.0),
        ("full", "down_full", 30, 0.0), ("full", "down_full", 60, 0.0)]
name = lambda v: "live (no VWAP rule)" if v[1] is None else (
    f"block: VWAP down over {v[2]} min" + (f" by > {v[3]}%" if v[3] else "") + (" (from open if younger)" if v[1] == "down" else " (only after {} min)".format(v[2])))


def path(b, bi, P):
    w30, w60 = b[bi:bi + 30], b[bi:bi + 60]
    o = dict(mfe30=(max(x["h"] for x in w30) / P - 1) * 100, mfe60=(max(x["h"] for x in w60) / P - 1) * 100,
             mae30=(min(x["l"] for x in w30) / P - 1) * 100)
    first = 0
    for x in b[bi:bi + 120]:
        if x["l"] <= P * 0.99: first = -1; break
        if x["h"] >= P * 1.01: first = 1; break
    o["first"] = first
    return o


def run(D, mk, vw, kind, n, thr):
    T = []; last_loss = None; nxt = 0
    for i in sorted(mk):
        if i < nxt: continue
        m_, stop = mk[i]
        if m_ & ~LIVE_OFF or not stop: continue
        if kind and not rule(vw, i, kind, n, thr): continue
        bi = i + 1; P = D.b[bi]["o"]
        if last_loss is not None and P <= last_loss + 0.01: continue
        pl, j, why = sim(D, bi, P, min(stop, P * 0.97), 2.0, "C3")
        t = dict(pl=pl, **path(D.b, bi, P))
        if kind is None:
            t["pass"] = {f"{k}{nn}_{th}": rule(vw, i, k, nn, th) for _, k, nn, th in VARS if k}
        T.append(t); nxt = j + 1
        if pl <= 0: last_loss = P
    return T


res = {v: {"y1": [], "y2": []} for v in VARS}
for p in sorted(R.OW.glob("bars/bars_20*.json.gz")):
    day = p.name[5:15]
    if day not in MK: continue
    d = json.load(gzip.open(p, "rt")); y = "y1" if day < "2025-10-01" else "y2"
    for s, mk in MK[day].items():
        ref = R.REF.load(day, s); fp = R.OW / "flow" / day / f"{s}.json"
        bars = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]
        D = Day(bars, [R.minute(x["t"]) for x in bars], json.loads(fp.read_text()), ref); vw = vw_series(bars)
        for v in VARS: res[v][y] += run(D, mk, vw, v[1], v[2], v[3])
    del d; R.REF._CACHE.clear()
    print(day, flush=True, file=sys.stderr)


def stats(T):
    if not T: return "n     0"
    a = lambda k: np.mean([t[k] for t in T])
    up = sum(t["first"] == 1 for t in T); dn = sum(t["first"] == -1 for t in T)
    return (f"n {len(T):5} | max rise 30m {a('mfe30'):+.2f}% 60m {a('mfe60'):+.2f}% | reach +2% {np.mean([t['mfe60'] >= 2 for t in T]) * 100:4.0f}%"
            f" +3% {np.mean([t['mfe60'] >= 3 for t in T]) * 100:4.0f}% | +1% first {up / max(up + dn, 1) * 100:4.0f}% | max drop 30m {a('mae30'):+.2f}%"
            f" | C3 P/L {a('pl'):+.3f}%/trade")


print("PART 1 -- live Star buys (2 years), PASS = allowed, BLOCK = VWAP sloping down at the signal bar (rise after the buy; 60 min window)")
base = res[VARS[0]]
for v in VARS[1:]:
    key = f"{v[1]}{v[2]}_{v[3]}"
    for y in ("y1", "y2"):
        ok = [t for t in base[y] if t["pass"][key]]; bad = [t for t in base[y] if not t["pass"][key]]
        print(f"{name(v):45} {y}  PASS  {stats(ok)}")
        print(f"{'':45} {y}  BLOCK {stats(bad)}")
print("\nPART 2 -- full replay per variant (blocked buys can come back later when the rule passes)")
for v in VARS:
    for y in ("y1", "y2"):
        print(f"{name(v):45} {y}  {stats(res[v][y])}")
print("VWAPDOWN_DONE")
