"""
star_exit_setups.py -- [2026-10-23] the user: drop R2 and R6, and EXIT the chart-setup buys (R1, R1A, R3, R4, R5, R7, R8, R9)
with the STAR BOT's sells -- test on 1 year (2025-10-01 .. 2026-10-02).
Entries: every trigger of trade/reports/playbook/setups_2y.jsonl (2-year test, finished bars only); buy at the next open.
Exit = the live Star bot's sell logic, real star_live engine (library v3, good days only, library days BEFORE the replayed day):
  Star's sell (sf3 latest) at the next open, held back by noise2 (k 2.0: close >= VWAP and the dip from the high since the
  buy < 2 x the mean 1-min range) -- the 3% safety stop (intrabar) -- 15:55 sell.
Every trigger is its own trade (no slots), $1,640 each, 0.2% cost. Compared on the SAME trades with the 1% trailing stop
of the 2-year test. Positions share one engine (each trade carries its own Star state).
    nice -n 19 python3 star_exit_setups.py [START..END]  -> data/star_exit_setups.jsonl + report
"""
import gzip
import json
import sys
from collections import defaultdict
from datetime import datetime, timedelta
from pathlib import Path

import numpy as np

sys.path.insert(0, "/var/www/screener/premarket")
import star_live  # noqa: E402
from star_replay import OW, REFD, ET, rows_to_bars  # noqa: E402

TRIG = Path("/var/www/screener/trade/reports/playbook/setups_2y.jsonl")
OUT = Path("/var/www/screener/premarket/data/star_exit_setups.jsonl")
KEEP = {"R1", "R1A", "R3", "R4", "R5", "R7", "R8", "R9"}
SIZE, COST, STOP, NOISE_K = 1640.0, 0.2, 3.0, 2.0


def noise2(bars_done, pos):
    if len(bars_done) < 16:
        return False
    pv = sum((b["h"] + b["l"] + b["c"]) / 3 * b["v"] for b in bars_done); vol = sum(b["v"] for b in bars_done)
    vwap = pv / vol if vol else bars_done[-1]["c"]
    close = bars_done[-1]["c"]
    since = [b for b in bars_done if star_live.minute_of(b["t"]) >= pos["buy_m"]] or bars_done[-1:]
    high = max(max(b["h"] for b in since), pos["buy"])
    r1 = sum(b["h"] - b["l"] for b in bars_done[-15:]) / 15
    return close >= vwap and (high - close) < NOISE_K * r1


def load_triggers(a, b):
    by = defaultdict(list)
    for l in open(TRIG):
        t = json.loads(l)
        if t["setup"] in KEEP and a <= t["day"] <= b:
            by[t["day"]].append(t)
    return by


def run_day(eng, day, trigs, out):
    d = json.load(gzip.open(OW / "bars" / f"bars_{day}.json.gz", "rt"))
    bj = OW / "bars" / f"bench_{day}.json.gz"
    bench = json.load(gzip.open(bj, "rt")) if bj.exists() else {}
    bench = (rows_to_bars(bench.get("SPY", [])), rows_to_bars(bench.get("IWM", [])))
    eng.set_day(day)
    syms = sorted({t["sym"] for t in trigs})
    data = {}
    for s in syms:
        rp, fp = REFD / day / f"{s}.json", OW / "flow" / day / f"{s}.json"
        if s not in d["symbols"] or not rp.exists() or not fp.exists():
            continue
        fl = json.loads(fp.read_text()); bars = rows_to_bars(d["symbols"][s]["bars"])
        data[s] = {"bars": bars, "by": {star_live.minute_of(b["t"]): b for b in bars}, "ref": json.loads(rp.read_text()),
                   "flow": {m: (fl["buy"][m], fl["sell"][m]) for m in range(390)}}
    del d
    entries = defaultdict(list)                       # minute m (trigger bar) -> triggers
    for t in trigs:
        if t["sym"] in data:
            entries[t["m"]].append(t)
    first = {s: min(t["m"] for t in trigs if t["sym"] == s) for s in data}
    d0 = datetime.fromisoformat(day).replace(tzinfo=ET)
    open_tr, n = [], 0
    for m in range(0, 386):
        now = d0.replace(hour=9, minute=30) + timedelta(minutes=m + 1)
        nxt = m + 1
        for s, x in data.items():
            if m >= first[s] or any(tr["sym"] == s for tr in open_tr):
                eng.update(s, [b for b in x["bars"] if star_live.minute_of(b["t"]) <= m], x["ref"],
                           tuple([b for b in bb if star_live.minute_of(b["t"]) <= m] for bb in bench), x["flow"], now)
                eng.state[s]["qualified"] = True
        keep = []
        for tr in open_tr:
            s = tr["sym"]; x = data[s]; b = x["by"].get(m); st = eng.state[s]
            done = None
            if b and m >= tr["buy_m"] and b["l"] <= tr["stop"]:
                tr.update(sell_m=m, sell=min(tr["stop"], b["o"]) if m > tr["buy_m"] else tr["stop"], why="safety stop 3%"); done = True
            elif m >= 385:
                last = [y for k, y in x["by"].items() if k <= m]
                tr.update(sell_m=m, sell=max(last, key=lambda y: y["t"])["c"] if last else tr["buy"], why="15:55"); done = True
            elif m >= tr["buy_m"]:
                st["pos"] = tr["star"]
                sell, why = eng.sell_check(s)
                tr["star"] = st["pos"]; st["pos"] = None
                if sell and x["by"].get(nxt):
                    bd = [y for y in x["bars"] if star_live.minute_of(y["t"]) <= m]
                    if noise2(bd, tr):
                        tr["star"].update(diverged=False, climb=False, out=0); tr["holds"] = tr.get("holds", 0) + 1
                    else:
                        tr.update(sell_m=nxt, sell=x["by"][nxt]["o"], why=why.split(" (")[0].split(",")[0]); done = True
            if done:
                tr.pop("star", None)
                tr["pl"] = (tr["sell"] / tr["buy"] - 1) * 100 - COST
                out.write(json.dumps(tr) + "\n"); n += 1
            else:
                keep.append(tr)
        open_tr = keep
        for t in entries.get(m, []):
            s = t["sym"]; x = data[s]
            if not x["by"].get(nxt) or s not in eng.state:
                continue
            e = x["by"][nxt]["o"]
            st = eng.state[s]; st["pos"] = None
            eng.open_position(s)
            open_tr.append({"setup": t["setup"], "day": day, "sym": s, "m": m, "buy_m": nxt, "buy": e, "stop": e * (1 - STOP / 100),
                            "atr": t["atr"], "trail": t["trail"], "rise_fade": t["rise_fade"], "star": st["pos"]})
            st["pos"] = None
    print(day, len(trigs), "triggers", n, "trades", flush=True)


def report():
    T = [json.loads(l) for l in open(OUT)]
    days = sorted({t["day"] for t in T}); half = days[len(days) // 2]
    print(f"\n{len(days)} days {days[0]}..{days[-1]}; every trigger its own trade; 0.2% cost; ${SIZE:.0f} per trade")
    print(f"   {'setup':6} {'trades':>6} | {'STAR sells':>28} | {'1% trailing stop (same trades)':>30} | exits")
    def line(lab, X):
        if not X:
            return
        p = np.array([t["pl"] for t in X]); q = np.array([t["trail"] for t in X]); h = np.array([t["day"] < half for t in X])
        w = defaultdict(int)
        for t in X:
            w[t["why"]] += 1
        print(f"   {lab:6} {len(X):6} | {p.mean():+.3f}% win {np.mean(p > 0):4.0%} (h1 {p[h].mean() if h.any() else 0:+.3f} h2 {p[~h].mean() if (~h).any() else 0:+.3f}) "
              f"| {q.mean():+.3f}% (h1 {q[h].mean() if h.any() else 0:+.3f} h2 {q[~h].mean() if (~h).any() else 0:+.3f}) | "
              + ", ".join(f"{k} {v}" for k, v in sorted(w.items(), key=lambda z: -z[1])[:3])
              + f" | median hold {np.median([t['sell_m'] - t['buy_m'] for t in X]):.0f} min | total ${p.sum() * SIZE / 100:+,.0f}")
    line("ALL", T)
    for s in ["R1", "R1A", "R3", "R4", "R5", "R7", "R8", "R9"]:
        line(s, [t for t in T if t["setup"] == s])
    print("  by daily ATR (all setups):")
    for lab, lo, hi in (("<6%", 0, 6), ("6-10%", 6, 10), (">=10%", 10, 999)):
        line(lab, [t for t in T if lo <= t["atr"] < hi])
    print("STAREXIT_DONE")


if __name__ == "__main__":
    if "--report" in sys.argv:
        report(); sys.exit()
    rng = sys.argv[1] if len(sys.argv) > 1 else "2025-10-01..2026-10-02"
    a, b = rng.split("..")
    trig = load_triggers(a, b)
    eng = star_live.StarEngine({}, today="2099-01-01")
    with open(OUT, "w") as out:
        for day in sorted(trig):
            run_day(eng, day, trig[day], out)
            out.flush()
    report()
