# ===== autopsy.py - failure-pattern autopsy of the live basket's losing trades =====
# Colab:  !wget -q -O autopsy.py https://osom-boba.pages.dev/colab/autopsy.py
#         %run autopsy.py
# Box (synthetic smoke only):  python3 autopsy.py --smoke
#
# Trades: oslib.engines(df, fund=funding(asset,'binance')) for BTC and ETH (X7 on), 2017+ by
# exit time, 0.12%/side (oslib.COST). R = net R per trade (weight x R).
# Entry-time features use only data closed before the entry bar opens (no lookahead):
#   daily bars count only if day_open + 1d <= entry_time; 4h and 1h likewise.
# Path labels (from 1h bars entry..exit): MFE/MAE in R, bars to exit.
#   QUICK_STOP = loser, MFE<0.3R, held <= 3 engine bars (C1/C2/MOM30 4h, R0 1h, others 1d)
#   GAVE_BACK  = loser after MFE>=1R;  SLOW_BLEED = other losers;  WIN = R>0
# Pocket = bucket with BTC PF<0.8 & n>=20, PF<1 in BTC 2017-20 and 2021-26, PF<1 on ETH (n>=10),
#   and skip-it PF above the 90th pct of 200 random skips of the same count. WORTH_WF or NOISE.
# Many buckets are tested, so expect some chance pockets; walk-forward is the real test.
import os, sys, time, subprocess
from pathlib import Path

T0 = time.time()
OSLIB_URL = "https://osom-boba.pages.dev/colab/oslib.py"

def _ensure_oslib():
    cands = [Path.cwd() / "oslib.py"]
    if "__file__" in globals():
        cands.append(Path(__file__).resolve().parent / "oslib.py")
    found = next((p for p in cands if p.exists()), None)
    if found is None:
        found = Path.cwd() / "oslib.py"
        print("oslib.py missing -> downloading " + OSLIB_URL, flush=True)
        try:
            subprocess.run(["wget", "-q", "-O", str(found), OSLIB_URL], check=True)
        except Exception:
            from urllib.request import urlopen, Request
            raw = urlopen(Request(OSLIB_URL, headers={"User-Agent": "osom-autopsy/1.0"}), timeout=120).read()
            found.write_bytes(raw)
    parent = str(found.parent)
    if parent not in sys.path:
        sys.path.insert(0, parent)

_ensure_oslib()
import numpy as np
import pandas as pd
import oslib
from oslib import (load, funding, engines, synthetic_1h, in_colab, resample_ohlcv, expiry_days,
                   adx, atr, sma, chop, bb_width, LIVE_RISK, H1, H4, D1, HEADLINE_START, COST)

print(f"oslib v{oslib.__version__} | cost {100*COST:.2f}%/side | live risk {LIVE_RISK}", flush=True)

START = HEADLINE_START
SPLIT = "2021-01-01"
TREE_SPLIT = "2022-01-01"
PLACEBO_N = 200
SEED = 20261122
TF_H = {"C1": 4, "C2": 4, "MOM30": 4, "R0": 1}
NUM_FEATS = ["adx_d", "adx_4h", "atrp_pct", "z20", "z50", "z200", "slope50", "wk_pos",
             "d_hi20", "d_lo20", "r1d", "r3d", "r7d", "chop_d", "bbw_pct", "fund3_pct", "last5_R"]
CAT_FEATS = ["side", "dow", "hour_blk", "dte_blk", "streak_b", "last5_w", "others_b", "trend_agree"]
TREE_FEATS = NUM_FEATS + ["side", "dow", "hour", "dte", "streak", "last5_wins", "others_open", "trend_agree"]
OUT_DIR = Path("/content") if Path("/content").exists() else Path(".")
FULL = os.environ.get("AUTOPSY_FULL") == "1"   # 1 = print every bucket; default prints worst 10 per group

def ms(s):
    return int(pd.Timestamp(s, tz="UTC").value // 1_000_000)

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

def rstats(r):
    r = np.asarray(r, dtype=float)
    r = r[np.isfinite(r)]
    n = len(r)
    if n == 0:
        return dict(n=0, win=np.nan, pf=np.nan, avgR=np.nan, totR=0.0)
    g = r[r > 0].sum(); ls = -r[r < 0].sum()
    pf = g / ls if ls > 0 else (np.inf if g > 0 else np.nan)
    return dict(n=n, win=100.0 * float((r > 0).mean()), pf=float(pf), avgR=float(r.mean()), totR=float(r.sum()))

def roll_pct(x, w):
    s = pd.Series(np.asarray(x, dtype=float))
    mp = max(10, w // 2)
    try:
        return s.rolling(w, min_periods=mp).rank(pct=True).to_numpy() * 100.0
    except Exception:
        return s.rolling(w, min_periods=mp).apply(lambda a: 100.0 * (a <= a[-1]).mean(), raw=True).to_numpy()

def last_closed(bar_t, bar_ms, T):
    # index of the last bar whose close (open + bar_ms) is <= T; -1 if none
    return np.searchsorted(bar_t + bar_ms, T, side="right") - 1

# ---------------------------------------------------------------- market features
def market_frames(df, fund):
    t1 = df["time"].to_numpy(dtype="int64")
    h1 = df["high"].to_numpy(float); l1 = df["low"].to_numpy(float); c1 = df["close"].to_numpy(float)
    o1 = df["open"].to_numpy(float)
    d = resample_ohlcv(df, D1)
    dt = d["time"].to_numpy(dtype="int64")
    dh, dl, dc = d["high"].to_numpy(float), d["low"].to_numpy(float), d["close"].to_numpy(float)
    adx_d = adx(dh, dl, dc, 14)[0]
    atr_d = atr(dh, dl, dc, 14)
    s20, s50, s200 = sma(dc, 20), sma(dc, 50), sma(dc, 200)
    with np.errstate(invalid="ignore", divide="ignore"):
        atrp = atr_d / dc
        z20 = (dc - s20) / atr_d; z50 = (dc - s50) / atr_d; z200 = (dc - s200) / atr_d
        s50_5 = np.r_[np.full(5, np.nan), s50[:-5]]
        slope50 = (s50 - s50_5) / atr_d
        hi20 = pd.Series(dh).rolling(20, min_periods=20).max().to_numpy()
        lo20 = pd.Series(dl).rolling(20, min_periods=20).min().to_numpy()
        d_hi20 = (hi20 - dc) / atr_d; d_lo20 = (dc - lo20) / atr_d
        up, mid, lo, wid = bb_width(dc, 20, 2.0)
        bbw = wid / mid
    D = dict(t=dt, adx_d=adx_d, atrp_pct=roll_pct(atrp, 365), z20=z20, z50=z50, z200=z200,
             slope50=slope50, d_hi20=d_hi20, d_lo20=d_lo20, chop_d=chop(dh, dl, dc, 14),
             bbw_pct=roll_pct(bbw, 365), s200=s200, close=dc)
    q = resample_ohlcv(df, H4)
    Q = dict(t=q["time"].to_numpy(dtype="int64"),
             adx_4h=adx(q["high"].to_numpy(float), q["low"].to_numpy(float), q["close"].to_numpy(float), 14)[0])
    wk_hi = pd.Series(h1).rolling(168, min_periods=168).max().to_numpy()
    wk_lo = pd.Series(l1).rolling(168, min_periods=168).min().to_numpy()
    Hh = dict(t=t1, o=o1, h=h1, l=l1, c=c1, wk_hi=wk_hi, wk_lo=wk_lo)
    F = None
    if fund is not None and len(fund):
        ft = fund["time"].to_numpy(dtype="int64")
        fr = pd.to_numeric(fund["funding"], errors="coerce").to_numpy(float)
        f3 = pd.Series(fr).rolling(3, min_periods=3).sum().to_numpy()
        F = dict(t=ft, fund3_pct=roll_pct(f3, 1095))
    return D, Q, Hh, F

def entry_features(T, side, D, Q, Hh, F, exps):
    out = {}
    i = last_closed(D["t"], D1, T)
    for k in ("adx_d", "atrp_pct", "z20", "z50", "z200", "slope50", "d_hi20", "d_lo20", "chop_d", "bbw_pct"):
        out[k] = float(D[k][i]) if i >= 0 else np.nan
    if i >= 0 and np.isfinite(D["s200"][i]):
        out["trend_agree"] = int(side * (D["close"][i] - D["s200"][i]) > 0)
    else:
        out["trend_agree"] = np.nan
    j4 = last_closed(Q["t"], H4, T)
    out["adx_4h"] = float(Q["adx_4h"][j4]) if j4 >= 0 else np.nan
    j = last_closed(Hh["t"], H1, T)
    c = Hh["c"]
    if j >= 0:
        rng_ = Hh["wk_hi"][j] - Hh["wk_lo"][j]
        out["wk_pos"] = float((c[j] - Hh["wk_lo"][j]) / rng_) if (np.isfinite(rng_) and rng_ > 0) else np.nan
        for nd, k in ((1, "r1d"), (3, "r3d"), (7, "r7d")):
            jj = j - 24 * nd
            out[k] = float(100.0 * (c[j] / c[jj] - 1.0)) if jj >= 0 else np.nan
    else:
        out["wk_pos"] = out["r1d"] = out["r3d"] = out["r7d"] = np.nan
    if F is not None:
        jf = np.searchsorted(F["t"], T, side="left") - 1
        out["fund3_pct"] = float(F["fund3_pct"][jf]) if jf >= 0 else np.nan
    else:
        out["fund3_pct"] = np.nan
    ts = pd.Timestamp(int(T), unit="ms", tz="UTC")
    out["dow"] = int(ts.dayofweek)
    out["hour"] = int(ts.hour)
    k = np.searchsorted(exps, T, side="left")
    out["dte"] = float((exps[k] - T) / D1) if k < len(exps) else np.nan
    return out

def path_labels(tr, Hh, eng):
    t = Hh["t"]; n = len(t)
    T, X = int(tr["entry_time"]), int(tr["exit_time"])
    ei = int(min(max(np.searchsorted(t, T, side="left"), 0), n - 1))
    xi = int(min(max(np.searchsorted(t, X, side="left"), ei), n - 1))
    entry = tr.get("entry", np.nan)
    if not np.isfinite(entry):
        entry = float(Hh["o"][ei])
    risk = tr.get("risk", np.nan)
    side = int(tr["side"])
    mfe = mae = np.nan
    if np.isfinite(risk) and risk > 0 and entry > 0:
        rp = entry * risk
        hi = float(np.max(Hh["h"][ei:xi + 1])); lo = float(np.min(Hh["l"][ei:xi + 1]))
        if side > 0:
            mfe, mae = (hi - entry) / rp, (entry - lo) / rp
        else:
            mfe, mae = (entry - lo) / rp, (hi - entry) / rp
    hold_h = (X - T) / H1
    R = float(tr.get("R", np.nan)) * float(tr.get("weight", 1.0))
    tfh = TF_H.get(eng, 24)
    if not np.isfinite(R):
        ft = "NA"
    elif R > 0:
        ft = "WIN"
    elif np.isfinite(mfe) and mfe >= 1.0:
        ft = "GAVE_BACK"
    elif np.isfinite(mfe) and mfe < 0.3 and hold_h <= 3 * tfh:
        ft = "QUICK_STOP"
    else:
        ft = "SLOW_BLEED"
    return dict(Rw=R, mfe_R=mfe, mae_R=mae, bars_to_exit=xi - ei, hold_h=hold_h,
                engine_bars=hold_h / tfh, ftype=ft)

def build_trades(asset, eng, D, Q, Hh, F, exps):
    t0 = ms(START)
    rows = []
    # interval arrays for "others open"
    iv = {}
    for nm, trs in eng.items():
        iv[nm] = (np.array([int(x["entry_time"]) for x in trs], dtype="int64"),
                  np.array([int(x["exit_time"]) for x in trs], dtype="int64"))
    for nm, trs in eng.items():
        try:
            ts = sorted(list(trs or []), key=lambda x: (int(x["entry_time"]), int(x["exit_time"])))
            if not ts:
                continue
            Ts = np.array([int(x["entry_time"]) for x in ts], dtype="int64")
            others = np.zeros(len(ts), dtype=int)
            for on, (ein, eout) in iv.items():
                if on == nm or len(ein) == 0:
                    continue
                for a in range(0, len(Ts), 2000):
                    q = Ts[a:a + 2000]
                    others[a:a + 2000] += ((ein[None, :] < q[:, None]) & (eout[None, :] > q[:, None])).any(axis=1)
            prev_side = None; streak = 0
            closed = []
            for k, tr in enumerate(ts):
                side = int(tr["side"])
                streak = 1 if (prev_side is None or side != prev_side) else streak + 1
                prev_side = side
                T = int(tr["entry_time"])
                done = [c for c in closed if c[0] <= T]
                last5 = [c[1] for c in sorted(done)[-5:]]
                lab = path_labels(tr, Hh, nm)
                closed.append((int(tr["exit_time"]), lab["Rw"]))
                if int(tr["exit_time"]) < t0:
                    continue
                fe = entry_features(T, side, D, Q, Hh, F, exps)
                row = dict(asset=asset, engine=nm, side=side, entry_time=T, exit_time=int(tr["exit_time"]),
                           entry_ts=str(pd.Timestamp(T, unit="ms", tz="UTC")),
                           exit_ts=str(pd.Timestamp(int(tr["exit_time"]), unit="ms", tz="UTC")),
                           entry=tr.get("entry", np.nan), stop=tr.get("stop", np.nan), exit=tr.get("exit", np.nan),
                           risk=tr.get("risk", np.nan), R=tr.get("R", np.nan), why=tr.get("why", ""),
                           streak=streak, others_open=int(others[k]),
                           last5_wins=(int(sum(1 for x in last5 if np.isfinite(x) and x > 0)) if len(last5) == 5 else np.nan),
                           last5_R=(float(np.nansum(last5)) if len(last5) == 5 else np.nan))
                row.update(fe); row.update(lab)
                rows.append(row)
        except Exception as e:
            print(f"  [{asset}] {nm}: trade build failed: {type(e).__name__}: {e}", flush=True)
    tf = pd.DataFrame(rows)
    if len(tf):
        tf["half"] = np.where(tf["exit_time"] < ms(SPLIT), "17_20", "21_26")
        tf["hour_blk"] = tf["hour"].apply(lambda h: f"h{int(h)//4*4:02d}-{int(h)//4*4+3:02d}")
        tf["dte_blk"] = tf["dte"].apply(lambda x: "NA" if not np.isfinite(x) else ("0-3d" if x < 4 else ("4-7d" if x < 8 else ("8-14d" if x < 15 else "15d+"))))
        tf["streak_b"] = tf["streak"].apply(lambda s: "4th+" if s >= 4 else ["1st", "2nd", "3rd"][int(s) - 1])
        tf["last5_w"] = tf["last5_wins"].apply(lambda w: "NA" if not np.isfinite(w) else ("w0-1" if w <= 1 else ("w2" if w == 2 else ("w3" if w == 3 else "w4-5"))))
        tf["others_b"] = tf["others_open"].apply(lambda o: "3+" if o >= 3 else str(int(o)))
    return tf

# ---------------------------------------------------------------- bucketing
def make_buckets(btc_vals, feat):
    """Return function value-array -> label array, edges fixed from BTC group values."""
    if feat in CAT_FEATS:
        def fn(v):
            return np.array([("NA" if (isinstance(x, float) and not np.isfinite(x)) else str(x)) for x in v], dtype=object)
        return fn
    x = np.asarray(btc_vals, dtype=float); x = x[np.isfinite(x)]
    if len(x) < 30:
        return None
    k = 5 if len(x) >= 150 else 3
    qs = np.unique(np.nanquantile(x, np.linspace(0, 1, k + 1)[1:-1]))
    lo_edges = np.r_[-np.inf, qs]; hi_edges = np.r_[qs, np.inf]
    def _e(v):
        return "lo" if v == -np.inf else ("hi" if v == np.inf else f"{v:.3g}")
    labels = [f"Q{i+1}[{_e(lo_edges[i])},{_e(hi_edges[i])})" for i in range(len(qs) + 1)]
    def fn(v):
        v = np.asarray(v, dtype=float)
        idx = np.searchsorted(qs, v, side="right")
        out = np.array([labels[i] for i in idx], dtype=object)
        out[~np.isfinite(v)] = "NA"
        return out
    return fn

def groups_of(tf):
    g = []
    for nm in sorted(tf["engine"].unique()):
        g.append((nm, tf["engine"] == nm))
    g.append(("ALL_LONG", tf["side"] > 0))
    g.append(("ALL_SHORT", tf["side"] < 0))
    return g

def placebo_pct(r, k, real_pf, rng, n_runs):
    r = np.asarray(r, float); n = len(r)
    if k <= 0 or k >= n or not np.isfinite(real_pf):
        return np.nan
    pfs = np.empty(n_runs)
    for i in range(n_runs):
        keep = np.ones(n, bool); keep[rng.choice(n, size=k, replace=False)] = False
        pfs[i] = rstats(r[keep])["pf"]
    ok = np.isfinite(pfs)
    return 100.0 * float(np.sum(ok & (pfs < real_pf))) / max(1, int(ok.sum()))

def analyse(TB, TE, placebo_n, verbose_tables=True):
    rng = np.random.default_rng(SEED)
    bucket_rows, pockets = [], []
    n_tested = 0
    gb = dict(groups_of(TB))
    ge = dict(groups_of(TE)) if TE is not None and len(TE) else {}
    for gname, mB in gb.items():
        try:
            gB = TB[mB]
            gE = TE[ge[gname]] if gname in ge else None
            if len(gB) < 20:
                print(f"\n--- {gname}: n={len(gB)} < 20, skipped", flush=True)
                continue
            base = rstats(gB["Rw"])
            glines = []
            print(f"\n--- {gname} (BTC n={base['n']} win {f1(base['win'],1)}% PF {f1(base['pf'],3)} totR {f1(base['totR'],1)}) ---", flush=True)
            for feat in NUM_FEATS + CAT_FEATS:
                if feat == "side" and gname.startswith("ALL_"):
                    continue
                fn = make_buckets(gB[feat].to_numpy(), feat)
                if fn is None:
                    continue
                lb = fn(gB[feat].to_numpy())
                le = fn(gE[feat].to_numpy()) if gE is not None and len(gE) else None
                lines = []
                for b in sorted(set(lb), key=str):
                    if b == "NA":
                        continue
                    m = lb == b
                    s = rstats(gB["Rw"][m])
                    h1 = rstats(gB["Rw"][m & (gB["half"] == "17_20").to_numpy()])
                    h2 = rstats(gB["Rw"][m & (gB["half"] == "21_26").to_numpy()])
                    se = rstats(gE["Rw"][le == b]) if le is not None else rstats([])
                    n_tested += 1
                    row = dict(group=gname, feature=feat, bucket=b, n=s["n"], win=s["win"], PF=s["pf"], avgR=s["avgR"],
                               totR=s["totR"], PF_17_20=h1["pf"], n_17_20=h1["n"], PF_21_26=h2["pf"], n_21_26=h2["n"],
                               n_eth=se["n"], PF_eth=se["pf"])
                    bucket_rows.append(row)
                    lines.append((s["pf"] if (s["n"] >= 20 and np.isfinite(s["pf"])) else 9e9, f"    {feat:11s} {b:26s} n={s['n']:4d} win={f1(s['win'],1):>5s}% PF={f1(s['pf'],2):>5s} avgR={f1(s['avgR'],2):>6s} | h1 {f1(h1['pf'],2):>5s} h2 {f1(h2['pf'],2):>5s} | ETH n={se['n']:4d} PF={f1(se['pf'],2):>5s}"))
                    if s["n"] >= 20 and np.isfinite(s["pf"]) and s["pf"] < 0.8:
                        fails = []
                        for lab_, v in (("PF_17_20", h1["pf"]), ("PF_21_26", h2["pf"])):
                            if not (np.isfinite(v) and v < 1.0):
                                fails.append(f"{lab_}={f1(v,2)}")
                        if se["n"] < 10:
                            fails.append(f"ETH n={se['n']}<10")
                        elif not (np.isfinite(se["pf"]) and se["pf"] < 1.0):
                            fails.append(f"ETH PF={f1(se['pf'],2)}")
                        keep = ~m
                        after = rstats(gB["Rw"][keep])
                        pct = placebo_pct(gB["Rw"].to_numpy(), int(m.sum()), after["pf"], rng, placebo_n)
                        if not (np.isfinite(pct) and pct >= 90.0):
                            fails.append(f"placebo {f1(pct,1)}<90")
                        aE = rstats(gE["Rw"][~(le == b)]) if le is not None else rstats([])
                        bE = rstats(gE["Rw"]) if gE is not None else rstats([])
                        p = dict(row)
                        p.update(base_PF=base["pf"], PF_after=after["pf"], dPF=after["pf"] - base["pf"],
                                 base_totR=base["totR"], totR_after=after["totR"], dR=after["totR"] - base["totR"],
                                 n_skip=int(m.sum()), placebo_pctile=pct,
                                 eth_base_PF=bE["pf"], eth_PF_after=aE["pf"],
                                 verdict="WORTH_WF" if not fails else "NOISE", failed="; ".join(fails))
                        pockets.append(p)
                if FULL and lines:
                    for _, ln in lines:
                        print(ln, flush=True)
                glines.extend(lines)
            if not FULL:
                worst = sorted([x for x in glines if x[0] < 9e9], key=lambda x: x[0])[:10]
                print("  worst 10 buckets by BTC PF (n>=20):", flush=True)
                for _, ln in worst:
                    print(ln, flush=True)
        except Exception as e:
            print(f"  {gname}: analysis failed: {type(e).__name__}: {e}", flush=True)
    return pd.DataFrame(bucket_rows), pd.DataFrame(pockets), n_tested

# ---------------------------------------------------------------- failure mix
def failure_mix(tf, label):
    print(f"\n=== FAILURE-TYPE MIX ({label}) - share of losers; MFE/MAE medians in R ===", flush=True)
    for gname, m in groups_of(tf):
        try:
            g = tf[m]
            L = g[g["ftype"].isin(["QUICK_STOP", "GAVE_BACK", "SLOW_BLEED"])]
            if len(g) == 0:
                continue
            nL = max(1, len(L))
            q = 100.0 * (L["ftype"] == "QUICK_STOP").sum() / nL
            gbk = 100.0 * (L["ftype"] == "GAVE_BACK").sum() / nL
            sb = 100.0 * (L["ftype"] == "SLOW_BLEED").sum() / nL
            if gbk >= 35:
                hint = "GAVE_BACK-heavy -> exit/BE issue (trail or BE earlier)"
            elif q >= 50:
                hint = "QUICK_STOP-heavy -> entry timing (confirm/retest entry)"
            elif sb >= 60:
                hint = "SLOW_BLEED-heavy -> regime/filter issue (trade dies slowly; time stop or regime gate)"
            else:
                hint = "mixed"
            print(f"  {gname:9s} n={len(g):4d} losers={len(L):4d} QUICK={f1(q,0):>3s}% GAVE_BACK={f1(gbk,0):>3s}% SLOW={f1(sb,0):>3s}% "
                  f"| loser MFE med {f1(L['mfe_R'].median(),2)} MAE med {f1(L['mae_R'].median(),2)} hold_h med {f1(L['hold_h'].median(),0)} "
                  f"| win MFE med {f1(g[g['ftype']=='WIN']['mfe_R'].median(),2)} -> {hint}", flush=True)
        except Exception as e:
            print(f"  {gname}: mix failed: {type(e).__name__}: {e}", flush=True)

# ---------------------------------------------------------------- decision tree
def leaf_rules(tree, names):
    tr = tree.tree_
    rules = {}
    def walk(node, path):
        if tr.children_left[node] == tr.children_right[node]:
            rules[node] = " AND ".join(path) if path else "(all)"
            return
        nm = names[tr.feature[node]]; th = tr.threshold[node]
        walk(tr.children_left[node], path + [f"{nm}<={th:.3g}"])
        walk(tr.children_right[node], path + [f"{nm}>{th:.3g}"])
    walk(0, [])
    return rules

def tree_section(TB, TE):
    print("\n=== DECISION TREE (depth 3, predict loser; train exits < 2022, test 2022-26; ETH = BTC tree applied) ===", flush=True)
    try:
        from sklearn.tree import DecisionTreeClassifier, export_text
    except Exception:
        print("  sklearn not available -> skipped (pip install scikit-learn)", flush=True)
        return []
    out = []
    t_split = ms(TREE_SPLIT)
    gb = dict(groups_of(TB)); ge = dict(groups_of(TE)) if TE is not None and len(TE) else {}
    for gname, mB in gb.items():
        try:
            g = TB[mB]
            tr = g[g["exit_time"] < t_split]; te = g[g["exit_time"] >= t_split]
            if len(tr) < 100 or len(te) < 20:
                print(f"  {gname}: train {len(tr)} / test {len(te)} too small, skipped", flush=True)
                continue
            Xtr = tr[TREE_FEATS].astype(float)
            med = Xtr.median()
            Xtr = Xtr.fillna(med).to_numpy(); ytr = (tr["Rw"] <= 0).to_numpy().astype(int)
            msl = max(20, len(tr) // 20)
            clf = DecisionTreeClassifier(max_depth=3, min_samples_leaf=msl, random_state=0).fit(Xtr, ytr)
            rules = leaf_rules(clf, TREE_FEATS)
            leaf_tr = clf.apply(Xtr)
            bad = []
            for lf in sorted(set(leaf_tr)):
                s = rstats(tr["Rw"].to_numpy()[leaf_tr == lf])
                if np.isfinite(s["pf"]) and s["pf"] < 0.8 and s["n"] >= 20:
                    bad.append(lf)
            Xte = te[TREE_FEATS].astype(float).fillna(med).to_numpy()
            leaf_te = clf.apply(Xte)
            all_s = rstats(te["Rw"]); kept = rstats(te["Rw"].to_numpy()[~np.isin(leaf_te, bad)])
            eth_txt = ""
            eth_all = eth_kept = rstats([])
            if gname in ge:
                gE = TE[ge[gname]]
                if len(gE):
                    leaf_e = clf.apply(gE[TREE_FEATS].astype(float).fillna(med).to_numpy())
                    eth_all = rstats(gE["Rw"]); eth_kept = rstats(gE["Rw"].to_numpy()[~np.isin(leaf_e, bad)])
                    eth_txt = f" | ETH all PF {f1(eth_all['pf'],3)} (n {eth_all['n']}) kept PF {f1(eth_kept['pf'],3)} (n {eth_kept['n']})"
            print(f"\n  {gname}: train n={len(tr)} test n={len(te)} | skip leaves(train PF<0.8): {len(bad)}", flush=True)
            for lf in sorted(set(leaf_tr)):
                s = rstats(tr["Rw"].to_numpy()[leaf_tr == lf]); st = rstats(te["Rw"].to_numpy()[leaf_te == lf])
                tag = "SKIP" if lf in bad else "keep"
                print(f"    [{tag}] {rules.get(lf,'?')}  | train n={s['n']} PF={f1(s['pf'],2)} | test n={st['n']} PF={f1(st['pf'],2)}", flush=True)
            better = np.isfinite(kept["pf"]) and np.isfinite(all_s["pf"]) and kept["pf"] > all_s["pf"] and len(bad) > 0
            print(f"    OOS 2022-26: all PF {f1(all_s['pf'],3)} totR {f1(all_s['totR'],1)} (n {all_s['n']}) | kept PF {f1(kept['pf'],3)} totR {f1(kept['totR'],1)} (n {kept['n']}){eth_txt} -> {'helps OOS' if better else 'no OOS gain'}", flush=True)
            out.append(dict(group=gname, n_train=len(tr), n_test=len(te), skip_leaves=len(bad),
                            oos_PF_all=all_s["pf"], oos_PF_kept=kept["pf"], oos_R_all=all_s["totR"], oos_R_kept=kept["totR"],
                            eth_PF_all=eth_all["pf"], eth_PF_kept=eth_kept["pf"],
                            rules=" || ".join(rules.get(lf, "?") for lf in bad)))
        except Exception as e:
            print(f"  {gname}: tree failed: {type(e).__name__}: {e}", flush=True)
    return out

# ---------------------------------------------------------------- charts of recent losers
def loser_charts(tf, Hh, asset, max_per=9):
    try:
        import matplotlib
        matplotlib.use("Agg")
        import matplotlib.pyplot as plt
    except Exception:
        print("  matplotlib not available -> no charts", flush=True)
        return
    od = OUT_DIR / "autopsy_charts"
    od.mkdir(exist_ok=True)
    t = Hh["t"]
    made = 0
    for nm in sorted(tf["engine"].unique()):
        try:
            L = tf[(tf["engine"] == nm) & (tf["Rw"] <= 0)].sort_values("entry_time").tail(max_per)
            if not len(L):
                continue
            fig, axs = plt.subplots(3, 3, figsize=(15, 10))
            for ax, (_, r) in zip(axs.ravel(), L.iterrows()):
                tfh = TF_H.get(nm, 24)
                ei = int(np.searchsorted(t, r["entry_time"])); xi = int(np.searchsorted(t, r["exit_time"]))
                a = max(0, ei - 40 * tfh); z = min(len(t) - 1, xi + 10 * tfh)
                xs = (t[a:z + 1] - t[ei]) / H1
                ax.fill_between(xs, Hh["l"][a:z + 1], Hh["h"][a:z + 1], color="0.85")
                ax.plot(xs, Hh["c"][a:z + 1], lw=0.8, color="k")
                col = "g" if r["side"] > 0 else "r"
                ax.axvline(0, color=col, lw=1); ax.axvline((t[min(xi, len(t)-1)] - t[ei]) / H1, color="b", lw=1, ls="--")
                if np.isfinite(r["stop"]):
                    ax.axhline(r["stop"], color="r", lw=0.7, ls=":")
                if np.isfinite(r["entry"]):
                    ax.axhline(r["entry"], color=col, lw=0.7, ls=":")
                ax.set_title(f"{nm} {'L' if r['side']>0 else 'S'} {str(r['entry_ts'])[:16]} R={r['Rw']:.2f} {r['ftype']}", fontsize=8)
                ax.tick_params(labelsize=6)
            for ax in axs.ravel()[len(L):]:
                ax.axis("off")
            fig.suptitle(f"{asset.upper()} {nm}: last {len(L)} losers (x = hours from entry; green/red = entry, blue = exit, dotted = stop)", fontsize=10)
            fig.tight_layout()
            fig.savefig(od / f"{asset}_{nm}_losers.png", dpi=80)
            plt.close(fig)
            made += 1
        except Exception as e:
            print(f"  chart {nm} failed: {type(e).__name__}: {e}", flush=True)
    print(f"  saved {made} loser chart grids to {od}", flush=True)

# ---------------------------------------------------------------- main
def run_asset(label, df, fund, exps):
    ta = time.time()
    print(f"\n=== {label.upper()}: building oslib live engines (X7 on: funding passed) ...", flush=True)
    eng = engines(df, fund=fund)
    print(f"  {label}: " + ", ".join(f"{k} {len(v)}" for k, v in eng.items()) + f"  ({time.time()-ta:.0f}s)", flush=True)
    D, Q, Hh, F = market_frames(df, fund)
    tf = build_trades(label, eng, D, Q, Hh, F, exps)
    print(f"  {label}: {len(tf)} trades with features ({time.time()-ta:.0f}s)", flush=True)
    return tf, Hh

def main(smoke=False):
    print("=== autopsy.py: failure patterns in live-basket losers (BTC/ETH 2017+, X7 on, 0.12%/side) ===", flush=True)
    placebo_n = PLACEBO_N
    if smoke:
        print("SMOKE MODE: synthetic data only (no real backtest).", flush=True)
        placebo_n = 20
        data = {}
        for a, seed in (("btc", 9), ("eth", 21)):
            h1 = synthetic_1h(n=int(os.environ.get("AUTOPSY_SMOKE_N", "12000")), seed=seed, start="2017-01-02")
            fund = pd.DataFrame({"time": h1["time"].to_numpy()[::8],
                                 "funding": np.random.default_rng(seed).normal(0, 1e-4, (len(h1) + 7) // 8)})
            data[a] = (h1, fund)
    else:
        data = {a: (load(a, "1h"), funding(a, "binance")) for a in ("btc", "eth")}
    exps = np.array([int(e.value // 1_000_000) for e in expiry_days("2012-01-01", "2027-12-31")], dtype="int64")
    T, HH = {}, {}
    for a, (df, fund) in data.items():
        try:
            T[a], HH[a] = run_asset(a, df, fund, exps)
        except Exception as e:
            print(f"  {a}: engine/feature build failed: {type(e).__name__}: {e}", flush=True)
            T[a] = pd.DataFrame()
    TB, TE = T.get("btc", pd.DataFrame()), T.get("eth", pd.DataFrame())
    if not len(TB):
        print("No BTC trades -> nothing to analyse.", flush=True)
        return
    allT = pd.concat([x for x in (TB, TE) if len(x)], ignore_index=True)
    p_trades = OUT_DIR / ("autopsy_trades_smoke.csv" if smoke else "autopsy_trades.csv")
    allT.to_csv(p_trades, index=False)
    print(f"Saved {p_trades} ({len(allT)} rows)", flush=True)

    failure_mix(TB, "BTC")
    if len(TE):
        failure_mix(TE, "ETH")

    print("\n=== BUCKET TABLES (BTC; edges from BTC; AUTOPSY_FULL=1 prints all, else worst 10 per group; all in autopsy_buckets.csv, same edges on ETH; h1 = 2017-20, h2 = 2021-26) ===", flush=True)
    buckets, pockets, n_tested = analyse(TB, TE, placebo_n)
    trees = tree_section(TB, TE)

    print(f"\n=== TOP POCKETS (candidates: BTC bucket PF<0.8 & n>=20; {n_tested} buckets tested, so expect some chance hits) ===", flush=True)
    if len(pockets):
        pockets = pockets.assign(_w=(pockets["verdict"] == "WORTH_WF").astype(int))
        pockets = pockets.sort_values(["_w", "placebo_pctile", "dR"], ascending=[False, False, False]).drop(columns="_w")
        show = pockets.head(30).copy()
        cols = ["verdict", "group", "feature", "bucket", "n", "PF", "PF_17_20", "PF_21_26", "n_eth", "PF_eth",
                "base_PF", "PF_after", "dR", "placebo_pctile", "failed"]
        for c in ("PF", "PF_17_20", "PF_21_26", "PF_eth", "base_PF", "PF_after"):
            show[c] = show[c].map(lambda v: f1(v, 2))
        show["dR"] = show["dR"].map(lambda v: f1(v, 1)); show["placebo_pctile"] = show["placebo_pctile"].map(lambda v: f1(v, 0))
        print(show[cols].to_string(index=False), flush=True)
        nw = int((pockets["verdict"] == "WORTH_WF").sum())
        print(f"\n  {nw} WORTH_WF pocket(s) of {len(pockets)} candidates.", flush=True)
    else:
        print("  no candidate buckets.", flush=True)
    p_pk = OUT_DIR / ("autopsy_pockets_smoke.csv" if smoke else "autopsy_pockets.csv")
    (pockets if len(pockets) else pd.DataFrame(columns=["group", "feature", "bucket", "verdict"])).to_csv(p_pk, index=False)
    buckets.to_csv(OUT_DIR / ("autopsy_buckets_smoke.csv" if smoke else "autopsy_buckets.csv"), index=False)
    if trees:
        pd.DataFrame(trees).to_csv(OUT_DIR / ("autopsy_tree_smoke.csv" if smoke else "autopsy_tree.csv"), index=False)
    print(f"Saved {p_pk}, autopsy_buckets, autopsy_tree", flush=True)

    print("\n=== LOSER CHARTS (last 9 losers per engine, BTC) ===", flush=True)
    if "btc" in HH:
        loser_charts(TB, HH["btc"], "btc")
    print("\nVERDICT KEY: WORTH_WF = pocket passes BTC PF<0.8 n>=20, both halves PF<1, ETH PF<1, placebo>=90 -> next step is a walk-forward skip test. NOISE = fails at least one gate (see 'failed').", flush=True)
    print(f"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)
