"""
v_styleA_test.py -- [2026-10-11] The user: within STYLE A (opening spike, then collapse), does anything KNOWN AT THE V
predict a RECOVERY vs a WEAK bounce? Causal version: EVERY V (deepv_outcomes.vs_of, drop >= 2%) that has the style-A
path when it is confirmed (3 bars after the low):
  spike = the first-15-min high >= +2% over the open, still the day high; the V low >= 3% under the spike.
Label (hindsight): share of the fall spike -> V low taken back before the low breaks: RECOVERED >= 50%, WEAK < 25%.
Features at the confirmation: time, drop into the V, fall from the spike, V low vs open, spike size, minutes since the
spike, V number of the day, gap, daily ATR %, volume so far / prior day, vs VWAP, buy share 15 min before the low,
buy share low -> confirmation, selling dried up, volume at the low, net flow 15 min.
Trades from the confirmation close, stop = V low - 0.1%: a) 2R / 60 min  b) target = 50% back to the spike, else stop /
15:55; at the real 0.2% cost. Year 1 < 2025-10-01 <= year 2; filters chosen on year 1 only.
    python3 v_styleA_test.py
"""
import gzip
import json
import sys
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
OW = HERE.parent / "open_window"
sys.path.insert(0, str(HERE)); sys.path.insert(0, str(OW)); sys.path.insert(0, "/var/www/screener/trade")
from deepv_outcomes import vs_of  # noqa: E402
from up2_styles_build import arrays  # noqa: E402
from v_pressure_study import auc  # noqa: E402
import reference as REF  # noqa: E402

COST, SPLIT = 0.2, "2025-10-01"
sh = lambda b, s: b / (b + s) if b + s > 0 else np.nan


def exits(a, k, stop, target):
    O, H, L, C = a[0], a[1], a[2], a[3]
    e = C[k]; R = e - stop
    r2 = None
    for j in range(k + 1, min(k + 61, 386)):
        if L[j] <= stop:
            r2 = (min(stop, O[j]) / e - 1) * 100; break
        if H[j] >= e + 2 * R:
            r2 = (max(e + 2 * R, O[j]) / e - 1) * 100; break
    if r2 is None:
        r2 = (C[min(k + 60, 385)] / e - 1) * 100
    rt = None
    for j in range(k + 1, 386):
        if L[j] <= stop:
            rt = (min(stop, O[j]) / e - 1) * 100; break
        if target > e and H[j] >= target:
            rt = (max(target, O[j]) / e - 1) * 100; break
    if rt is None:
        rt = (C[385] / e - 1) * 100
    return r2, rt


def build():
    R = []
    for p in sorted(OW.glob("bars/bars_20*.json.gz")):
        day = p.name[5:15]
        d = json.load(gzip.open(p, "rt"))
        for s in d["top30_current"]:
            fp = OW / "flow" / day / f"{s}.json"
            if s not in d["symbols"] or not fp.exists():
                continue
            a = arrays(d["symbols"][s]["bars"])
            if a is None:
                continue
            O, H, L, C, V = a; O0 = float(O[0])
            spike = H[:15].max()
            if spike < O0 * 1.02:
                continue
            fl = json.loads(fp.read_text()); bu, se = np.array(fl["buy"], float), np.array(fl["sell"], float)
            ref = REF.load(day, s) or {}; pc = ref.get("prev_close"); atr = ref.get("atr14")
            base = d["symbols"][s].get("baseline")
            cv = np.cumsum(V); vw = np.cumsum((H + L + C) / 3 * V) / np.where(cv > 0, cv, np.nan)
            for v in vs_of(a):
                j = v["m"]; k = j + 3
                if v["drop"] < 2 or H[:j].max() > spike or L[j] > spike * 0.97:
                    continue
                lo = L[j]
                brk = np.where(L[j + 1:386] < lo)[0]; end = j + 1 + int(brk[0]) if len(brk) else 386
                top = H[j + 1:end].max() if end > j + 1 else lo
                share = (top - lo) / (spike - lo)
                r2, rt = exits(a, k, lo * 0.999, spike - 0.5 * (spike - lo))
                pre10 = slice(max(0, j - 10), j)
                R.append({"day": day, "sym": s, "y2": day >= SPLIT, "share": share,
                          "pl_2r": r2 - COST, "pl_half": rt - COST,
                          "time": j, "drop": v["drop"], "fall": (spike / lo - 1) * 100, "v_vs_open": (lo / O0 - 1) * 100,
                          "spike": (spike / O0 - 1) * 100, "since_spike": j - int(np.argmax(H[:15])), "nth": v["n"],
                          "gap": (O0 / pc - 1) * 100 if pc else np.nan, "atr": atr / pc * 100 if atr and pc else np.nan,
                          "rvol": cv[k] / base if base else np.nan, "vwap": (C[k] / vw[k] - 1) * 100,
                          "bs_pre15": sh(bu[max(0, j - 14):j + 1].sum(), se[max(0, j - 14):j + 1].sum()),
                          "bs_turn": sh(bu[j:k + 1].sum(), se[j:k + 1].sum()),
                          "sell_dry": se[j:k + 1].mean() / se[pre10].mean() if se[pre10].mean() > 0 else np.nan,
                          "vol_low": V[j:k + 1].mean() / V[pre10].mean() if V[pre10].mean() > 0 else np.nan,
                          "net15": (bu[k - 14:k + 1].sum() - se[k - 14:k + 1].sum()) / max(bu[k - 14:k + 1].sum() + se[k - 14:k + 1].sum(), 1)})
        del d
        print(day, len(R), flush=True)
    return R


def main():
    R = build()
    F = ["time", "drop", "fall", "v_vs_open", "spike", "since_spike", "nth", "gap", "atr", "rvol", "vwap", "bs_pre15",
         "bs_turn", "sell_dry", "vol_low", "net15"]
    X = {f: np.array([r[f] for r in R], float) for f in F}
    y2 = np.array([r["y2"] for r in R]); share = np.array([r["share"] for r in R])
    rec, weak = share >= 0.5, share < 0.25
    p2r, ph = np.array([r["pl_2r"] for r in R]), np.array([r["pl_half"] for r in R])
    print(f"\nSTYLE A Vs (causal, drop >= 2%): {len(R)} ({(~y2).sum()} year 1 / {y2.sum()} year 2), "
          f"{len({(r['day'], r['sym']) for r in R})} stock-days")
    print(f"  RECOVERED >= 50% of the fall: {rec.mean():.0%}   WEAK < 25%: {weak.mean():.0%}")
    print(f"  trades at {COST}% cost: 2R/60min {p2r[~y2].mean():+.3f}% / {p2r[y2].mean():+.3f}%  |  50%-back target "
          f"{ph[~y2].mean():+.3f}% / {ph[y2].mean():+.3f}%   (year 1 / year 2)")
    print("\nAUC recovered vs weak (> 0.5 = higher value -> recovers more) | AUC for a winning 50%-back trade")
    k2 = rec | weak
    rank = []
    for f in F:
        a1, a2 = auc(X[f][k2 & ~y2], rec[k2 & ~y2]), auc(X[f][k2 & y2], rec[k2 & y2])
        t1, t2 = auc(X[f][~y2], ph[~y2] > 0), auc(X[f][y2], ph[y2] > 0)
        rank.append((abs(a1 - 0.5), f))
        print(f"  {f:12} recovery: year 1 {a1:.2f}  year 2 {a2:.2f}   | trade win: year 1 {t1:.2f}  year 2 {t2:.2f}")
    print("\nQUINTILES of the 4 strongest (cut points from year 1)")
    for _, f in sorted(rank, reverse=True)[:4]:
        qs = np.nanquantile(X[f][~y2], [0.2, 0.4, 0.6, 0.8]); b = np.digitize(X[f], qs); ok = ~np.isnan(X[f])
        print(f"  {f} (cuts {', '.join(f'{q:.2f}' for q in qs)})")
        for q in range(5):
            row = []
            for lab, sel in (("y1", ~y2), ("y2", y2)):
                k = ok & (b == q) & sel
                row.append(f"{lab} {k.sum():5} rec {rec[k].mean():4.0%} weak {weak[k].mean():4.0%} 2R {p2r[k].mean():+.3f}% "
                           f"50%-back {ph[k].mean():+.3f}%")
            print(f"    Q{q + 1}: " + " | ".join(row))
    # best 2-feature filter on year 1 (quintile edges), checked on year 2
    best = None
    tops = [f for _, f in sorted(rank, reverse=True)[:6]]
    for i, f1 in enumerate(tops):
        for f2 in tops[i + 1:]:
            for q1 in (0.2, 0.4, 0.6, 0.8):
                for q2 in (0.2, 0.4, 0.6, 0.8):
                    for s1 in (1, -1):
                        for s2 in (1, -1):
                            c1 = np.nanquantile(X[f1][~y2], q1); c2 = np.nanquantile(X[f2][~y2], q2)
                            k = (s1 * X[f1] >= s1 * c1) & (s2 * X[f2] >= s2 * c2)
                            if (k & ~y2).sum() < 150:
                                continue
                            m = ph[k & ~y2].mean()
                            if best is None or m > best[0]:
                                best = (m, f1, s1, c1, f2, s2, c2)
    if best:
        m, f1, s1, c1, f2, s2, c2 = best
        k = (s1 * X[f1] >= s1 * c1) & (s2 * X[f2] >= s2 * c2)
        print(f"\nBEST 2-FEATURE FILTER picked on year 1: {f1} {'>=' if s1 > 0 else '<='} {c1:.2f} AND {f2} {'>=' if s2 > 0 else '<='} {c2:.2f}")
        for lab, sel in (("year 1 (fitted)", ~y2), ("YEAR 2 (unseen)", y2)):
            kk = k & sel
            print(f"  {lab}: {kk.sum()} Vs | recovered {rec[kk].mean():.0%} weak {weak[kk].mean():.0%} | 2R {p2r[kk].mean():+.3f}% | "
                  f"50%-back {ph[kk].mean():+.3f}% win {np.mean(ph[kk] > 0):.0%}")


if __name__ == "__main__":
    main()
