"""
sim_cache.py -- [2026-10-24] fast gate tests. PASS 1 (slow, once per period): every minute where any EV3 setup's check is true
(ignoring cool-downs, so any gate can be replayed exactly), with the gate features (N2 / N3 / A3 RVOL / A20 gap / ATR %) and the
result of buying it at the next open (stop under the support, C3 exit) -> cache_<period>.json.gz.
PASS 2 (seconds): the account replay = sim_full's logic (setup order, per-setup cool-down set on any true check, gates, one
setup per stock per minute, 5 slots, 1% risk / 19% cap, re-entry above a losing entry, last buy 15:15) with any GATE set.
    python3 sim_cache.py build 10y|lib        python3 sim_cache.py replay
"""
import gzip, json, math, 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/reports/playbook"); sys.path.insert(0, "/var/www/screener/trade")
import v2_bar_replay as R
import ev3 as E
from sim_full import loader, CFG
from sim_2y import sim as exit_sim
START = 100000.0; LAST_BUY_M = 344


def build(src):
    days, load_day = loader(src, "tick")
    out = {}
    for day in days():
        if src == "10y" and day > "2018-11-23":
            continue
        if src == "lib" and day > "2026-10-02":
            continue
        stocks = load_day(day); rows = []
        for rank, (s, D) in enumerate(stocks):
            ref = D.ref
            if not ref or not ref.get("atr14") or not ref.get("prev_close"):
                continue                               # as sim_full.entries: no trading without a reference
            atrp = ref["atr14"] / ref["prev_close"] * 100
            vpm = ref.get("vol_per_min") or []; gap = (D.b[0]["o"] / ref["prev_close"] - 1) * 100
            cv = np.cumsum([x["v"] for x in D.b])
            for i in range(4, len(D.b) - 1):
                m = D.m[i]
                if m >= CFG["last_entry_minute"]:
                    break
                done = D.b[:i + 1]
                for name in CFG["order"]:
                    sc = CFG["setups"].get(name) or {}
                    if name == "R1B":
                        continue
                    if "atr_min" in sc and atrp < sc["atr_min"] or "atr_max" in sc and atrp >= sc["atr_max"]:
                        continue
                    try:
                        ok, info = E.MODS[name].check(done, D.fl, ref, m, {k: v for k, v in sc.items() if k not in E.CONTROL_KEYS} or None)
                    except Exception:
                        ok = False
                    if not ok:
                        continue
                    P = D.b[i + 1]["o"]; Pc = done[-1]["c"]
                    sup = (info or {}).get("support") or P * 0.99
                    stop = min(max(sup * (1 - CFG["stop_buf"]), P * (1 - CFG["stop_max_pct"] / 100)), P * (1 - CFG["stop_min_pct"] / 100))
                    if P <= stop:
                        continue
                    pl, j, why = exit_sim(D, i + 1, P, stop, CFG["arm_pct"], "C3")
                    B = sum(D.fl["buy"][max(0, m - 14):m + 1]); S = sum(D.fl["sell"][max(0, m - 14):m + 1])
                    norm = sum(vpm[:m + 1]) if len(vpm) > m else 0
                    rows.append([s, rank, m, name, round(P, 4), round(stop, 4), round(pl, 3), D.m[j], why,
                                 bool(ref.get("prev_low") and Pc < ref["prev_low"]), round(B / (B + S), 3) if B + S else 0.5,
                                 round(cv[i] / norm, 2) if norm else None, round(gap, 2), round(atrp, 2)])
        out[day] = rows
        R.REF._CACHE.clear()
        print(day, len(stocks), len(rows), flush=True)
    json.dump(out, gzip.open(HERE / f"cache_{src}.json.gz", "wt"))
    print("CACHE_DONE")


GATES = {
    "live (N2+N3)": {},
    "R3 + A3 + A20": {"R3": ["A3", "A20"]},
    "A20 all except R1A": {s: ["A20"] for s in ("R1D", "R1E", "R4", "R3")},
    "R3 + A3 + A20, A20 on R1D R1E R4": {"R3": ["A3", "A20"], "R1D": ["A20"], "R1E": ["A20"], "R4": ["A20"]},
}


def blocked(r, name, extra):
    s, rank, m, st, P, stop, pl, xm, why, n2, bs15, rvol, gap, atrp = r
    sc = CFG["setups"].get(name) or {}
    if not sc.get("no_trade_exempt") and CFG["no_trade"].get("enabled") and (n2 or bs15 < CFG["no_trade"]["min_bs15"]):
        return True
    for g in extra.get(name, []):
        if g == "A3" and rvol is not None and rvol < 1.5:
            return True
        if g == "A20" and -3 <= gap <= -0.5:
            return True
    return False


def replay(cache, extra):
    eq = START; trades = []; daily = []
    for day in sorted(cache):
        by = defaultdict(list)
        for r in cache[day]:
            by[(r[0], r[2])].append(r)
        last = defaultdict(dict); ev = []
        for (s, m) in sorted(by, key=lambda z: (z[1], z[0])):
            rs = {r[3]: r for r in by[(s, m)]}
            for name in CFG["order"]:
                r = rs.get(name)
                if r is None or (CFG["setups"].get(name) or {}).get("enabled") is False:
                    continue
                if m - last[s].get(name, -9999) < E.MODS[name].DEFAULTS.get("cooldown", 15):
                    continue
                last[s][name] = m
                if blocked(r, name, extra):
                    continue
                ev.append(r); break
        ev.sort(key=lambda r: (r[2] + 1, r[1]))
        open_pos = []; lastt = {}; realized = 0.0; e0 = eq
        for r in ev:
            s, rank, m, st, P, stop, pl, xm, why = r[:9]; bm = m + 1
            if bm > LAST_BUY_M:
                continue
            for op in list(open_pos):
                if op["exit_m"] <= bm:
                    open_pos.remove(op); realized += op["pl_usd"]; lastt[op["sym"]] = op
            if any(op["sym"] == s for op in open_pos) or len(open_pos) >= 5:
                continue
            if s in lastt and lastt[s]["pl_usd"] <= 0 and not P > lastt[s]["entry"] + 0.01:
                continue
            equity = e0 + realized
            qty = min(math.floor(equity * 0.01 / (P - stop)), math.floor(equity * 0.19 / P))
            if qty < 1:
                continue
            t = {"day": day, "sym": s, "setup": st, "exit_m": xm, "entry": P, "pl_pct": pl, "pl_usd": qty * P * pl / 100, "why": why}
            open_pos.append(t); trades.append(t)
        realized += sum(op["pl_usd"] for op in open_pos); eq = e0 + realized; daily.append((day, eq))
    return trades, daily


def summary(trades, daily):
    e = np.array([x[1] for x in daily]); dd = (e / np.maximum.accumulate(e) - 1).min() * 100
    a = np.array([t["pl_usd"] for t in trades]); half = daily[len(daily) // 2][0]
    h1 = sum(t["pl_usd"] for t in trades if t["day"] < half); h2 = a.sum() - h1
    per = " ".join(f"{s} {len(X)}:{np.mean([t['pl_pct'] for t in X]):+.2f}%" for s in CFG["order"] for X in [[t for t in trades if t["setup"] == s]] if X)
    return (f"${e[-1]:>9,.0f} ({(e[-1] / START - 1) * 100:+5.1f}%) DD {dd:5.1f}% | {len(trades):3} trades win {np.mean(a > 0):.0%} "
            f"avg {np.mean([t['pl_pct'] for t in trades]):+.3f}% | halves ${h1:+,.0f} / ${h2:+,.0f} | {per}")


def main():
    if sys.argv[1] == "build":
        build(sys.argv[2]); return
    C = {p: json.load(gzip.open(HERE / f"cache_{s}.json.gz", "rt")) for p, s in (("2016-18", "10y"), ("2024-26", "lib"))}
    for g, extra in GATES.items():
        print(f"\n== {g}")
        for p in C:
            print(f"   {p}: " + summary(*replay(C[p], extra)))
    print("REPLAY_DONE")


if __name__ == "__main__":
    main()
