"""
gbfloor_test.py -- [2026-10-23] HELP 7/3/25: the live give-back sold 10:03 at 7.73 (+0.72%) on a 1,709-share bar that opened
4 cents lower -- the 1/4 give-back was 2.8 cents while HELP's normal 1-min range was 6.6 cents (same as JOBY / DERM). The user:
sell where the old test did (10:11, 7.84, +2.15%: the first heavy seller bar after the 7.90 push).
Test (no look-ahead, as the live code): the give-back LEVEL gets a NOISE FLOOR -- level = peak - max(g x gain, k x the mean 1-min
range of the 15 finished bars before) -- and/or a higher ARM. Grid arm 1 / 1.5 / 2 %, k 0 / 1 / 1.5 / 2. 833 EV3 buys, 0.2% cost.
Also with the N2+N3 no-trade gate (the 535 kept buys).
"""
import gzip, json, sys
from collections import defaultdict
import numpy as np
sys.path.insert(0, "/var/www/screener/trade/reports/playbook"); sys.path.insert(0, "/var/www/screener/trade")
import v2_bar_replay as R
import r1b_setup
from exit_pepg import MODS
MODS = {**MODS, "R1B": r1b_setup}
COST = 0.2; SPLIT = "2025-10-01"
GRID = [(a, k) for a in (1.0, 1.5, 2.0) for k in (0, 1.0, 1.5, 2.0)]


def sim(bars, mins, bi, P, stop, arm, k, g=0.25):
    peak = P
    for j in range(bi, len(bars)):
        b = bars[j]
        if b["l"] <= stop:
            return (min(stop, b["o"]) if j > bi else stop) / P * 100 - 100 - COST, j
        gain = peak - P
        if gain >= P * arm / 100 and j > bi:
            w = bars[max(0, j - 15):j]
            rng = sum(x["h"] - x["l"] for x in w) / len(w)
            lvl = peak - max(g * gain, k * rng)
            x = min(lvl, bars[j - 1]["c"] * 0.9999)
            if b["l"] <= x:
                return min(x, b["o"]) / P * 100 - 100 - COST, j
        peak = max(peak, b["h"])
        if mins[j] >= 385:
            return b["c"] / P * 100 - 100 - COST, j
    return bars[-1]["c"] / P * 100 - 100 - COST, len(bars) - 1


nt = {(r["day"], r["sym"], r["m"]): (r["f"]["N2"] or r["f"]["N3"]) for r in json.load(open("notrade.json"))}
trig = defaultdict(list)
for l in open("/var/www/screener/trade/reports/playbook/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, "m": t["m"], "nt": nt.get((day, s, t["m"]), False)}
        for a, k in GRID:
            r[f"a{a}k{k}"], j = sim(bars, mins, bi, P, stop, a, k)
            r[f"a{a}k{k}_t"] = mins[j]
        rows.append(r)
    R.REF._CACHE.clear(); del d
json.dump(rows, open("gbfloor.json", "w"))
for lab, X in (("ALL 833", rows), ("after N2+N3 (kept)", [r for r in rows if not r["nt"]])):
    y = np.array([r["day"] < SPLIT for r in X])
    print(f"\n{lab}: {len(X)} buys, per trade after 0.2% cost (year 1 / year 2)")
    for a, k in GRID:
        v = np.array([r[f"a{a}k{k}"] for r in X])
        print(f"   arm {a:.1f}%  floor {k:.1f} x range   {v.mean():+.3f}% ({v[y].mean():+.3f} / {v[~y].mean():+.3f})  win {np.mean(v > 0):.0%}  total {v.sum():+.1f}%")
for r in rows:
    if (r["sym"], r["day"]) in (("HELP", "2025-07-03"), ("JOBY", "2024-10-23"), ("DERM", "2024-11-05"), ("QUBT", "2025-05-20")):
        hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"
        print(" ", r["sym"], r["day"], " ".join(f"a{a}k{k}:{r[f'a{a}k{k}']:+.2f}@{hm(r[f'a{a}k{k}_t'])}" for a, k in GRID))
print("GBFLOOR_DONE")
