# ===== wf_b16.py - walk-forward of the batch16 passes (#2, #3, #18), maker entries for C1/C2, autopsy skip filters =====
# Colab:  !wget -q -O wf_b16.py https://osom-boba.pages.dev/colab/wf_b16.py
#         %run wf_b16.py
# Box (synthetic smoke only):  python3 wf_b16.py --smoke
#
# Helpers are imported unchanged from batch16.py (sim, ideas #2/#3/#18, Ctx, metrics) and autopsy.py
# (market_frames / entry_features, completed-bar features only); both are auto-downloaded next to oslib.py.
# Live basket = oslib.engines(df, fund=funding(asset,'binance')) at oslib.LIVE_RISK (X7 on), 0.12%/side,
# compounded on exit time (oslib.overlay math). Test years 2020..2026, train always 2017-01-01 .. Y-01-01.
# A) ideas #2 (4H squeeze release), #3 (1D ATR%<=p10 then 10d Donchian), #18 (1D funding carry + EMA30):
#    plateau grid; walk-forward param pick by train MAR of basket + idea at 0.5% / 1%; all three together;
#    overlap / daily-R corr. KEEP_LIVE: beats baseline in >=5/7 BTC and >=4/7 ETH years and BTC OOS PF 2021-26 > 1.2.
# B) maker entries on C1/C2 only (limit -/+ k*ATR14(1h) from the prior 1h close, next 3 1h bars, 0.02% in,
#    0.12% out; batch16 maker_reprice rule), k = 0.10 / 0.20 / 0.30 and a fold-picked k.
# C) autopsy skip filters, quintile cutoffs picked on 2017..Y-1 trades, applied to Y; placebo = 200 random
#    skips of the same count per year from the same eligible trades. WORTH_LIVE: basket MAR beats baseline
#    >=5/7 BTC and >=4/7 ETH and BTC placebo >= 90. (Skipped trades do not free the engine for a new entry.)
import os, sys, time, itertools, subprocess, traceback
from pathlib import Path

T0 = time.time()
BASE_URL = "https://osom-boba.pages.dev/colab/"
try:
    _HERE = Path(__file__).resolve().parent
except Exception:
    _HERE = Path.cwd()

def _download(name):
    here = Path.cwd() / name
    url = BASE_URL + name + "?nc=" + str(int(time.time()))
    tmp = Path(str(here) + ".tmp")
    try:
        try:
            subprocess.run(["wget", "-q", "-O", str(tmp), url], check=True)
        except Exception:
            from urllib.request import urlopen, Request
            tmp.write_bytes(urlopen(Request(url, headers={"User-Agent": "osom-wfb16/1.0"}), timeout=120).read())
        if tmp.stat().st_size < 1000:
            raise RuntimeError("download too small")
        os.replace(str(tmp), str(here))
    except Exception as ex:
        if not here.exists():
            raise
        print(f"  could not refresh {name} ({type(ex).__name__}); using the local copy", flush=True)

def _need(name, refresh):
    if not refresh:
        for d in (Path.cwd(), _HERE):
            if (d / name).exists():
                if str(d) not in sys.path:
                    sys.path.insert(0, str(d))
                return
        print(f"{name} missing -> downloading " + BASE_URL + name, flush=True)
    _download(name)
    if str(Path.cwd()) not in sys.path:
        sys.path.insert(0, str(Path.cwd()))

_need("oslib.py", False)
import numpy as np
import pandas as pd
import oslib
from oslib import (load, funding, engines, overlay, standardize, expiry_days, atr, ema, bb_width, er, in_colab,
                   LIVE_RISK, COST, RISK, H1, H4, D1)

IN_COLAB = in_colab()
_need("batch16.py", IN_COLAB)
_need("autopsy.py", IN_COLAB)
import batch16 as b16
import autopsy as aut

assert abs(COST - 0.0012) < 1e-12, "Expected COST=0.0012"
print(f"wf_b16 | oslib v{oslib.__version__} | cost {100*COST:.2f}%/side | live risk {LIVE_RISK}", flush=True)

NAN = np.nan
START = "2017-01-01"
WEIGHTS = (0.005, 0.01)
OFFS = (0.10, 0.20, 0.30)
N_PLC = 200
SEED = 20261122
NEED_B, NEED_E = 5, 4
ms = b16.ms

def f1(x, nd=2):
    try:
        x = float(x)
    except Exception:
        return str(x)
    if not np.isfinite(x):
        return "-" if np.isnan(x) else ("inf" if x > 0 else "-inf")
    return f"{x:.{nd}f}"

def pct(w):
    return f"{100*w:.1f}%"

def score(s):
    if s["maxDD"] < 0:
        return s["MAR"]
    return 1e12 + s["ret"] if s["ret"] > 0 else s["ret"]

def beats(a, b):
    sa, sb = score(a), score(b)
    if sa >= 1e12 and sb >= 1e12:
        return a["ret"] > b["ret"]
    return sa > sb

def curve(t, pnl, lo, hi):
    """oslib.overlay math: events summed per exit stamp, compounded, maxDD from a 1.0 start."""
    sel = (t >= lo) & (t < hi)
    if not sel.any():
        return dict(ret=0.0, maxDD=0.0, MAR=NAN, n=0)
    u, inv = np.unique(t[sel], return_inverse=True)
    g = np.bincount(inv, weights=pnl[sel], minlength=len(u))
    eq = np.cumprod(1.0 + g)
    peak = np.maximum.accumulate(np.r_[1.0, eq])[1:]
    mdd = min(0.0, float((eq / peak - 1.0).min()))
    ret = 100.0 * (eq[-1] - 1.0); dd = 100.0 * mdd
    return dict(ret=ret, maxDD=dd, MAR=(ret / abs(dd) if dd < 0 else NAN), n=int(sel.sum()))

def pfR(R):
    R = np.asarray(R, float); R = R[np.isfinite(R)]
    if len(R) == 0:
        return NAN
    g, ls = R[R > 0].sum(), -R[R < 0].sum()
    return g / ls if ls > 0 else (np.inf if g > 0 else NAN)

def ctxt(s):
    return f"{f1(s['ret'],1)}/{f1(s['maxDD'],1)}/{f1(s['MAR'],1)}"

def year_bounds(Y, end_ms):
    return ms(f"{Y}-01-01"), min(ms(f"{Y+1}-01-01"), end_ms)

# ---------------------------------------------------------------------------
# Live trade book (flat arrays, oslib.overlay pnl = R * min(live risk, stop distance))
# ---------------------------------------------------------------------------
class Book:
    def __init__(self, eng):
        std = []
        for nm, trs in eng.items():
            for t in standardize(trs, src=nm):
                t = dict(t); t["nm"] = nm
                std.append(t)
        std.sort(key=lambda d: (d["exit_time"], d["nm"], d["entry_time"]))
        self.trs = std
        self.nm = np.array([d["nm"] for d in std], dtype=object)
        self.t_in = np.array([d["entry_time"] for d in std], dtype=np.int64)
        self.t_out = np.array([d["exit_time"] for d in std], dtype=np.int64)
        self.side = np.array([d["side"] for d in std], dtype=int)
        R = np.array([d["R"] for d in std], dtype=float)
        rk = np.array([d.get("risk", NAN) for d in std], dtype=float)
        self.valid = np.isfinite(R) & np.isfinite(rk) & (rk > 0)
        self.R = np.where(self.valid, R, 0.0)
        self.risk = np.where(self.valid, rk, 0.0)
        self.lr = np.array([LIVE_RISK.get(n, RISK) for n in self.nm], float)
        self.pnl0 = self.R * np.minimum(self.lr, self.risk)
        self.n = len(std)

# ---------------------------------------------------------------------------
# Section A: parametrised copies of batch16 i02 / i03 / i18 (defaults reproduce batch16 exactly)
# ---------------------------------------------------------------------------
def i02p(A, p):
    B = A.h4; c = B["c"]
    e20 = ema(c, p["ln"]); a20 = atr(B["h"], B["l"], c, p["ln"])
    bu, bm, bl, _ = bb_width(c, p["ln"], 2.0)
    inside = (bu < e20 + p["kc"] * a20) & (bl > e20 - p["kc"] * a20)
    sq = b16.sh1(b16.consec(inside)) >= p["sq"]
    e = er(c, 20) >= p["er"]
    sig = np.where(sq & e & (c > bu), 1, np.where(sq & e & (c < bl), -1, 0))
    return dict(B=B, sig=sig, stop_atr=p["stop"], exitL=c < e20, exitS=c > e20)

def i03p(A, p):
    D = A.d; c = D["c"]
    ap = D["atr"] / c
    comp = b16.prank(ap, p["W"]) <= p["pct"]
    armed = b16.rmax(comp.astype(float), p["arm"]) > 0
    hh, ll = b16.sh1(b16.rmax(D["h"], p["N"])), b16.sh1(b16.rmin(D["l"], p["N"]))
    sig = np.where(armed & (c > hh), 1, np.where(armed & (c < ll), -1, 0))
    return dict(B=D, sig=sig, stop_atr=p["stop"], lvlL=b16.rmin(D["l"], p["trail"]), lvlS=b16.rmax(D["h"], p["trail"]))

def i18p(A, p):
    D = A.d; c = D["c"]
    fl = A.f.last(D); e30 = ema(c, p["ema"])
    th = p["fth"]
    st = np.where((c > e30) & (fl <= th), 1, np.where((c < e30) & (fl >= -th), -1, 0))
    return dict(B=D, sig=st, stop_atr=p["stop"], exitL=st != 1, exitS=st != -1, start=b16.FUND_START)

IDEA_DEFS = [
    ("#2", "BB-in-Keltner squeeze release 4H", i02p, b16.i02, None,
     dict(sq=6, ln=20, kc=1.5, er=0.35, stop=2.2), dict(sq=[4, 6, 8], ln=[16, 20, 26], stop=[1.8, 2.2, 2.6])),
    ("#3", "ATR%<=p10 then 10d Donchian 1D", i03p, b16.i03, None,
     dict(W=180, pct=0.10, arm=10, N=10, trail=15, stop=2.5), dict(W=[120, 180, 250], N=[7, 10, 14], stop=[2.0, 2.5, 3.0])),
    ("#18", "Funding carry + EMA30 trend 1D", i18p, b16.i18, b16.FUND_START,
     dict(ema=30, fth=0.0001, stop=2.5), dict(ema=[20, 30, 45], fth=[0.00005, 0.0001, 0.0002], stop=[2.0, 2.5, 3.0])),
]

def combos_of(default, grid):
    keys = list(grid)
    out = []
    for vals in itertools.product(*[grid[k] for k in keys]):
        p = dict(default); p.update(zip(keys, vals))
        out.append(("/".join(f"{v:g}" for v in vals), p))
    dkey = "/".join(f"{default[k]:g}" for k in keys)
    out.sort(key=lambda x: x[0] != dkey)   # default first (wins ties)
    return out, keys

def run_combo(A, fn, p):
    kw = fn(A, p)
    B = kw.pop("B"); st = kw.pop("start", None)
    r = b16.sim(B, maker=False, start=st, **kw)
    trs = r["trades"]
    for tr in trs:
        tr["asset"] = A.name
    trs.sort(key=lambda d: (d["exit_time"], d["entry_time"]))
    return trs

def tarr(trs):
    t_out = np.array([d["exit_time"] for d in trs], dtype=np.int64)
    t_in = np.array([d["entry_time"] for d in trs], dtype=np.int64)
    R = np.array([d["R"] for d in trs], dtype=float)
    rk = np.array([d["risk"] for d in trs], dtype=float)
    ok = np.isfinite(R) & np.isfinite(rk) & (rk > 0)
    return dict(t_in=t_in, t_out=t_out, R=np.where(ok, R, 0.0), risk=np.where(ok, rk, 0.0), ok=ok)

def ipnl(I, w):
    return I["R"] * np.minimum(w, I["risk"])

def wf_pick(book, per, w, years, end_ms):
    s0 = ms(START); chosen = {}
    for Y in years:
        lo, hi = year_bounds(Y, end_ms)
        if lo >= end_ms:
            continue
        best, bs = 0, None
        for k, c in enumerate(per):
            I = c["I"]
            s = curve(np.r_[book.t_out, I["t_out"]], np.r_[book.pnl0, ipnl(I, w)], s0, lo)
            if bs is None or beats(s, bs):
                best, bs = k, s
        chosen[Y] = best
    return chosen

def eval_add(book, adds, years, end_ms):
    """adds = list of (per, chosen, w). Idea trades of test year Y come from that fold's chosen combo."""
    et, ep, eR, eY = [], [], [], []
    for per, chosen, w in adds:
        for Y, k in chosen.items():
            lo, hi = year_bounds(Y, end_ms)
            I = per[k]["I"]
            m = (I["t_out"] >= lo) & (I["t_out"] < hi)
            et.append(I["t_out"][m]); ep.append(ipnl(I, w)[m])
            eR.append(np.where(I["ok"][m], I["R"][m], NAN)); eY.append(np.full(int(m.sum()), Y))
    et = np.concatenate(et) if et else np.zeros(0, np.int64)
    ep = np.concatenate(ep) if ep else np.zeros(0)
    eR = np.concatenate(eR) if eR else np.zeros(0)
    eY = np.concatenate(eY) if eY else np.zeros(0, int)
    T = np.r_[book.t_out, et]; P = np.r_[book.pnl0, ep]
    wins, ny, yl = 0, 0, []
    for Y in years:
        lo, hi = year_bounds(Y, end_ms)
        if lo >= end_ms:
            continue
        ny += 1
        sb = curve(book.t_out, book.pnl0, lo, hi); sw = curve(T, P, lo, hi)
        bt = beats(sw, sb); wins += int(bt)
        yl.append((Y, sb, sw, bt))
    lo0 = ms(f"{years[0]}-01-01")
    sb = curve(book.t_out, book.pnl0, lo0, end_ms); sw = curve(T, P, lo0, end_ms)
    m21 = eY >= 2021
    return dict(base=sb, st=sw, wins=wins, ny=ny, years=yl, n=len(eR), pf=pfR(eR), n21=int(m21.sum()),
                pf21=pfR(eR[m21]), totR=float(np.nansum(eR)))

def overlap_pct(a_in, a_out, b_in, b_out):
    if len(a_in) == 0 or len(b_in) == 0:
        return NAN
    hit = np.zeros(len(a_in), bool)
    for s in range(0, len(a_in), 500):
        qi, qo = a_in[s:s + 500], a_out[s:s + 500]
        hit[s:s + 500] = ((b_in[None, :] < qo[:, None]) & (b_out[None, :] > qi[:, None])).any(axis=1)
    return 100.0 * float(hit.mean())

def dayR(t_out, R):
    if len(t_out) == 0:
        return pd.Series(dtype=float)
    return pd.DataFrame({"d": t_out // D1, "R": R}).groupby("d")["R"].sum()

def section_A(ctx, books, ends, years, rows):
    print("\n=== A) NEW ENGINES #2 / #3 / #18: plateau grid, walk-forward, all three, overlap ===", flush=True)
    S = {}
    s0 = ms(START)
    for key, name, fn, ref_fn, ref_start, default, grid in IDEA_DEFS:
        S[key] = {}
        combos, gkeys = combos_of(default, grid)
        for a in ("btc", "eth"):
            try:
                A = ctx[a]; O = ctx["eth" if a == "btc" else "btc"]
                per = []
                for lab, p in combos:
                    trs = run_combo(A, fn, p)
                    m = b16.metrics(trs)
                    per.append(dict(lab=lab, p=p, I=tarr(b16.win(trs, START)), trs=b16.win(trs, START),
                                    n=m["n"], pf=m["pf"], pf2=m["pf_h2"], ret=m["ret"]))
                    rows.append(dict(section="A_grid", asset=a, item=key, variant=lab, n=m["n"], PF=m["pf"],
                                     PF_21_26=m["pf_h2"], ret=m["ret"]))
                ref = b16.run_idea(ref_fn, A, O, False, ref_start)["trades"]
                sig = lambda L: [(d["entry_time"], d["exit_time"], d["side"], round(d["R"], 9)) for d in L]
                repro = "repro OK" if sig(ref) == sig(run_combo(A, fn, combos[0][1])) else "REPRO MISMATCH"
                d0 = per[0]
                pfs = np.array([c["pf"] for c in per], float); p2s = np.array([c["pf2"] for c in per], float)
                share = 100.0 * float(np.mean(np.where(np.isfinite(p2s), p2s, 0.0) > 1.2))
                print(f"  {key:3s} {a.upper()} grid {len(per)} [{'/'.join(gkeys)}]: default {d0['lab']} n {d0['n']} PF {f1(d0['pf'])} "
                      f"PF21-26 {f1(d0['pf2'])} | grid PF med {f1(np.nanmedian(pfs))} ({f1(np.nanmin(pfs))}..{f1(np.nanmax(pfs))}) "
                      f"PF21-26 med {f1(np.nanmedian(p2s))} | PF21-26>1.2 in {share:.0f}% | {repro}", flush=True)
                marg = []
                for k in gkeys:
                    parts = []
                    for v in grid[k]:
                        sel = np.array([c["p"][k] == v for c in per])
                        parts.append(f"{v:g}:{f1(np.nanmedian(p2s[sel]))}")
                    marg.append(f"{k} " + " ".join(parts))
                print("        PF21-26 median by value: " + " | ".join(marg), flush=True)
                rows.append(dict(section="A_plateau", asset=a, item=key, variant="grid", n=d0["n"], PF=d0["pf"],
                                 PF_21_26=d0["pf2"], share_pf2126_gt_1_2=share, repro=repro))
                S[key][a] = per
            except Exception as ex:
                print(f"  {key} {a} grid ERROR {type(ex).__name__}: {ex}", flush=True)
                traceback.print_exc(limit=2)

    print(f"\n  walk-forward: params picked on 2017..Y-1 by MAR of basket + idea, applied to Y ({years[0]}..{years[-1]}); "
          f"stitched OOS basket ret/maxDD/MAR", flush=True)
    WF = {}
    for key, name, fn, ref_fn, ref_start, default, grid in IDEA_DEFS:
        for w in WEIGHTS:
            for a in ("btc", "eth"):
                try:
                    per = S[key][a]
                    ch = wf_pick(books[a], per, w, years, ends[a])
                    r = eval_add(books[a], [(per, ch, w)], years, ends[a])
                    WF[(key, a, w)] = dict(r=r, ch=ch)
                    picks = " ".join(f"{str(Y)[2:]}:{per[k]['lab']}" for Y, k in ch.items())
                    print(f"  {key:3s} {a.upper()} @{pct(w)}: base {ctxt(r['base'])} | +idea {ctxt(r['st'])} | beat {r['wins']}/{r['ny']} "
                          f"| OOS n {r['n']} PF {f1(r['pf'])} PF21-26 {f1(r['pf21'])} | picks {picks}", flush=True)
                    for Y, sb, sw, bt in r["years"]:
                        rows.append(dict(section="A_wf_year", asset=a, item=key, w=w, year=Y, variant=per[ch[Y]]["lab"],
                                         ret=sw["ret"], maxDD=sw["maxDD"], MAR=sw["MAR"], base_ret=sb["ret"],
                                         base_maxDD=sb["maxDD"], base_MAR=sb["MAR"], beat=bt))
                    rows.append(dict(section="A_wf_stitched", asset=a, item=key, w=w, ret=r["st"]["ret"], maxDD=r["st"]["maxDD"],
                                     MAR=r["st"]["MAR"], base_ret=r["base"]["ret"], base_maxDD=r["base"]["maxDD"],
                                     base_MAR=r["base"]["MAR"], years_beat=r["wins"], n_years=r["ny"], n=r["n"],
                                     PF=r["pf"], PF_21_26=r["pf21"]))
                except Exception as ex:
                    print(f"  {key} {a} @{pct(w)} WF ERROR {type(ex).__name__}: {ex}", flush=True)
                    traceback.print_exc(limit=2)

    print("\n  all three added together (each idea with its own fold-picked params):", flush=True)
    for w in WEIGHTS:
        for a in ("btc", "eth"):
            try:
                adds = [(S[k][a], WF[(k, a, w)]["ch"], w) for k, *_ in IDEA_DEFS if (k, a, w) in WF]
                r = eval_add(books[a], adds, years, ends[a])
                WF[("ALL3", a, w)] = dict(r=r, ch=None)
                print(f"  ALL3 {a.upper()} @{pct(w)} each: base {ctxt(r['base'])} | +all {ctxt(r['st'])} | beat {r['wins']}/{r['ny']} "
                      f"| OOS n {r['n']} PF {f1(r['pf'])} PF21-26 {f1(r['pf21'])}", flush=True)
                rows.append(dict(section="A_all3", asset=a, item="ALL3", w=w, ret=r["st"]["ret"], maxDD=r["st"]["maxDD"],
                                 MAR=r["st"]["MAR"], base_ret=r["base"]["ret"], base_MAR=r["base"]["MAR"],
                                 years_beat=r["wins"], n_years=r["ny"], PF=r["pf"], PF_21_26=r["pf21"]))
            except Exception as ex:
                print(f"  ALL3 {a} @{pct(w)} ERROR {type(ex).__name__}: {ex}", flush=True)

    print("\n  overlap % (row trades overlapping any column trade) and daily-R corr, default params, 2017+:", flush=True)
    for a in ("btc", "eth"):
        try:
            bk = books[a]
            cols = []
            for key, *_ in IDEA_DEFS:
                d0 = S[key][a][0]["I"]
                cols.append((key, d0["t_in"], d0["t_out"], np.where(d0["ok"], d0["R"], 0.0)))
            for nm in oslib.LIVE_ENGINES:
                m = (bk.nm == nm) & (bk.t_out >= s0)
                cols.append((nm, bk.t_in[m], bk.t_out[m], bk.R[m]))
            dr = {c[0]: dayR(c[2], c[3]) for c in cols}
            hdr = "".join(f"{c[0]:>6s}" for c in cols)
            for what in ("ovl%", "corr"):
                print(f"  {a.upper()} {what:4s} {hdr}", flush=True)
                for key, ti, to, _ in cols[:3]:
                    vals = []
                    for c in cols:
                        if c[0] == key:
                            vals.append("     -"); continue
                        v = overlap_pct(ti, to, c[1], c[2]) if what == "ovl%" else b16.dcorr(dr[key], dr[c[0]])
                        vals.append(f"{f1(v, 0 if what == 'ovl%' else 2):>6s}")
                        rows.append(dict(section="A_overlap" if what == "ovl%" else "A_corr", asset=a, item=key,
                                         variant=c[0], value=v))
                    print(f"  {'':3s} {key:4s} " + "".join(vals), flush=True)
        except Exception as ex:
            print(f"  overlap {a} ERROR {type(ex).__name__}: {ex}", flush=True)

    V = {}
    print(f"\n  A verdicts (KEEP_LIVE: beat >= {NEED_B}/{len(years)} BTC and >= {NEED_E}/{len(years)} ETH years and BTC OOS PF 2021-26 > 1.2):", flush=True)
    for key in [k for k, *_ in IDEA_DEFS] + ["ALL3"]:
        ok_w, paper = [], False
        for w in WEIGHTS:
            rb, re_ = WF.get((key, "btc", w)), WF.get((key, "eth", w))
            if rb is None or re_ is None:
                continue
            rb, re_ = rb["r"], re_["r"]
            pf21 = rb["pf21"]
            if rb["wins"] >= NEED_B and re_["wins"] >= NEED_E and np.isfinite(pf21) and pf21 > 1.2:
                ok_w.append((score(rb["st"]), w))
            if rb["wins"] >= NEED_B - 1 and np.isfinite(pf21) and pf21 > 1.0:
                paper = True
        if ok_w:
            w = max(ok_w)[1]; vd = "KEEP_LIVE"; rec = f"{pct(w)} each" if key == "ALL3" else pct(w)
        else:
            vd = "PAPER" if paper else "DROP"; rec = "paper only" if paper else "-"
        V[key] = (vd, rec)
        parts = []
        for w in WEIGHTS:
            rb, re_ = WF.get((key, "btc", w)), WF.get((key, "eth", w))
            if rb and re_:
                parts.append(f"@{pct(w)} BTC {rb['r']['wins']}/{rb['r']['ny']} ETH {re_['r']['wins']}/{re_['r']['ny']} "
                             f"PF21-26 {f1(rb['r']['pf21'])} MAR {f1(rb['r']['st']['MAR'],1)} vs {f1(rb['r']['base']['MAR'],1)}")
        print(f"  {vd:9s} {key:4s} risk {rec:10s} | " + " | ".join(parts), flush=True)
        rows.append(dict(section="A_verdict", item=key, verdict=vd, rec_risk=rec))
    return V

# ---------------------------------------------------------------------------
# Section B: maker entries for C1 / C2 (batch16 maker_reprice rule, offset as a parameter)
# ---------------------------------------------------------------------------
MK_ENG = ("C1", "C2")

def maker_pnl(book, h1df, off):
    t = h1df["time"].to_numpy(dtype="int64")
    o, h, l, c = (h1df[k].to_numpy(dtype=float) for k in ("open", "high", "low", "close"))
    a1 = atr(h, l, c, 14)
    n = len(t)
    pnl = book.pnl0.copy()
    elig = np.zeros(book.n, bool); miss = np.zeros(book.n, bool)
    s0 = ms(START)
    for i in np.flatnonzero(np.isin(book.nm, MK_ENG) & book.valid & (book.t_out >= s0)):
        tt = book.trs[i]
        elig[i] = True
        R, rk, lr = book.R[i], book.risk[i], book.lr[i]
        s = int(tt["side"]); ent = tt["entry"]; stp = tt["stop"]
        if not (np.isfinite(ent) and ent > 0 and s != 0):
            continue
        if not np.isfinite(stp):
            stp = ent - s * rk * ent
        gross = R * rk + 2 * COST
        xeff = ent * (1.0 + s * gross)
        ei = int(np.searchsorted(t, tt["entry_time"]))
        if ei <= 0 or ei >= n:
            continue
        lim = c[ei - 1] - s * off * a1[ei - 1]
        fill = None
        for k in range(ei, min(n, ei + b16.MK_BARS)):
            if t[k] > tt["exit_time"]:
                break
            if (s > 0 and l[k] <= lim) or (s < 0 and h[k] >= lim):
                fill = min(o[k], lim) if s > 0 else max(o[k], lim); break
        if fill is None or not (s * (fill - stp) > 0):
            miss[i] = True; pnl[i] = 0.0; continue
        rk2 = abs(fill - stp) / fill
        ret2 = s * (xeff / fill - 1.0) - b16.MAKER_IN - COST
        pnl[i] = (ret2 / rk2) * min(lr, rk2)
    return pnl, elig, miss

def section_B(data, books, ends, years, rows):
    print("\n=== B) MAKER ENTRIES ON C1/C2 ONLY (limit -/+k*ATR14 1h from prior 1h close, 3 bars, 0.02% in / 0.12% out) ===", flush=True)
    out = {}
    s0 = ms(START)
    for a in ("btc", "eth"):
        try:
            bk = books[a]; end = ends[a]
            P = {k: maker_pnl(bk, data[a][0], k) for k in OFFS}
            msk = {e: bk.nm == e for e in MK_ENG}
            msk["BASKET"] = np.ones(bk.n, bool)
            c0 = P[0.20][0]
            chk = " ".join(f"{e} MAR tkr {f1(curve(bk.t_out[msk[e]], bk.pnl0[msk[e]], s0, end)['MAR'])} "
                           f"mkr {f1(curve(bk.t_out[msk[e]], c0[msk[e]], s0, end)['MAR'])}" for e in MK_ENG)
            print(f"  {a.upper()} check 2017+ @0.20 (batch16 maker rule): {chk}", flush=True)
            pick = {}
            for Y in years:
                lo, hi = year_bounds(Y, end)
                if lo >= end:
                    continue
                pick[Y] = max(OFFS, key=lambda k: score(curve(bk.t_out, P[k][0], s0, lo)))
            wfp = bk.pnl0.copy(); wfm = np.zeros(bk.n, bool); wfe = np.zeros(bk.n, bool)
            for Y, k in pick.items():
                lo, hi = year_bounds(Y, end)
                ym = (bk.t_out >= lo) & (bk.t_out < hi)
                wfp[ym] = P[k][0][ym]; wfm[ym] = P[k][2][ym]; wfe[ym] = P[k][1][ym]
            variants = [(f"k{k:.2f}", P[k][0], P[k][1], P[k][2]) for k in OFFS] + [("kWF", wfp, wfe, wfm)]
            lo0 = ms(f"{years[0]}-01-01")
            inwf = bk.t_out >= lo0
            print(f"  {a.upper()} {'var':5s} {'target':6s} {'miss%':>6s}  {'taker ret/DD/MAR':>22s}  {'maker ret/DD/MAR':>22s}  beat", flush=True)
            for vn, pnl, el, mi in variants:
                for tg in ("C1", "C2", "BASKET"):
                    m = msk[tg]
                    e_ = el & m & inwf
                    mp = 100.0 * float(mi[e_].sum()) / max(1, int(e_.sum()))
                    st_t = curve(bk.t_out[m], bk.pnl0[m], lo0, end); st_m = curve(bk.t_out[m], pnl[m], lo0, end)
                    wins = 0; ny = 0
                    for Y in years:
                        lo, hi = year_bounds(Y, end)
                        if lo >= end:
                            continue
                        ny += 1
                        wins += int(beats(curve(bk.t_out[m], pnl[m], lo, hi), curve(bk.t_out[m], bk.pnl0[m], lo, hi)))
                    print(f"  {'':3s} {vn:5s} {tg:6s} {f1(mp,1):>6s}  {ctxt(st_t):>22s}  {ctxt(st_m):>22s}  {wins}/{ny}", flush=True)
                    out[(a, vn, tg)] = dict(wins=wins, ny=ny, st_t=st_t, st_m=st_m, miss=mp)
                    rows.append(dict(section="B_maker", asset=a, item=tg, variant=vn, missed_pct=mp, base_ret=st_t["ret"],
                                     base_maxDD=st_t["maxDD"], base_MAR=st_t["MAR"], ret=st_m["ret"], maxDD=st_m["maxDD"],
                                     MAR=st_m["MAR"], years_beat=wins, n_years=ny))
            print(f"  {a.upper()} kWF picks: " + " ".join(f"{Y}:{k:.2f}" for Y, k in pick.items()), flush=True)
        except Exception as ex:
            print(f"  {a} maker ERROR {type(ex).__name__}: {ex}", flush=True)
            traceback.print_exc(limit=2)
    return out

# ---------------------------------------------------------------------------
# Section C: autopsy skip filters, walk-forward quintile cutoffs
# ---------------------------------------------------------------------------
FEATS = ("r3d", "r7d", "bbw_pct", "adx_d", "atrp_pct", "d_hi20", "z20")
FILTERS = [
    ("a1", "SHORT skip r7d top Q", "short", "short", [("r7d", "hi")]),
    ("a2", "SHORT skip bbw_pct top Q", "short", "short", [("bbw_pct", "hi")]),
    ("a3", "SHORT skip adx_d top Q", "short", "short", [("adx_d", "hi")]),
    ("a4", "SHORT skip any of a1-a3", "short", "short", [("r7d", "hi"), ("bbw_pct", "hi"), ("adx_d", "hi")]),
    ("b1", "C2 skip atrp_pct top Q", "C2", "C2", [("atrp_pct", "hi")]),
    ("b2", "C2 skip adx_d top Q", "C2", "C2", [("adx_d", "hi")]),
    ("b3", "C2 skip either", "C2", "C2", [("atrp_pct", "hi"), ("adx_d", "hi")]),
    ("c1", "V7 long skip r3d top Q", "V7", "V7L", [("r3d", "hi")]),
    ("c2", "V7 long skip r7d top Q", "V7", "V7L", [("r7d", "hi")]),
    ("c3", "V7 long skip near 20d high", "V7", "V7L", [("d_hi20", "lo")]),
    ("c4", "V7 long skip any of c1-c3", "V7", "V7L", [("r3d", "hi"), ("r7d", "hi"), ("d_hi20", "lo")]),
    ("d1", "K8 skip z20 bottom Q", "K8", "K8", [("z20", "lo")]),
]

def gmask(bk, g):
    if g == "short":
        return bk.side == -1
    if g == "V7L":
        return (bk.nm == "V7") & (bk.side == 1)
    return bk.nm == g

def book_features(bk, df, fund, exps):
    D, Q, Hh, F = aut.market_frames(df, fund)
    X = {k: np.full(bk.n, NAN) for k in FEATS}
    s0 = ms(START)
    for i in range(bk.n):
        if bk.t_out[i] < s0:
            continue
        fe = aut.entry_features(int(bk.t_in[i]), int(bk.side[i]), D, Q, Hh, F, exps)
        for k in FEATS:
            X[k][i] = fe.get(k, NAN)
    return X

def section_C(data, books, ends, years, rows, n_plc):
    print(f"\n=== C) AUTOPSY SKIP FILTERS (quintile cutoff on 2017..Y-1 trades, applied to Y; placebo {n_plc} random skips) ===", flush=True)
    exps = np.array([int(e.value // 1_000_000) for e in expiry_days("2012-01-01", "2027-12-31")], dtype="int64")
    s0 = ms(START)
    X = {}
    for a in ("btc", "eth"):
        try:
            X[a] = book_features(books[a], data[a][0], data[a][1], exps)
        except Exception as ex:
            print(f"  {a} features ERROR {type(ex).__name__}: {ex}", flush=True)
            traceback.print_exc(limit=2)
    res = {}
    rng = np.random.default_rng(SEED)
    for code, name, edge_g, app_g, conds in FILTERS:
        for a in ("btc", "eth"):
            try:
                bk = books[a]; end = ends[a]; F = X[a]
                em = gmask(bk, edge_g) & bk.valid; am = gmask(bk, app_g) & bk.valid
                skip = np.zeros(bk.n, bool); cuts = {}; ylist = []
                for Y in years:
                    lo, hi = year_bounds(Y, end)
                    if lo >= end:
                        continue
                    ym = (bk.t_out >= lo) & (bk.t_out < hi)
                    trn = em & (bk.t_out >= s0) & (bk.t_out < lo)
                    sk = np.zeros(bk.n, bool); cy = []
                    for feat, tail in conds:
                        x = F[feat][trn]; x = x[np.isfinite(x)]
                        if len(x) < 10:
                            cy.append(NAN); continue
                        q = float(np.quantile(x, 0.8 if tail == "hi" else 0.2))
                        cy.append(q)
                        v = F[feat]
                        with np.errstate(invalid="ignore"):
                            sk |= np.isfinite(v) & ((v >= q) if tail == "hi" else (v < q))
                    cuts[Y] = cy
                    skip |= sk & am & ym
                    ylist.append((Y, lo, hi, ym))
                lo0 = ms(f"{years[0]}-01-01")
                pnlF = np.where(skip, 0.0, bk.pnl0)
                sb = curve(bk.t_out, bk.pnl0, lo0, end); sf = curve(bk.t_out, pnlF, lo0, end)
                wins = sum(int(beats(curve(bk.t_out, pnlF, lo, hi), curve(bk.t_out, bk.pnl0, lo, hi))) for Y, lo, hi, ym in ylist)
                oos = am & (bk.t_out >= lo0) & (bk.t_out < end)
                pf_b, pf_f = pfR(bk.R[oos]), pfR(bk.R[oos & ~skip])
                tr_b, tr_f = float(bk.R[oos].sum()), float(bk.R[oos & ~skip].sum())
                pools = [(np.flatnonzero(am & ym), int((skip & ym).sum())) for Y, lo, hi, ym in ylist]
                sc_real = score(sf); better = 0
                for _ in range(n_plc):
                    pp = bk.pnl0.copy()
                    for pool, cnt in pools:
                        if cnt > 0 and len(pool) >= cnt:
                            pp[rng.choice(pool, size=cnt, replace=False)] = 0.0
                    better += int(sc_real > score(curve(bk.t_out, pp, lo0, end)))
                plc = 100.0 * better / max(1, n_plc)
                res[(code, a)] = dict(wins=wins, ny=len(ylist), plc=plc, sb=sb, sf=sf)
                print(f"  {code} {name:27s} {a.upper()} skip {int(skip.sum()):3d}/{int(oos.sum()):4d} | grp PF {f1(pf_b)}->{f1(pf_f)} "
                      f"totR {f1(tr_b,1)}->{f1(tr_f,1)} | basket {ctxt(sb)} -> {ctxt(sf)} | beat {wins}/{len(ylist)} | plc {plc:.0f} | last cut "
                      + ",".join(f1(q, 2) for q in (cuts[max(cuts)] if cuts else [])), flush=True)
                rows.append(dict(section="C_filter", asset=a, item=code, variant=name, n=int(oos.sum()), n_skip=int(skip.sum()),
                                 base_PF=pf_b, PF=pf_f, base_totR=tr_b, totR=tr_f, base_ret=sb["ret"], base_maxDD=sb["maxDD"],
                                 base_MAR=sb["MAR"], ret=sf["ret"], maxDD=sf["maxDD"], MAR=sf["MAR"], years_beat=wins,
                                 n_years=len(ylist), placebo=plc,
                                 cuts="; ".join(f"{Y}:" + ",".join(f1(q, 3) for q in cy) for Y, cy in cuts.items())))
            except Exception as ex:
                print(f"  {code} {a} ERROR {type(ex).__name__}: {ex}", flush=True)
                traceback.print_exc(limit=2)
    V = {}
    print(f"\n  C verdicts (WORTH_LIVE: beat >= {NEED_B}/{len(years)} BTC, >= {NEED_E}/{len(years)} ETH, BTC placebo >= 90):", flush=True)
    for code, name, *_ in FILTERS:
        b, e = res.get((code, "btc")), res.get((code, "eth"))
        if not b or not e:
            V[code] = ("ERROR", name); continue
        ok = b["wins"] >= NEED_B and e["wins"] >= NEED_E and b["plc"] >= 90
        vd = "WORTH_LIVE" if ok else "NO"
        V[code] = (vd, name)
        print(f"  {vd:10s} {code} {name:27s} BTC {b['wins']}/{b['ny']} plc {b['plc']:.0f} MAR {f1(b['sf']['MAR'],1)} vs {f1(b['sb']['MAR'],1)} | "
              f"ETH {e['wins']}/{e['ny']} plc {e['plc']:.0f} MAR {f1(e['sf']['MAR'],1)} vs {f1(e['sb']['MAR'],1)}", flush=True)
        rows.append(dict(section="C_verdict", item=code, variant=name, verdict=vd))
    return V

# ---------------------------------------------------------------------------
def main(smoke=False):
    global NEED_B, NEED_E
    n_plc = N_PLC
    if smoke:
        print("SMOKE MODE: synthetic data only (no real backtest).", flush=True)
        nb = int(os.environ.get("WFB16_SMOKE_N", "46000"))
        b1, zb = b16.synth(1, start="2017-01-02", n=nb)
        e1, _ = b16.synth(2, start="2017-01-02", n=nb, base=zb, px0=500.0)
        bf, ef = b16.synth_fund(b1, 3), b16.synth_fund(e1, 4)
        years = [2019, 2020, 2021, 2022]
        NEED_B, NEED_E = 2, 2
        n_plc = 20
    else:
        b1, e1 = load("btc", "1h"), load("eth", "1h")
        bf, ef = funding("btc", "binance"), funding("eth", "binance")
        years = list(range(2020, 2027))
    data = {"btc": (b1, bf), "eth": (e1, ef)}
    ctx = {"btc": b16.Ctx("btc", b1, bf), "eth": b16.Ctx("eth", e1, ef)}
    books, ends = {}, {}
    for a, (df, fd) in data.items():
        t_a = time.time()
        eng = engines(df, fund=fd)
        books[a] = Book(eng)
        ends[a] = int(df["time"].iloc[-1]) + D1
        ov = overlay(eng, lambda nm, t: 1.0, start=START)["baseline"]
        fb = curve(books[a].t_out, books[a].pnl0, ms(START), ends[a])
        print(f"  {a.upper()} engines: " + " ".join(f"{k} {len(v)}" for k, v in eng.items()) +
              f" | basket 2017+ ret {f1(fb['ret'],1)}% maxDD {f1(fb['maxDD'],2)}% MAR {f1(fb['MAR'])} "
              f"(oslib.overlay {f1(ov['ret'],1)}% / {f1(ov['MAR'])})  ({time.time()-t_a:.0f}s)", flush=True)
    rows = []
    VA, VB, VC = {}, {}, {}
    try:
        VA = section_A(ctx, books, ends, years, rows)
    except Exception as ex:
        print(f"SECTION A ERROR {type(ex).__name__}: {ex}", flush=True); traceback.print_exc(limit=3)
    print(f"  ({time.time()-T0:.0f}s)", flush=True)
    try:
        VB = section_B(data, books, ends, years, rows)
    except Exception as ex:
        print(f"SECTION B ERROR {type(ex).__name__}: {ex}", flush=True); traceback.print_exc(limit=3)
    print(f"  ({time.time()-T0:.0f}s)", flush=True)
    try:
        VC = section_C(data, books, ends, years, rows, n_plc)
    except Exception as ex:
        print(f"SECTION C ERROR {type(ex).__name__}: {ex}", flush=True); traceback.print_exc(limit=3)

    print("\n=== RECOMMENDATIONS ===", flush=True)
    try:
        keep = [f"{k} at {v[1]}" for k, v in VA.items() if v[0] == "KEEP_LIVE" and k != "ALL3"]
        paper = [k for k, v in VA.items() if v[0] == "PAPER" and k != "ALL3"]
        drop = [k for k, v in VA.items() if v[0] == "DROP" and k != "ALL3"]
        print(f"  New engines: add live {', '.join(keep) or 'none'}; paper {', '.join(paper) or 'none'}; drop {', '.join(drop) or 'none'}.", flush=True)
        if "ALL3" in VA:
            print(f"  All three together: {VA['ALL3'][0]} ({VA['ALL3'][1]}).", flush=True)
        if VB:
            good = []
            for vn in [f"k{k:.2f}" for k in OFFS] + ["kWF"]:
                b, e = VB.get(("btc", vn, "BASKET")), VB.get(("eth", vn, "BASKET"))
                if b and e and b["wins"] >= NEED_B and e["wins"] >= NEED_E and beats(b["st_m"], b["st_t"]):
                    good.append(vn)
            eng_ok = []
            for eg in MK_ENG:
                b, e = VB.get(("btc", "k0.20", eg)), VB.get(("eth", "k0.20", eg))
                if b and e and b["wins"] >= NEED_B and e["wins"] >= NEED_E:
                    eng_ok.append(eg)
            print(f"  Maker C1/C2: basket passes (>= {NEED_B}/{len(years)} BTC, >= {NEED_E}/{len(years)} ETH, stitched MAR up) for {', '.join(good) or 'no variant'}; "
                  f"engine-level pass @0.20: {', '.join(eng_ok) or 'none'}.", flush=True)
        if VC:
            wl = [f"{k} ({v[1]})" for k, v in VC.items() if v[0] == "WORTH_LIVE"]
            print(f"  Skip filters worth live: {', '.join(wl) or 'none'}.", flush=True)
        print("  Anything not listed as live stays off; run a paper month before raising risk on any new KEEP_LIVE item.", flush=True)
    except Exception as ex:
        print(f"  RECOMMENDATIONS ERROR {type(ex).__name__}: {ex}", flush=True)

    out_dir = Path("/content") if Path("/content").exists() else Path(".")
    out = out_dir / ("wf_b16_smoke.csv" if smoke else "wf_b16.csv")
    pd.DataFrame(rows).to_csv(out, index=False)
    print(f"\nSaved {out} ({len(rows)} rows). Total {time.time()-T0:.0f}s", flush=True)

if __name__ == "__main__":
    _smoke = ("--smoke" in sys.argv) or (not in_colab() and os.environ.get("OSLIB_ALLOW_REAL") != "1")
    main(smoke=_smoke)
