"""
exit_pepg.py -- [2026-10-23] the user's exit idea from the PEPG 10/1/2025 chart, tested on the SAME 3,809 setup buys as the
Star-exit test (premarket/data/star_exit_setups.jsonl, 1 year, R1 R1A R3 R4 R5 R7 R8 R9; buy at the next open, 0.2% cost):
  STOP     under the setup's own support (the level it bought at) minus buf (0.2%) -- not a fixed % (clamped to 0.5%..4% under
           the buy so it is never on top of the price nor absurdly wide)
  HOLD     no selling on noise or on a thin spike into VWAP
  SELL     at the next open when a HEAVY SELLER BAR appears at or above VWAP: volume >= heavy_x (2x) the stock's normal and
           buyers <= heavy_bs (25%)  [PEPG 11:14: 19k shares, 11% buyers at the high, above VWAP]
  else     the support stop, or 15:55
Variants: A = the rule as above | B = heavy seller bar anywhere (not only >= VWAP) | C = A + lock-in: once +2% is reached the stop
moves to +0.5% | D = A with heavy_x 1.5 / heavy_bs 30%.
Compared with Star's sells and the 1% trailing stop on the same trades.
    nice -n 19 python3 exit_pepg.py   -> exit_pepg.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
import r1_setup, r1a_setup, r3_setup, r4_setup, r5_setup, r7_setup, r8_setup, r9_setup  # noqa: E402,E401

MODS = {"R1": r1_setup, "R1A": r1a_setup, "R3": r3_setup, "R4": r4_setup, "R5": r5_setup, "R7": r7_setup, "R8": r8_setup,
        "R9": r9_setup}
SRC = Path("/var/www/screener/premarket/data/star_exit_setups.jsonl")
COST = 0.2
VARIANTS = {"A": dict(any_vwap=False, lock=False, hx=2.0, hb=0.25), "B": dict(any_vwap=True, lock=False, hx=2.0, hb=0.25),
            "C": dict(any_vwap=False, lock=True, hx=2.0, hb=0.25), "D": dict(any_vwap=False, lock=False, hx=1.5, hb=0.30)}


def simulate(bars, mins, fb, fs, vpm, bi, P, stop0, v):
    stop = stop0
    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]; m = mins[j]
        pv += (b["h"] + b["l"] + b["c"]) / 3 * b["v"]; cv += b["v"]; vw = pv / cv if cv else b["c"]
        if b["l"] <= stop:
            px = min(stop, b["o"]) if j > bi else stop
            return (px / P - 1) * 100 - COST, j, "stop"
        if v["lock"] and b["h"] >= P * 1.02:
            stop = max(stop, P * 1.005)
        if m >= 385:
            return (b["c"] / P - 1) * 100 - COST, j, "15:55"
        t_ = fb[m] + fs[m]
        heavy = vpm and m < len(vpm) and vpm[m] and b["v"] >= v["hx"] * vpm[m] and t_ and fb[m] / t_ <= v["hb"]
        if heavy and j > bi and (v["any_vwap"] or b["h"] >= vw) and j + 1 < len(bars):
            return (bars[j + 1]["o"] / P - 1) * 100 - COST, j + 1, "heavy seller bar"
    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)
    res = defaultdict(list)
    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
            ok, info = MODS[t["setup"]].check(bars[:ti + 1], fl, ref, t["m"])
            P = t["buy"]
            sup = (info or {}).get("support") or P * 0.99
            stop0 = min(max(sup * 0.998, P * 0.96), P * 0.995)
            row = {"setup": t["setup"], "day": day, "atr": t["atr"], "star": t["pl"], "trail": t["trail"],
                   "stop_dist": round((1 - stop0 / P) * 100, 2)}
            for vn, v in VARIANTS.items():
                pl, j, why = simulate(bars, mins, fl["buy"], fl["sell"], ref.get("vol_per_min") or [], bi, P, stop0, v)
                row[vn] = pl; row[vn + "_why"] = why; row[vn + "_hold"] = mins[j] - t["buy_m"]
            res[t["setup"]].append(row)
        R.REF._CACHE.clear(); del d
    allr = [r for v in res.values() for r in v]
    days = sorted({r["day"] for r in allr}); half = days[len(days) // 2]
    def line(lab, X):
        h = np.array([r["day"] < half for r in X])
        f = lambda k: np.array([r[k] for r in X], float)
        cells = []
        for k in ("star", "trail", "A", "B", "C", "D"):
            a = f(k)
            cells.append(f"{a.mean():+.3f}% ({a[h].mean() if h.any() else 0:+.2f}/{a[~h].mean() if (~h).any() else 0:+.2f})")
        print(f"   {lab:6} {len(X):5} | " + " | ".join(cells) + f" | stop {np.median(f('stop_dist')):.1f}% under, A hold {np.median(f('A_hold')):.0f} min")
    print(f"{len(allr)} trades, {len(days)} days {days[0]}..{days[-1]}; per trade after {COST}% cost (half 1 / half 2)")
    print(f"   {'setup':6} {'n':>5} | {'STAR sells':^22} | {'1% trailing':^22} | {'A heavy seller >=VWAP':^22} | {'B heavy seller any':^22} | "
          f"{'C = A + lock +0.5%':^22} | {'D = A looser':^22}")
    line("ALL", allr)
    for s in MODS:
        if res[s]:
            line(s, res[s])
    for lab, lo, hi in (("ATR<6", 0, 6), ("6-10", 6, 10), (">=10", 10, 999)):
        line(lab, [r for r in allr if lo <= r["atr"] < hi])
    w = defaultdict(int)
    for r in allr:
        w[r["A_why"]] += 1
    print("   A exits:", dict(w))
    print("EXITPEPG_DONE")


if __name__ == "__main__":
    main()
