"""
runner_snap.py -- [2026-10-26] the user: a deep study of TREND-DAY RUNNERS (10/26: WULF, CORZ, RIOT, CLSK, BRUN, SAIQ, CLRO ... rose
5-22% in steady trends; no EV3 setup fired) to build a setup that catches them. SNAPSHOTS: every stock-day of the daily list
(2024-10..2026-10, old-score top 30, quote flow) at T = 9:45, 10:00, 10:15, 10:30, 11:00 -- the readings known at T (finished bars), and
the outcome of buying at the next open: rise to the later high, +3% before -1.5%, and the C3 exit (stop 1.5% under the buy, arm +2%).
List-wide readings at T: the mean move from the open of the other listed stocks (the day's breadth) and the stock's minute-return
correlation with the others (moving as a group, like 10/26's crypto miners). -> runner_snap.json
"""
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 as c3_sim
TS = [15, 30, 45, 60, 90]


def feats(D, k, P):
    b = D.b[:k + 1]; m = D.m[k]; O = b[0]["o"]; fl = D.fl; ref = D.ref
    c = np.array([x["c"] for x in b]); vw = D.vw[k]
    def bs(n):
        B = sum(fl["buy"][max(0, m - n + 1):m + 1]); S = sum(fl["sell"][max(0, m - n + 1):m + 1]); return B / (B + S) if B + S else 0.5
    lows5 = [min(x["l"] for x in b[i:i + 5]) for i in range(0, len(b) - 4, 5)]
    hl = sum(1 for a_, b_ in zip(lows5, lows5[1:]) if b_ > a_) / max(1, len(lows5) - 1)
    t = np.arange(len(c)); r2 = float(np.corrcoef(t, c)[0, 1] ** 2 * np.sign(np.corrcoef(t, c)[0, 1])) if len(c) > 3 and c.std() > 0 else 0
    vpm = ref.get("vol_per_min") or []; norm = sum(vpm[:m + 1]) if len(vpm) > m else 0
    hi = max(x["h"] for x in b); lo = min(x["l"] for x in b)
    dd = max((max(x["h"] for x in b[:i + 1]) - b[i]["l"]) / max(x["h"] for x in b[:i + 1]) * 100 for i in range(len(b)))
    pc = ref.get("prev_close") or O
    return {"ret_open": (P / O - 1) * 100, "gap": (O / pc - 1) * 100, "vs_vwap": (P / vw - 1) * 100, "atr": ref["atr14"] / pc * 100,
            "rvol": sum(x["v"] for x in b) / norm if norm else None, "bs5": bs(5), "bs15": bs(15), "bs_all": bs(m + 1),
            "hl_share": hl, "r2": r2, "pos_day": (P - lo) / (hi - lo) if hi > lo else 0.5, "off_high": (P / hi - 1) * 100,
            "max_dd": dd, "first15": (b[min(14, len(b) - 1)]["c"] / O - 1) * 100, "price": P,
            "above_vwap_share": float(np.mean([x["c"] >= D.vw[i] for i, x in enumerate(b)]))}


def outcome(D, k):
    bi = k + 1
    if bi >= len(D.b):
        return None
    P = D.b[bi]["o"]; rest = D.b[bi:]
    hi = max(x["h"] for x in rest); peak = 0; hit = None
    for x in rest:
        if x["l"] <= P * 0.985:
            hit = False; break
        if x["h"] >= P * 1.03:
            hit = True; break
    pl, j, why = c3_sim(D, bi, P, P * 0.985, 2.0, "C3")
    return {"P": P, "rise": (hi / P - 1) * 100, "hit3": hit, "c3": round(pl, 3), "why": why}


def main():
    out = []
    for p in sorted(R.OW.glob("bars/bars_20*.json.gz")):
        day = p.name[5:15]
        if not ("2024-10-01" <= day <= "2026-10-02"):
            continue
        d = json.load(gzip.open(p, "rt")); Ds = {}
        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("atr14") or not ref.get("prev_close"):
                continue
            b = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]
            if len(b) < 200:
                continue
            Ds[s] = Day(b, [R.minute(x["t"]) for x in b], json.loads(fp.read_text()), ref)
        for T in TS:
            snap = {}
            for s, D in Ds.items():
                ks = [i for i, mm in enumerate(D.m) if mm <= T - 1]
                if len(ks) < 10:
                    continue
                k = ks[-1]; snap[s] = (D, k)
            # list-wide: breadth + co-movement (minute returns of the first T minutes)
            ret = {s: (D.b[k]["c"] / D.b[0]["o"] - 1) * 100 for s, (D, k) in snap.items()}
            mr = {}
            for s, (D, k) in snap.items():
                a = np.full(T, np.nan)
                for i in range(1, k + 1):
                    if D.m[i] < T and D.m[i - 1] == D.m[i] - 1:
                        a[D.m[i]] = D.b[i]["c"] / D.b[i - 1]["c"] - 1
                mr[s] = a
            for s, (D, k) in snap.items():
                o = outcome(D, k)
                if not o:
                    continue
                others = [v for z, v in ret.items() if z != s]
                cors = []
                for z, a in mr.items():
                    if z == s:
                        continue
                    ok = ~np.isnan(mr[s]) & ~np.isnan(a)
                    if ok.sum() >= 8 and np.std(mr[s][ok]) > 0 and np.std(a[ok]) > 0:
                        cors.append(np.corrcoef(mr[s][ok], a[ok])[0, 1])
                f = feats(D, k, D.b[k]["c"])
                out.append({"day": day, "sym": s, "T": T, "breadth": float(np.mean(others)) if others else 0,
                            "breadth_up": float(np.mean([v > 1 for v in others])) if others else 0,
                            "peer_corr_max": max(cors) if cors else 0, "peers_corr50": sum(1 for x in cors if x >= 0.5),
                            **{kk: (round(v, 4) if isinstance(v, float) else v) for kk, v in f.items()},
                            **{kk: (round(v, 4) if isinstance(v, float) else v) for kk, v in o.items()}})
        R.REF._CACHE.clear(); del d, Ds
        print(day, len(out), flush=True)
    json.dump(out, open(HERE / "runner_snap.json", "w"))
    print("SNAP_DONE")


if __name__ == "__main__":
    main()
