"""
exit_trail_noise.py -- [2026-10-23] the user: test the 1% trailing stop COMBINED with noise2 (the Star bot's noise filter),
on the SAME 3,809 setup buys (premarket/data/star_exit_setups.jsonl: R1 R1A R3 R4 R5 R7 R8 R9, 1 year, buy at the next
open, 0.2% cost).
  T0  plain 1% trailing stop, intrabar (stop 1% under the buy, raised to 1% under every new high; sold at the stop)
  T1  the same trail checked at the BAR CLOSE (close below the trail stop -> sell at the next open) -- no noise filter
  T2  T1 + noise2 as in the Star bot: if the close is >= VWAP AND the dip from the high since the buy < 2 x the mean 1-min
      range of the last 15 bars -> HOLD (the trail stays); + the 3% safety stop (intrabar) like the Star bot
  T3  T1 + noise2 WITHOUT the VWAP condition (only "the dip is normal 1-min noise") + the 3% safety stop
  T4  T3 but the hard floor is UNDER THE SETUP'S SUPPORT (support x 0.998, clamped 0.5%..4% under the buy) instead of 3%
Also shown: Star's sells and the 2-year test's plain trail on the same trades.
    nice -n 19 python3 exit_trail_noise.py   -> exit_trail_noise.log
"""
import gzip
import json
import sys
from collections import defaultdict
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")
import v2_bar_replay as R  # noqa: E402
from exit_pepg import MODS  # noqa: E402

SRC = Path("/var/www/screener/premarket/data/star_exit_setups.jsonl")
COST, K = 0.2, 2.0


def sim(bars, mins, bi, P, mode, floor):
    hi = P; trail = P * 0.99
    pv = sum((b["h"] + b["l"] + b["c"]) / 3 * b["v"] for b in bars[:bi]); cv = sum(b["v"] for b in bars[:bi])
    for j in range(bi, len(bars)):
        b = bars[j]
        pv += (b["h"] + b["l"] + b["c"]) / 3 * b["v"]; cv += b["v"]; vw = pv / cv if cv else b["c"]
        if mode == "T0":
            if b["l"] <= trail:
                px = min(trail, b["o"]) if j > bi else trail
                return (px / P - 1) * 100 - COST, j, "trail"
        else:
            if floor and b["l"] <= floor:                       # hard floor, intrabar
                px = min(floor, b["o"]) if j > bi else floor
                return (px / P - 1) * 100 - COST, j, "floor"
        if b["h"] > hi:
            hi = b["h"]; trail = max(trail, hi * 0.99)
        if mins[j] >= 385:
            return (b["c"] / P - 1) * 100 - COST, j, "15:55"
        if mode != "T0" and b["c"] < trail and j + 1 < len(bars):
            if mode in ("T2", "T3", "T4"):
                r1 = sum(x["h"] - x["l"] for x in bars[max(0, j - 14):j + 1]) / min(15, j + 1)
                noise = (hi - b["c"]) < K * r1 and (mode != "T2" or b["c"] >= vw)
                if noise:
                    continue
            return (bars[j + 1]["o"] / P - 1) * 100 - COST, j + 1, "trail (close)"
    return (bars[-1]["c"] / P - 1) * 100 - COST, len(bars) - 1, "end"


def main():
    T = [json.loads(l) for l in open(SRC)]
    by = defaultdict(list)
    for t in T:
        by[t["day"]].append(t)
    rows = []
    for day in sorted(by):
        d = json.load(gzip.open(R.OW / "bars" / f"bars_{day}.json.gz", "rt"))
        for t in by[day]:
            s = t["sym"]; ref = R.REF.load(day, s); fl = json.loads((R.OW / "flow" / day / f"{s}.json").read_text())
            bars = [b for b in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(b["t"]) < 390]
            mins = [R.minute(b["t"]) for b in bars]
            ti = next((i for i, m in enumerate(mins) if m == t["m"]), None)
            bi = next((i for i, m in enumerate(mins) if m >= t["buy_m"]), None)
            if ti is None or bi is None:
                continue
            P = t["buy"]
            ok, info = MODS[t["setup"]].check(bars[:ti + 1], fl, ref, t["m"])
            sup = (info or {}).get("support") or P * 0.99
            sfloor = min(max(sup * 0.998, P * 0.96), P * 0.995)
            row = {"setup": t["setup"], "day": day, "atr": t["atr"], "star": t["pl"], "trail2y": t["trail"]}
            for mode, floor in (("T0", None), ("T1", None), ("T2", P * 0.97), ("T3", P * 0.97), ("T4", sfloor)):
                pl, j, why = sim(bars, mins, bi, P, mode, floor)
                row[mode] = pl; row[mode + "_hold"] = mins[j] - t["buy_m"]; row[mode + "_why"] = why
            rows.append(row)
        R.REF._CACHE.clear(); del d
    days = sorted({r["day"] for r in rows}); half = days[len(days) // 2]
    def line(lab, X):
        if not X:
            return
        h = np.array([r["day"] < half for r in X])
        cells = []
        for k in ("star", "T0", "T1", "T2", "T3", "T4"):
            a = np.array([r[k] for r in X])
            cells.append(f"{a.mean():+.3f}% ({a[h].mean() if h.any() else 0:+.2f}/{a[~h].mean() if (~h).any() else 0:+.2f})")
        holds = " ".join(f"{k} {np.median([r[k + '_hold'] for r in X]):.0f}" for k in ("T0", "T3", "T4"))
        print(f"   {lab:6} {len(X):5} | " + " | ".join(cells) + f" | median hold min: {holds}")
    print(f"{len(rows)} trades, {len(days)} days {days[0]}..{days[-1]}; per trade after {COST}% cost (half 1 / half 2)")
    print(f"   {'':6} {'n':>5} | {'STAR sells':^22} | {'T0 1% trail':^22} | {'T1 trail at close':^22} | {'T2 + noise2 (VWAP)':^22} | "
          f"{'T3 + noise2 no VWAP':^22} | {'T4 = T3, floor support':^22}")
    line("ALL", rows)
    for s in MODS:
        line(s, [r for r in rows if r["setup"] == s])
    for lab, lo, hi in (("ATR<6", 0, 6), ("6-10", 6, 10), (">=10", 10, 999)):
        line(lab, [r for r in rows if lo <= r["atr"] < hi])
    for k in ("T2", "T3", "T4"):
        w = defaultdict(int)
        for r in rows:
            w[r[k + "_why"]] += 1
        print(f"   {k} exits: {dict(w)}")
    print("TRAILNOISE_DONE")


if __name__ == "__main__":
    main()
