"""
exit_realistic_2y.py -- [2026-10-23] EV3 dry check found a LOOK-AHEAD in the tested 1/4 give-back (exit_giveback.giveback):
it sold AT the give-back level only if that same bar later CLOSED down -- the live bot can't know the close when the price
touches the level. Rerun the 2 years on the EV3 buys (R1A, R1B, R4, R3 ATR 6-10%; giveback_2y.jsonl triggers, buy next open,
same stop, 0.2% cost) with exits that are possible live:
  A  the tested one (look-ahead) -- reference only
  B  INTRABAR, no look-ahead (= the live code): armed + the price touches the level while it is under the last finished
     close -> sell there (level, or the previous close if the level is above it, or the open if it gapped under)
  C  AT THE BAR CLOSE: armed + the bar closes at/under the level and under the close before -> sell at the next open
YEAR 1 2024-10..2025-09 (not used to choose) | YEAR 2 2025-10..2026-10.
    nice -n 19 python3 exit_realistic_2y.py -> exit_realistic_2y.log
"""
import gzip, json, 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
import r1b_setup
from exit_pepg import MODS
from exit_giveback import giveback
MODS = {**MODS, "R1B": r1b_setup}
COST = 0.2; SPLIT = "2025-10-01"


def real(bars, mins, bi, P, stop, mode, arm=1.0, g=0.25):
    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, "stop"
        gain = peak - P
        if gain >= P * arm / 100 and j > bi:
            lvl = peak - g * gain; pc = bars[j - 1]["c"]
            if mode == "B":
                x = min(lvl, pc * 0.9999)
                if b["l"] <= x:
                    return (min(x, b["o"]) / P - 1) * 100 - COST, "give-back"
        peak = max(peak, b["h"])
        if mins[j] >= 385:
            return (b["c"] / P - 1) * 100 - COST, "15:55"
        if mode == "C" and j > bi:
            gain = peak - P
            if gain >= P * arm / 100 and b["c"] <= peak - g * gain and b["c"] < bars[j - 1]["c"] and j + 1 < len(bars):
                return (bars[j + 1]["o"] / P - 1) * 100 - COST, "give-back"
    return (bars[-1]["c"] / P - 1) * 100 - COST, "end"


def main():
    trig = defaultdict(list)
    for l in open(HERE / "giveback_2y.jsonl"):
        t = json.loads(l)
        if t["setup"] in ("R1A", "R1B", "R4") or (t["setup"] == "R3" and 6 <= t["atr"] < 10):
            trig[t["day"]].append(t)
    rows = []
    for day in sorted(trig):
        d = json.load(gzip.open(R.OW / "bars" / f"bars_{day}.json.gz", "rt"))
        for t in trig[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)
            if ti is None or ti + 1 >= len(bars):
                continue
            bi = ti + 1; P = bars[bi]["o"]
            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)
            r = {"setup": t["setup"], "day": day, "sym": s}
            r["A"] = giveback(bars, mins, bi, P, stop, 1.0, 0.25)[0]
            for k in "BC":
                r[k], r[k + "_why"] = real(bars, mins, bi, P, stop, k)
            rows.append(r)
        R.REF._CACHE.clear(); del d
        print(day, len(rows), flush=True)
    json.dump(rows, open(HERE / "exit_realistic_2y.json", "w"))
    print(f"\n{len(rows)} EV3 trades; per trade after {COST}% cost: all (year 1 / year 2) win%")
    for s in ["ALL", "R1A", "R1B", "R3", "R4"]:
        X = rows if s == "ALL" else [r for r in rows if r["setup"] == s]
        y = np.array([r["day"] < SPLIT for r in X]); cells = []
        for k in "ABC":
            a = np.array([r[k] for r in X])
            cells.append(f"{k} {a.mean():+.3f}% ({a[y].mean():+.3f}/{a[~y].mean():+.3f}) {np.mean(a > 0):.0%}")
        print(f"   {s:4} {len(X):5} | " + " | ".join(cells))
    print("REAL2Y_DONE")


if __name__ == "__main__":
    main()
