"""star42.py OUT | summary OUT -- [2026-10-30] the STAR BOT's live exit on the FIXED #42 LIQ2+ROOM buys (2 years), replayed with the live engine
(premarket/star_live.StarEngine, config star): library days BEFORE each trade day only (set_day), the stock's own per-minute features from
library_v3 (same formulas as live). Per minute after the buy: intrabar stop (3% safety, raised by the profit lock B: +2% best -> entry + half
the best gain, best = finished-bar highs capped at 3% over max(open, close)); at the bar close Star's sf3 sell check; a Star sell is ignored by
noise2 (close >= VWAP and dip from the high since the buy < 2 x the mean 1-min range of the last 15 bars; Star's state reset) else sold at the
next open; 15:55 sell-all. Variant PLAIN = Star sf3 sell + 3% safety only (no noise2, no profit lock). 0.2% cost."""
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)); sys.path.insert(0, "/var/www/screener/premarket")
COST = 0.2
if sys.argv[1] != "summary":
    import v2_bar_replay as R
    T = [json.loads(l) for f in ("tr42l_a.jsonl", "tr42l_b.jsonl") for l in open(f)]
    T = sorted([t for t in T if t["kind"] == "LIQ2+ROOM"], key=lambda t: (t["day"], t["sym"]))
    z = np.load(TR / "data/playbook/library_v3.npz", allow_pickle=True); keys = list(z["keys"]); kix = {k: i for i, k in enumerate(keys)}
    need = [kix.get(f"{t['day']}|{t['sym']}") for t in T]; F_all = z["F"]; C_all = z["C"]; L_all = z["L"]
    FT = {i: (F_all[i].copy(), C_all[i].copy(), L_all[i].copy()) for i in need if i is not None}
    del z, F_all, C_all, L_all
    import star_live as SL
    cfg = json.load(open("/var/www/screener/premarket/config.json"))["star"]
    eng = SL.StarEngine(cfg, today="2099-12-31")
    print("engine ready", len(eng.keys), "good days; trades", len(T), "missing features", sum(i is None for i in need), flush=True)
    out = open(sys.argv[1], "w"); cur = None; d = None
    for t, ki in zip(T, need):
        if ki is None: continue
        day, s = t["day"], t["sym"]
        if day != cur:
            d = json.load(gzip.open(R.OW / f"bars/bars_{day}.json.gz", "rt")); R.REF._CACHE.clear(); cur = day; eng.set_day(day)
        if eng.block.min() > 0 or (eng.block == 0).sum() < eng.c["k"] + 5: continue       # fewer than k+5 library days before this day
        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]
        F, C, L = FT[ki]; bi = M.index(t["t"]) + 1; P = bars[bi]["o"]; res = {}
        for var in ("LIVE", "PLAIN"):
            D = np.zeros(len(eng.keys))
            for m in range(0, t["t"] + 1): D += ((eng.Fm[m] - F[m][None, :]) ** 2).sum(1)
            eng.state[s] = {"D": D, "m": t["t"], "pos": None, "C": C, "L": L, "qualified": True}
            eng.open_position(s)
            stop = P * (1 - cfg.get("safety_stop_pct", 3.0) / 100); best = None; pl = None; why = ""
            for j in range(bi, len(bars)):
                x = bars[j]; m = M[j]
                if x["l"] <= stop:
                    pl = (min(stop, x["o"]) if j > bi else stop) / P * 100 - 100 - COST; why = "stop/lock"; break
                if m >= 385: pl = x["c"] / P * 100 - 100 - COST; why = "15:55"; break
                st = eng.state[s]
                for mm in range(st["m"] + 1, m + 1): st["D"] += ((eng.Fm[mm] - F[mm][None, :]) ** 2).sum(1)
                st["m"] = m
                if var == "LIVE":
                    capped = min(x["h"], max(x["o"], x["c"]) * 1.03); best = capped if best is None else max(best, capped)
                    if best >= P * 1.02: stop = max(stop, P + 0.5 * (best - P))
                sell, reason = eng.sell_check(s)
                if sell and var == "LIVE" and j >= 15:
                    done = bars[:j + 1]; vol = sum(b["v"] for b in done); vw = sum((b["h"] + b["l"] + b["c"]) / 3 * b["v"] for b in done) / vol if vol else x["c"]
                    high = max(max(b["h"] for b in bars[bi:j + 1]), P); r1 = sum(b["h"] - b["l"] for b in done[-15:]) / 15
                    if x["c"] >= vw and (high - x["c"]) < 2.0 * r1:
                        st["pos"].update(diverged=False, climb=False, out=0); sell = False
                if sell and j + 1 < len(bars):
                    pl = bars[j + 1]["o"] / P * 100 - 100 - COST; why = reason.split("(")[0].strip(); j += 1; break
            if pl is None: pl = bars[-1]["c"] / P * 100 - 100 - COST; why = "end"
            res[var] = round(pl, 3); res[var + "_why"] = why; res[var + "_hold"] = M[min(j, len(M) - 1)] - M[bi]
            eng.close_position(s)
        out.write(json.dumps(dict(day=day, sym=s, t=t["t"], **res)) + "\n"); out.flush()
    out.close(); print("STAR42_DONE")
else:
    X = [json.loads(l) for l in open(sys.argv[2])]
    Y = lambda y: [x for x in X if (x["day"] < "2025-10-01") == (y == 1)]
    print(f"STAR BOT live exit on the #42 LIQ2+ROOM buys, 2 years ({len(X)} trades with >= 155 library days before them); 0.2% cost\n")
    for var, lab in (("LIVE", "Star live: sf3 sell + noise2 + profit lock B + 3% safety + 15:55"), ("PLAIN", "Star sf3 sell + 3% safety only")):
        print(lab)
        for y in (1, 2):
            Z = Y(y); v = np.array([z[var] for z in Z]); w, l = v[v > 0], v[v <= 0]
            why = {}
            for z in Z: why[z[var + "_why"]] = why.get(z[var + "_why"], 0) + 1
            print(f"   year {y}: {v.mean():+.3f}%/trade  win {np.mean(v > 0):3.0%}  {w.mean():+.2f}/{l.mean():+.2f}  hold {np.median([z[var + '_hold'] for z in Z]):.0f}m  (n {len(v)})  exits: " + ", ".join(f"{k} {n}" for k, n in sorted(why.items(), key=lambda a: -a[1])))
    print("STAR42_SUMMARY_DONE")
