"""
giveback_2y.py -- [2026-10-23] the user: check the 1/4 GIVE-BACK exit (chosen on 2025-10..2026-10) on the OTHER year too, and
add R1B (PEPG deep V, built but never run).
Triggers: setups_2y.jsonl (R1 R1A R3 R4 R5 R7 R8 R9, both years) + R1B scanned here on every top-30 stock-day (its own
cool-down). Buy at the next open after the trigger bar.
Exit = stop under the setup's support (support x 0.998, clamped 0.5%..4% under the buy; R1B: under the V low) + arm at +1% +
sell on a 1/4 give-back of the peak gain while the bar closes down + 15:55. 0.2% cost. Reference: plain 1% trail.
YEAR 1 = 2024-10-01..2025-09-30 (NOT used to choose the exit) | YEAR 2 = 2025-10-01..2026-10-02 (used).
    nice -n 19 python3 giveback_2y.py   -> giveback_2y.jsonl + giveback_2y.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 r1b_setup  # noqa: E402
from exit_pepg import MODS  # noqa: E402
from exit_giveback import giveback  # noqa: E402
from exit_trail_noise import sim as trail_sim  # noqa: E402

MODS = {**MODS, "R1B": r1b_setup}
TRIG = HERE / "setups_2y.jsonl"
OUT = HERE / "giveback_2y.jsonl"
SPLIT = "2025-10-01"


def main():
    trig = defaultdict(list)
    for l in open(TRIG):
        t = json.loads(l)
        if t["setup"] in MODS:
            trig[t["day"]].append((t["setup"], t["sym"], t["m"], t["atr"]))
    with open(OUT, "w") as out:
        for p in sorted(R.OW.glob("bars/bars_20*.json.gz")):
            day = p.name[5:15]
            if day > "2026-10-02":
                continue
            d = json.load(gzip.open(p, "rt")); n = 0
            tl = list(trig.get(day, []))
            cache = {}
            for s in d["top30_current"]:
                fp = R.OW / "flow" / day / f"{s}.json"; ref = R.REF.load(day, s)
                if s not in d["symbols"] or not fp.exists() or not ref or not ref.get("atr14"):
                    continue
                fl = json.loads(fp.read_text())
                bars = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]
                if len(bars) < 100:
                    continue
                cache[s] = (ref, fl, bars, [R.minute(x["t"]) for x in bars])
                last = -9999                                       # R1B scan
                for i in range(len(bars) - 1):
                    m = cache[s][3][i]
                    if m >= 360:
                        break
                    if m - last < r1b_setup.DEFAULTS["cooldown"]:
                        continue
                    ok, _ = r1b_setup.check(bars[:i + 1], fl, ref, m)
                    if ok:
                        last = m; tl.append(("R1B", s, m, round(ref["atr14"] / ref["prev_close"] * 100, 1)))
            for setup, s, m, atr in tl:
                if s not in cache:
                    continue
                ref, fl, bars, mins = cache[s]
                ti = next((i for i, x in enumerate(mins) if x == m), None)
                if ti is None or ti + 1 >= len(bars):
                    continue
                bi = ti + 1; P = bars[bi]["o"]
                ok, info = MODS[setup].check(bars[:ti + 1], fl, ref, m)
                sup = (info or {}).get("support") or P * 0.99
                stop = min(max(sup * 0.998, P * 0.96), P * 0.995)
                gb, j, why = giveback(bars, mins, bi, P, stop, 1.0, 0.25)
                tr = trail_sim(bars, mins, bi, P, "T0", None)[0]
                out.write(json.dumps({"setup": setup, "day": day, "sym": s, "m": m, "atr": atr, "gb": round(gb, 3), "why": why,
                                      "hold": mins[j] - mins[bi], "trail": round(tr, 3), "stop_pct": round((1 - stop / P) * 100, 2)}) + "\n")
                n += 1
            R.REF._CACHE.clear(); del d
            print(day, n, flush=True)
    report()


def report():
    T = [json.loads(l) for l in open(OUT)]
    print(f"\n{len(T)} trades; per trade after 0.2% cost | YEAR 1 2024-10..2025-09 = not used to pick the exit | YEAR 2 = used")
    print(f"   {'setup':6} | {'YEAR 1: n':>10} {'give-back':>10} {'1% trail':>9} {'win':>5} | {'YEAR 2: n':>10} {'give-back':>10} {'1% trail':>9} {'win':>5} | both years")
    for s in ["ALL", "R1", "R1A", "R1B", "R3", "R4", "R5", "R7", "R8", "R9"]:
        X = T if s == "ALL" else [t for t in T if t["setup"] == s]
        if not X:
            continue
        cells = []
        for y in (True, False):
            Y = [t for t in X if (t["day"] < SPLIT) == y]
            if Y:
                g = np.array([t["gb"] for t in Y]); tr = np.array([t["trail"] for t in Y])
                cells.append(f"{len(Y):10} {g.mean():+9.3f}% {tr.mean():+8.3f}% {np.mean(g > 0):4.0%}")
            else:
                cells.append(f"{0:10} {'-':>10} {'-':>9} {'-':>5}")
        g = np.array([t["gb"] for t in X])
        print(f"   {s:6} | " + " | ".join(cells) + f" | {g.mean():+.3f}% ({len(X)})")
    print("  by daily ATR, both years (give-back):")
    for s in ["R1A", "R1B", "R3", "R4", "R7"]:
        for lab, lo, hi in (("<6%", 0, 6), ("6-10%", 6, 10), (">=10%", 10, 999)):
            X = [t for t in T if t["setup"] == s and lo <= t["atr"] < hi]
            if len(X) >= 15:
                g = np.array([t["gb"] for t in X]); y = np.array([t["day"] < SPLIT for t in X])
                print(f"   {s:4} ATR {lab:6} {len(X):5} {g.mean():+.3f}% (y1 {g[y].mean() if y.any() else 0:+.3f} y2 {g[~y].mean() if (~y).any() else 0:+.3f})")
    print("GB2Y_DONE")


if __name__ == "__main__":
    if "--report" in sys.argv:
        report()
    else:
        main()
