"""
exit_giveback.py -- [2026-10-23] the user: test the 1/4 GIVE-BACK exit (exit_giveback_room.py / EV3) 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).
  STOP     under the setup's own support (support x 0.998, clamped 0.5%..4% under the buy), intrabar
  ARM      nothing else sells until the peak since the buy is >= arm (% of the buy price) above the buy
  GIVE-BACK once armed: sell when the price falls to peak - g x (peak - buy) while the bar is closing down (close < the
           close before = "sloping down"), at that level (or the open if it gapped under it)
  else     15:55
Grid: arm 0.75 / 1.0 / 1.5 %, g 1/4 / 1/3. Compared with Star's sells and the plain 1% trail on the same trades.
On PEPG 10/1/2025 (R1B buy 4.775, V-low stop 4.621): arm 1% g 1/4 -> sold 10:51 at 4.854, +1.45%.
    nice -n 19 python3 exit_giveback.py   -> exit_giveback.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
from exit_trail_noise import sim as trail_sim  # noqa: E402

SRC = Path("/var/www/screener/premarket/data/star_exit_setups.jsonl")
COST = 0.2
GRID = [(a, g) for a in (0.75, 1.0, 1.5) for g in (0.25, 1 / 3)]


def giveback(bars, mins, bi, P, stop, arm, g):
    peak = P
    for j in range(bi, len(bars)):
        b = bars[j]
        if b["l"] <= stop:
            px = min(stop, b["o"]) if j > bi else stop
            return (px / P - 1) * 100 - COST, j, "stop"
        gain = peak - P
        if gain >= P * arm / 100:
            lvl = peak - g * gain
            if b["l"] <= lvl and j > bi and b["c"] < bars[j - 1]["c"]:
                px = min(lvl, b["o"])
                return (px / P - 1) * 100 - COST, j, "give-back"
        peak = max(peak, b["h"])
        if mins[j] >= 385:
            return (b["c"] / P - 1) * 100 - COST, j, "15:55"
    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
            stop = min(max(sup * 0.998, P * 0.96), P * 0.995)
            row = {"setup": t["setup"], "day": day, "atr": t["atr"], "star": t["pl"]}
            row["trail"] = trail_sim(bars, mins, bi, P, "T0", None)[0]
            for a, g in GRID:
                pl, j, why = giveback(bars, mins, bi, P, stop, a, g)
                k = f"a{a}_g{round(g, 2)}"
                row[k] = pl; row[k + "_why"] = why; row[k + "_hold"] = mins[j] - t["buy_m"]
            rows.append(row)
        R.REF._CACHE.clear(); del d
    keys = ["star", "trail"] + [f"a{a}_g{round(g, 2)}" for a, g in GRID]
    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 keys:
            a = np.array([r[k] for r in X])
            cells.append(f"{a.mean():+.3f}")
        print(f"   {lab:6} {len(X):5} | " + " ".join(f"{c:>8}" for c in cells))
    print(f"{len(rows)} trades, {len(days)} days {days[0]}..{days[-1]}; per trade % after {COST}% cost")
    print(f"   {'':6} {'n':>5} | " + " ".join(f"{k.replace('a', 'arm').replace('_g0.25', ' 1/4').replace('_g0.33', ' 1/3'):>8}" for k in keys))
    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])
    print("\n   halves (first / second) for ALL:")
    for k in keys:
        a = np.array([r[k] for r in rows]); h = np.array([r["day"] < half for r in rows])
        extra = ""
        if k + "_why" in rows[0]:
            w = defaultdict(int)
            for r in rows:
                w[r[k + "_why"]] += 1
            extra = f" | exits {dict(w)} | median hold {np.median([r[k + '_hold'] for r in rows]):.0f} min"
        print(f"   {k:12} {a.mean():+.3f}% ({a[h].mean():+.3f} / {a[~h].mean():+.3f}) win {np.mean(a > 0):.0%}{extra}")
    print("GIVEBACK_DONE")


if __name__ == "__main__":
    main()
