"""
x1_test.py -- [2026-10-23] 2-year test of the user's exit X1 (exit_x1.py: STALL at the top + FADE INTO RESISTANCE, armed at +2%,
break-even after arming) and the setup R1C (r1c_setup.py), NO look-ahead:
  stop / give-back = intrabar as the live bot; X1 = decided at a FINISHED bar's close -> sold at the next bar's open.
PART 1  exits on the 833 EV3 buys (R1A, R1B, R4, R3 ATR 6-10%; buy at the next open; stop under the setup support), also on
        the 535 kept by the N2+N3 no-trade gate:
   GB1   1/4 give-back armed at +1% (live now)        GB2   the same armed at +2%
   X1s   X1 stall only                                X1f   X1 fade into resistance only
   X1fn  X1 fade WITHOUT the resistance part          X1    stall OR fade
   X1g   X1 OR the +2% give-back (whichever first)    X1gn  X1 (fade without resistance) OR the +2% give-back
PART 2  R1C on every top-30 stock-day (its cool-down, 9:40-14:30), buy at the next open, stop under the flush low, same exits.
YEAR 1 2024-10-01..2025-09-30 | YEAR 2 2025-10-01..2026-10-02. 0.2% cost.
    nice -n 19 python3 x1_test.py -> x1_test.json / x1_r1c.json / x1_test.log
"""
import gzip, json, sys
from collections import defaultdict
from pathlib import Path
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, r1c_setup, exit_x1
from exit_pepg import MODS
MODS = {**MODS, "R1B": r1b_setup}
HERE = Path(__file__).resolve().parent
COST = 0.2; SPLIT = "2025-10-01"
VARS = ["GB1", "GB2", "X1s", "X1f", "X1fn", "X1", "X1g", "X1gn"]
XCFG = {"X1s": {"fade": False}, "X1f": {"stall": False}, "X1fn": {"stall": False, "res_required": False}, "X1": {},
        "X1g": {}, "X1gn": {"res_required": False}}


def sim(v, bars, mins, fl, bi, P, stop):
    gb_arm = 1.0 if v == "GB1" else 2.0 if v in ("GB2", "X1g", "X1gn") else None
    xc = XCFG.get(v)
    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, "stop", j
        if gb_arm is not None:
            gain = peak - P
            if gain >= P * gb_arm / 100 and j > bi:
                x = min(peak - 0.25 * gain, bars[j - 1]["c"] * 0.9999)
                if b["l"] <= x:
                    return min(x, b["o"]) / P * 100 - 100 - COST, "give-back", j
        peak = max(peak, b["h"])
        if mins[j] >= 385:
            return b["c"] / P * 100 - 100 - COST, "15:55", j
        if xc is not None and j + 1 < len(bars):
            sell, why = exit_x1.check(bars[:j + 1], fl, P, bi, xc)
            if sell:
                return bars[j + 1]["o"] / P * 100 - 100 - COST, why.split(":")[0], j + 1
    return bars[-1]["c"] / P * 100 - 100 - COST, "end", len(bars) - 1


def run(bars, mins, fl, bi, P, stop, r):
    for v in VARS:
        pl, why, j = sim(v, bars, mins, fl, bi, P, stop)
        r[v] = round(pl, 4); r[v + "_why"] = why; r[v + "_t"] = mins[j]


def report(rows, lab):
    y = np.array([r["day"] < SPLIT for r in rows])
    print(f"\n{lab}: {len(rows)} buys, per trade after {COST}% cost (year 1 / year 2) | win | total")
    for v in VARS:
        a = np.array([r[v] for r in rows])
        print(f"   {v:5} {a.mean():+.3f}% ({a[y].mean() if y.any() else 0:+.3f} / {a[~y].mean() if (~y).any() else 0:+.3f})  "
              f"win {np.mean(a > 0):.0%}  total {a.sum():+.1f}%")


def main():
    nt = {(r["day"], r["sym"], r["m"]): (r["f"]["N2"] or r["f"]["N3"]) for r in json.load(open(HERE / "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, rc = [], []
    for p in sorted(R.OW.glob("bars/bars_20*.json.gz")):
        day = p.name[5:15]
        if day < "2024-10-01" or day > "2026-10-02":
            continue
        d = json.load(gzip.open(p, "rt")); cache = {}
        def load(s):
            if s not in cache:
                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"):
                    cache[s] = None
                else:
                    bars = [b for b in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(b["t"]) < 390]
                    cache[s] = (ref, json.loads(fp.read_text()), bars, [R.minute(b["t"]) for b in bars])
            return cache[s]
        for t in trig.get(day, []):                                   # PART 1
            c = load(t["sym"])
            if not c:
                continue
            ref, fl, bars, mins = c
            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": t["sym"], "m": t["m"], "nt": nt.get((day, t["sym"], t["m"]), False)}
            run(bars, mins, fl, bi, P, stop, r); rows.append(r)
        for s in d["top30_current"]:                                  # PART 2: R1C scan
            c = load(s)
            if not c or len(c[2]) < 100:
                continue
            ref, fl, bars, mins = c
            O = bars[0]["o"]; lo = 1e18; lj = 0; last = -9999
            for i in range(len(bars) - 1):
                if bars[i]["l"] < lo:
                    lo, lj = bars[i]["l"], i
                m = mins[i]
                if m >= 300:
                    break
                if not (1 <= i - lj <= 2) or O - lo < r1c_setup.DEFAULTS["drop_atr"] * ref["atr14"] or m - last < r1c_setup.DEFAULTS["cooldown"]:
                    continue
                ok, info = r1c_setup.check(bars[:i + 1], fl, ref, m)
                if ok:
                    last = m; bi = i + 1; P = bars[bi]["o"]
                    stop = min(max(info["support"] * 0.998, P * 0.96), P * 0.995)
                    r = {"setup": "R1C", "day": day, "sym": s, "m": m, "atr": round(ref["atr14"] / ref["prev_close"] * 100, 1),
                         "stop_pct": round((1 - stop / P) * 100, 2)}
                    run(bars, mins, fl, bi, P, stop, r); rc.append(r)
        R.REF._CACHE.clear(); del d, cache
        print(day, len(rows), len(rc), flush=True)
    json.dump(rows, open(HERE / "x1_test.json", "w")); json.dump(rc, open(HERE / "x1_r1c.json", "w"))
    final()


def final():
    rows = json.load(open(HERE / "x1_test.json")); rc = json.load(open(HERE / "x1_r1c.json"))
    report(rows, "PART 1 -- ALL EV3 buys")
    kept = [r for r in rows if not r["nt"]]
    report(kept, "PART 1 -- EV3 buys kept by N2+N3")
    for st in ("R1A", "R1B", "R3", "R4"):
        report([r for r in kept if r["setup"] == st], f"   kept, {st}")
    if rc:
        report(rc, "PART 2 -- R1C (first reversal after a flush)")
        for lab, lo, hi in (("ATR <6%", 0, 6), ("ATR 6-10%", 6, 10), ("ATR >=10%", 10, 999)):
            X = [r for r in rc if lo <= r["atr"] < hi]
            if len(X) >= 10:
                report(X, f"   R1C {lab}")
    w = defaultdict(lambda: defaultdict(int))
    for r in kept:
        for v in VARS:
            w[v][r[v + "_why"]] += 1
    print("\n exits (kept EV3 buys):")
    for v in VARS:
        print(f"   {v:5} {dict(w[v])}")
    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"), ("QBTS", "2025-02-24")):
            print(f"  {r['sym']} {r['day']} {r['setup']}{' (N2/N3 no-trade)' if r['nt'] else ''}: " + " ".join(f"{v} {r[v]:+.2f}" for v in VARS))
    print("X1TEST_DONE")


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