"""
v2_rule_variants.py -- [2026-10-09] The user (10/9 review: 33 of 96 scanner stocks rose >= 3%, v2 bought 1):
test looser / ATR-scaled versions of the v2 entry rules, ONE RULE AT A TIME (entries tested separately -- the live
exits stay the same). 2-year bar replay (v2_bar_replay.run_stock: the real entry_v2 + exit_v2 code, every signal,
no slot limit), the 9:30 top-30 lists of reports/open_window/bars (~503 days, Oct 2024 - Oct 2026).
Scored at the REAL ~0.2% round-trip cost. Every trade also says whether the stock is a v3 scanner pick that day
(the bots' list since 10/9; the 2-year set holds the OLD list, so only part of the v3 picks are in it) and its ATR.
    python3 v2_rule_variants.py [START..END]        default 2024-10-01..2026-10-02
    python3 v2_rule_variants.py --report            (from v2_rule_variants.jsonl)
"""
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, str(HERE.parent / "open_window"))
import v2_bar_replay as R  # noqa: E402
from up2_styles_build import v3_top30  # noqa: E402

OUT = HERE / "v2_rule_variants.jsonl"
COST = 0.2


def atr_pct(ref):
    return ref["atr14"] / ref["prev_close"] * 100 if ref.get("atr14") and ref.get("prev_close") else None


# name -> function(base cfg, atr %) -> cfg for that stock
VARIANTS = {
    "base (live)": lambda c, a: c,
    "volume 1.2x": lambda c, a: {**c, "min_rvol": 1.2},
    "volume 1.0x": lambda c, a: {**c, "min_rvol": 1.0},
    "volume off if ATR>=8%": lambda c, a: {**c, "min_rvol": 0.0} if a and a >= 8 else c,
    "steady 0.6/0.4": lambda c, a: {**c, "min_r2": 0.6, "min_eff": 0.4},
    "steady 0.5/0.35": lambda c, a: {**c, "min_r2": 0.5, "min_eff": 0.35},
    "steady 0.5/0.35 if ATR>=8%": lambda c, a: {**c, "min_r2": 0.5, "min_eff": 0.35} if a and a >= 8 else c,
    "extended 0.5x ATR": lambda c, a: {**c, "max_above_open_pct": max(3.0, 0.5 * a)} if a else c,
    "extended 0.75x ATR": lambda c, a: {**c, "max_above_open_pct": max(3.0, 0.75 * a)} if a else c,
    "extended 1x ATR": lambda c, a: {**c, "max_above_open_pct": max(3.0, 1.0 * a)} if a else c,
    "VWAP 0..+3%": lambda c, a: {**c, "max_vwap_pct": 3.0},
    "VWAP 0..0.3x ATR": lambda c, a: {**c, "max_vwap_pct": max(2.0, 0.3 * a)} if a else c,
}


def run(rng):
    a, b = rng.split("..")
    cfg = R.get_config()
    ecfg = {**(cfg.get("entry_v2") or {}), "confirm_checks": 1}
    xcfg = {**(cfg.get("exit_v2") or {}), "enabled": True}
    with open(OUT, "w") as out:
        for p in sorted(R.OW.glob("bars/bars_20*.json.gz")):
            day = p.name[5:15]
            if not (a <= day <= b):
                continue
            d = json.load(gzip.open(p, "rt"))
            bench = R.bench_pct(day)
            v3 = v3_top30(day)
            k = defaultdict(int)
            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:
                    continue
                flow = json.loads(fp.read_text()); ap = atr_pct(ref)
                cache = {}                         # same settings for this stock -> same trades (1 CPU: skip reruns)
                for v, f in VARIANTS.items():
                    c = f(ecfg, ap); key = json.dumps(c, sort_keys=True, default=str)
                    if key not in cache:
                        cache[key] = R.run_stock(day, s, d["symbols"][s]["bars"], flow, ref, bench, c, xcfg)
                    for t in cache[key]:
                        out.write(json.dumps({"v": v, "day": day, "sym": s, "buy_m": t["buy_m"], "pl_gross": t["pl"] + R.COST,
                                              "why": t.get("why"), "v3": s in v3, "atr": ap}) + "\n")
                        k[v] += 1
            R.REF._CACHE.clear()
            del d
            print(day, dict(k), flush=True)
    print("VARIANTS_DONE")


def report():
    T = [json.loads(l) for l in open(OUT)]
    days = sorted({t["day"] for t in T}); half = days[len(days) // 2]
    base = {(t["day"], t["sym"], t["buy_m"]) for t in T if t["v"] == "base (live)"}
    print(f"{len(days)} days {days[0]}..{days[-1]}; per trade after {COST}% cost; every signal, no slot limit\n")
    print(f"{'variant':28} {'trades':>7} {'per trade':>10} {'total':>9} {'win':>5} | {'half 1':>8} {'half 2':>8} | "
          f"{'EXTRA trades vs live':>21} | {'v3 picks':>16} | {'ATR>=8%':>16}")
    for v in VARIANTS:
        X = [t for t in T if t["v"] == v]
        p = np.array([t["pl_gross"] - COST for t in X]); h = np.array([t["day"] < half for t in X])
        ex = np.array([t["pl_gross"] - COST for t in X if (t["day"], t["sym"], t["buy_m"]) not in base])
        v3 = np.array([t["pl_gross"] - COST for t in X if t["v3"]])
        hi = np.array([t["pl_gross"] - COST for t in X if (t["atr"] or 0) >= 8])
        f = lambda z: f"{len(z):5} {z.mean():+.3f}%" if len(z) else f"{0:5}      -"
        print(f"{v:28} {len(p):7} {p.mean():+9.3f}% {p.sum():+8.1f}% {np.mean(p > 0):4.0%} | {p[h].mean():+7.3f}% "
              f"{p[~h].mean():+7.3f}% | {f(ex):>21} | {f(v3):>16} | {f(hi):>16}")


if __name__ == "__main__":
    if "--report" in sys.argv:
        report()
    else:
        run(sys.argv[1] if len(sys.argv) > 1 else "2024-10-01..2026-10-02")
