"""Soft/hard blend: published SW2 decoder+clf fuse ↔ technique-synth-switch clf.

Acc-strong × Acc-strong (neither is linear_hp30 / stem):
  sw2   = README_BEST legal stack: 4 decoder + 4 clf10(sw2) via fuse_general a=0.5
          (AASD Acc 53.46 @0.994/0.8)
  swmix = direct_clf__eaP_n5_t60_w10b3_ptSPK_aug-sw2_swmix (technique-synth-switch)
          (AASD Acc 53.26 @0.994/0.8)

Reuses SW2 LODO/external caches + DEC_OFFSET alignment from sw2_hp30_blend.py.
DISTINCT from SW2↔hp30, SW2-as-5th-seed, prep-diverse, stem-sw2-ms.

Grid: soft w∈{0,0.25,0.5,0.75,1} and causal gates on |sw2| / |sw2−swmix|.
Select by mean LODO Acc then H at HMM p_stay=0.994 scale=0.8 (never AASD/Carta).
Score AASD + Carta with the selected rule. CPU only.

usage:
  /root/disk_3tb/EEG-sAAD-Grand-Challenge-Training-Dataset/.venv/bin/python -u sw2_swmix_blend.py
"""
from __future__ import annotations

import json
import os
import pickle
import time

import numpy as np
from scipy.signal import lfilter
from scipy.special import expit

import ensemble_clf as EC
import ensemble_clf_nested as N
import ensemble_clf_transformer_v4 as V4
import eval_external as E
import score as S
import sw2_hp30_blend as SW2
from common import DS_KEYS
from fuse_evidence import LA, OFF

EXP = os.path.dirname(os.path.abspath(__file__))
CACHE_DIR = os.path.join(EXP, "models", "sw2_swmix_blend", "cache")
SW2_CACHE = SW2.CACHE_DIR
LOG = os.path.join(EXP, "experiments", "sw2_swmix_blend.log")
OUT = os.path.join(EXP, "results", "research", "sw2_swmix_blend.json")
RESULTS_MD = os.path.join(EXP, "multi_agent_opt", "results_sw2_swmix_blend.md")

SWMIX_EXP = "direct_clf__eaP_n5_t60_w10b3_ptSPK_aug-sw2_swmix"
SWMIX_EXT = {
    "AASD": os.path.join(EXP, "results", "research", "ext_clf_AASD_w10b3_ptSPK_aug-sw2_swmix_evidence.pkl"),
    "Carta2026": os.path.join(
        EXP, "results", "research", "ext_clf_Carta2026_w10b3_ptSPK_aug-sw2_swmix_evidence.pkl"
    ),
}

P_STAY = 0.994
SCALE = 0.8
LOOKAHEAD = float(LA)
A_SW2 = SW2.A_SW2

LINEAR_HP30_EXT = dict(AASD=dict(H=0.6422, Acc=53.12), Carta2026=dict(H=0.6520, Acc=60.54))
SW2_ALONE_EXT = dict(AASD=dict(H=0.6439, Acc=53.46), Carta2026=dict(H=0.6470, Acc=59.60))
SWMIX_ALONE_EXT = dict(AASD=dict(H=0.6421, Acc=53.26), Carta2026=dict(H=0.6450, Acc=59.82))


def log_line(text):
    print(text, flush=True)
    os.makedirs(os.path.dirname(LOG), exist_ok=True)
    with open(LOG, "a") as fh:
        fh.write(text + "\n")


def save_pkl(path, obj):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "wb") as fh:
        pickle.dump(obj, fh, protocol=pickle.HIGHEST_PROTOCOL)


def load_pkl(path):
    with open(path, "rb") as fh:
        return pickle.load(fh)


def ewma_1d(x, tau_s=4.0, hop=0.25):
    x = np.asarray(x, np.float64)
    alpha = 1.0 - np.exp(-hop / tau_s)
    return lfilter([alpha], [1.0, -(1.0 - alpha)], x)


def gate_series(sw2, swmix, kind, thresh, sharp, ewma_tau=4.0):
    """g∈[0,1]; high g → trust sw2."""
    f = np.asarray(sw2, np.float64)
    h = np.asarray(swmix, np.float64)
    n = min(len(f), len(h))
    f, h = f[:n], h[:n]
    if kind == "soft_w":
        w = float(thresh)
        return np.full(n, w, np.float64)
    if kind == "const_sw2":
        return np.ones(n, np.float64)
    if kind == "const_swmix":
        return np.zeros(n, np.float64)
    if kind == "abs_sw2":
        return expit(sharp * (np.abs(f) - thresh))
    if kind == "ewma_abs_sw2":
        return expit(sharp * (ewma_1d(np.abs(f), ewma_tau) - thresh))
    if kind == "abs_swmix":
        return expit(sharp * (thresh - np.abs(h)))  # high |swmix| → trust swmix (low g)
    if kind == "ewma_abs_either":
        # trust the stream with larger EWMA |logit|
        af = ewma_1d(np.abs(f), ewma_tau)
        ah = ewma_1d(np.abs(h), ewma_tau)
        return expit(sharp * (af - ah - thresh))
    if kind == "disagree":
        return expit(sharp * (thresh - np.abs(f - h)))
    if kind == "ewma_disagree":
        return expit(sharp * (thresh - ewma_1d(np.abs(f - h), ewma_tau)))
    if kind == "hard_abs":
        return (np.abs(f) >= thresh).astype(np.float64)
    if kind == "hard_abs_swmix":
        # hard: prefer swmix when |swmix| >= thr else sw2
        return (np.abs(h) < thresh).astype(np.float64)
    if kind == "abs_and_disagree":
        a = expit(sharp * (np.abs(f) - thresh))
        d = expit(sharp * (thresh - np.abs(f - h)))
        return a * d
    raise ValueError(kind)


def apply_gate_stream(sw2_st, sm_st, kind, thresh, sharp):
    out = {}
    for key in sw2_st:
        if key not in sm_st:
            continue
        f = np.asarray(sw2_st[key], np.float64)
        h = np.asarray(sm_st[key], np.float64)
        n = min(len(f), len(h))
        g = gate_series(f[:n], h[:n], kind, thresh, sharp)
        out[key] = (g * f[:n] + (1.0 - g) * h[:n]).astype(np.float64)
    return out


def apply_gate_all(sw2_all, sm_all, kind, thresh, sharp):
    return {
        ds: apply_gate_stream(sw2_all[ds], sm_all[ds], kind, thresh, sharp)
        for ds in sw2_all
        if ds in sm_all
    }


def candidate_rules():
    rules = []
    for w in (0.0, 0.25, 0.5, 0.75, 1.0):
        rules.append(("soft_w", w, 1.0))
    rules += [
        ("const_sw2", 0.0, 1.0),
        ("const_swmix", 0.0, 1.0),
        ("abs_sw2", 0.5, 4.0),
        ("abs_sw2", 1.0, 4.0),
        ("abs_sw2", 1.5, 4.0),
        ("ewma_abs_sw2", 0.5, 4.0),
        ("ewma_abs_sw2", 1.0, 4.0),
        ("ewma_abs_sw2", 1.5, 4.0),
        ("ewma_abs_either", 0.0, 4.0),
        ("ewma_abs_either", 0.25, 4.0),
        ("disagree", 0.5, 4.0),
        ("disagree", 1.0, 4.0),
        ("disagree", 1.5, 4.0),
        ("ewma_disagree", 0.5, 4.0),
        ("ewma_disagree", 1.0, 4.0),
        ("hard_abs", 0.5, 1.0),
        ("hard_abs", 1.0, 1.0),
        ("hard_abs", 1.5, 1.0),
        ("hard_abs_swmix", 0.5, 1.0),
        ("hard_abs_swmix", 1.0, 1.0),
        ("abs_and_disagree", 0.75, 4.0),
        ("abs_and_disagree", 1.0, 4.0),
    ]
    return rules


def rule_key(kind, thr, sharp):
    if kind == "soft_w":
        return f"soft_w={thr:g}"
    return f"{kind}|t{thr:g}|s{sharp:g}"


def fuse_sw2_held(Z, held, a=A_SW2):
    return SW2.fuse_sw2_held(Z, held, a=a)


def align_swmix_to_sw2(swmix_full, sw2, off=OFF):
    """Truncate/shift full-length swmix deltas to match SW2 DEC_OFFSET alignment."""
    out = {}
    for ds in sw2:
        out[ds] = {}
        for k, f in sw2[ds].items():
            if k not in swmix_full[ds]:
                continue
            h = np.asarray(swmix_full[ds][k], np.float64).reshape(-1)
            n = len(f)
            if len(h) >= off + n:
                out[ds][k] = h[off:off + n].copy()
            else:
                sl = h[off:off + n] if len(h) > off else h[:n]
                pad = np.zeros(n, np.float64)
                pad[: len(sl)] = sl
                out[ds][k] = pad
    return out


def ev_from_stream(stream, meta):
    ev = {}
    for ds in DS_KEYS:
        ev[ds] = {}
        for k, d in stream[ds].items():
            att, te = meta[ds][k]
            d = np.asarray(d, np.float64)
            n = len(d)
            ev[ds][k] = dict(
                r0=d,
                r1=np.zeros(n),
                att=np.asarray(att)[:n],
                t_end=np.asarray(te, np.float64)[:n],
                pre_switched=True,
            )
    return ev


def ensure_sw2_lodo():
    path = os.path.join(SW2_CACHE, "sw2_lodo_Z_meta.pkl")
    if os.path.isfile(path):
        log_line(f"cache hit {path}")
        return load_pkl(path)
    return SW2.ensure_sw2_lodo()


def ensure_swmix_lodo():
    path = os.path.join(CACHE_DIR, "swmix_lodo.pkl")
    if os.path.isfile(path):
        log_line(f"cache hit {path}")
        return load_pkl(path)
    log_line(f"loading swmix LODO folds ({SWMIX_EXP}) …")
    t0 = time.time()
    from common_exp import fold_file

    missing = [fold_file(SWMIX_EXP, ds) for ds in DS_KEYS if not os.path.exists(fold_file(SWMIX_EXP, ds))]
    if missing:
        raise FileNotFoundError(
            "swmix LODO folds missing:\n" + "\n".join(missing)
        )
    ev, info = S.load_folds(SWMIX_EXP, "causal")
    out = {ds: {k: EC.delta(e) for k, e in ev[ds].items()} for ds in DS_KEYS}
    la = float(info[DS_KEYS[0]]["lookahead_s"])
    save_pkl(path, (out, la))
    log_line(f"swmix LODO cache wrote ({time.time() - t0:.0f}s) lookahead={la}")
    return out, la


def score_lodo_held(stream_all, meta, held):
    ev = ev_from_stream(stream_all, meta)
    V4._install_scorer_state(ev, LOOKAHEAD)
    return N.official(held, ev, P_STAY, SCALE)


def mean_lodo_for_rule(Z, meta, swmix_full, kind, thr, sharp):
    hs, acs, per = [], [], {}
    for held in DS_KEYS:
        sw2 = fuse_sw2_held(Z, held)
        sm = align_swmix_to_sw2(swmix_full, sw2)
        gated = apply_gate_all(sw2, sm, kind, thr, sharp)
        r = score_lodo_held(gated, meta, held)
        hs.append(r["H"])
        acs.append(r["Acc"])
        per[held] = dict(H=r["H"], Acc=r["Acc"], SDT=r["SDT"], L=r.get("L"))
    return float(np.mean(hs)), float(np.mean(acs)), per


def ensure_sw2_external():
    path = os.path.join(SW2_CACHE, "sw2_external_a05.pkl")
    if os.path.isfile(path):
        log_line(f"cache hit {path}")
        return load_pkl(path)
    return SW2.ensure_sw2_external()


def ensure_swmix_external():
    path = os.path.join(CACHE_DIR, "swmix_external.pkl")
    if os.path.isfile(path):
        log_line(f"cache hit {path}")
        return load_pkl(path)
    missing = [p for p in SWMIX_EXT.values() if not os.path.isfile(p)]
    if missing:
        raise FileNotFoundError("swmix external evidence missing:\n" + "\n".join(missing))
    out = {}
    for ds, p in SWMIX_EXT.items():
        raw = load_pkl(p)
        # store full-length delta (r0-r1); align later with OFF vs SW2
        out[ds] = {k: EC.delta(e) for k, e in raw.items()}
        # keep meta from raw for packing
        out[ds + "__meta"] = raw
    save_pkl(path, out)
    log_line(f"swmix external cache wrote → {path}")
    return out


def align_ext_swmix_to_sw2(sm_stream, sw2_ev, off=OFF):
    out = {}
    for k, e in sw2_ev.items():
        if k not in sm_stream:
            continue
        f = np.asarray(e["r0"], np.float64)
        h = np.asarray(sm_stream[k], np.float64).reshape(-1)
        n = len(f)
        if len(h) >= off + n:
            out[k] = h[off:off + n].copy()
        else:
            sl = h[off:off + n] if len(h) > off else h[:n]
            pad = np.zeros(n, np.float64)
            pad[: len(sl)] = sl
            out[k] = pad
    return out


def blend_ext_ev(sw2_ev, sm_aligned, kind, thr, sharp):
    out = {}
    for k, e in sw2_ev.items():
        if k not in sm_aligned:
            continue
        f = np.asarray(e["r0"], np.float64)
        h = np.asarray(sm_aligned[k], np.float64)
        n = min(len(f), len(h))
        g = gate_series(f[:n], h[:n], kind, thr, sharp)
        d = g * f[:n] + (1.0 - g) * h[:n]
        out[k] = dict(
            r0=d,
            r1=np.zeros(n),
            att=e["att"][:n],
            t_end=e["t_end"][:n],
            att128=e["att128"],
            n128=e["n128"],
            subject=e["subject"],
        )
    return out


def corpus_emis_for_blend(Z, meta, swmix_full, kind, thr, sharp):
    acc = {ds: {} for ds in DS_KEYS}
    counts = {ds: {} for ds in DS_KEYS}
    for held in DS_KEYS:
        sw2 = fuse_sw2_held(Z, held)
        sm = align_swmix_to_sw2(swmix_full, sw2)
        gated = apply_gate_all(sw2, sm, kind, thr, sharp)
        for ds in DS_KEYS:
            for k, d in gated[ds].items():
                if k not in acc[ds]:
                    acc[ds][k] = np.zeros_like(d, np.float64)
                    counts[ds][k] = 0
                n = min(len(acc[ds][k]), len(d))
                acc[ds][k][:n] += d[:n]
                counts[ds][k] += 1
    stream = {}
    for ds in DS_KEYS:
        stream[ds] = {k: acc[ds][k] / max(counts[ds][k], 1) for k in acc[ds]}
    parts = []
    for ds in DS_KEYS:
        for k, d in stream[ds].items():
            att = meta[ds][k][0]
            n = min(len(d), len(att))
            parts.append(d[:n] * np.where(np.asarray(att)[:n] == 0, 1.0, -1.0))
    A = np.concatenate(parts)
    return float(A.mean()), float(A.std())


def _swmix_as_ev(sm_stream, raw_meta, off_align_to=None):
    """Pack full-length swmix deltas into external evidence; optionally OFF-align to SW2."""
    out = {}
    for k, h0 in sm_stream.items():
        h = np.asarray(h0, np.float64).reshape(-1)
        m = raw_meta[k]
        if off_align_to is not None and k in off_align_to:
            n = len(off_align_to[k]["r0"])
            if len(h) >= OFF + n:
                h = h[OFF:OFF + n]
            else:
                h = h[:n]
            att = off_align_to[k]["att"][: len(h)]
            te = off_align_to[k]["t_end"][: len(h)]
            att128 = off_align_to[k]["att128"]
            n128 = off_align_to[k]["n128"]
            subject = off_align_to[k]["subject"]
        else:
            att = m["att"][: len(h)]
            te = m["t_end"][: len(h)]
            att128 = m["att128"]
            n128 = m["n128"]
            subject = m["subject"]
        out[k] = dict(
            r0=h,
            r1=np.zeros(len(h)),
            att=att,
            t_end=te,
            att128=att128,
            n128=n128,
            subject=subject,
        )
    return out


def _json_default(o):
    if isinstance(o, (np.floating, np.integer)):
        return float(o)
    if isinstance(o, np.ndarray):
        return o.tolist()
    raise TypeError(type(o))


def write_md_abandon(reason):
    text = f"""# results_sw2_swmix_blend

**Status: abandoned**

Could not load SW2 fuse and/or technique-synth-switch (swmix) evidence.

Reason:
```
{reason}
```

## NEXT IDEA

Restore SW2 caches under `models/sw2_hp30_blend/cache/` and swmix folds/external pickles before retrying. Do not retrain either Acc stream for a blend experiment.
"""
    with open(RESULTS_MD, "w") as fh:
        fh.write(text)


def write_md_partial(selected, rows, reason):
    with open(RESULTS_MD, "w") as fh:
        fh.write("# results_sw2_swmix_blend\n\n**Status: partial (LODO only)**\n\n")
        fh.write(
            f"Selected: `{selected['key']}` LODO mean H {selected['mean_LODO_H']:.4f} "
            f"Acc {selected['mean_LODO_Acc']:.2f}\n\nExternal abort: {reason}\n"
        )


def write_md(summary):
    sel = summary["selected"]
    ext = summary["external"]
    lines = []
    lines.append("# results_sw2_swmix_blend\n")
    lines.append(
        "Soft/hard blend of **published SW2 decoder+classifier fuse** (README_BEST, `fuse_general` a=0.5; "
        "AASD Acc 53.46) with **technique-synth-switch** classifier evidence "
        f"(`{SWMIX_EXP}`; AASD Acc 53.26), aligned by `DEC_OFFSET={OFF}`. "
        "**Not** SW2↔hp30 / SW2-as-5th / prep-diverse / stem-sw2-ms.\n"
    )
    lines.append(
        f"HMM preset **{P_STAY} / {SCALE}**. Code: `sw2_swmix_blend.py`. "
        f"JSON: `results/research/sw2_swmix_blend.json`.\n"
    )
    lines.append("## Selection (mean LODO Acc then H; never AASD/Carta)\n")
    lines.append(
        f"**SELECTED `{sel['key']}`** — mean LODO H **{sel['mean_LODO_H']:.4f}** "
        f"Acc **{sel['mean_LODO_Acc']:.2f}**\n"
    )
    lines.append("| Held-out | H | Acc % |")
    lines.append("|---|---:|---:|")
    for ds in DS_KEYS:
        p = sel["per_ds"][ds]
        lines.append(f"| {ds} | {p['H']:.4f} | {p['Acc']:.2f} |")
    lines.append(
        f"| **mean** | **{sel['mean_LODO_H']:.4f}** | **{sel['mean_LODO_Acc']:.2f}** |\n"
    )
    lines.append("### Soft-w grid (reference)\n")
    lines.append("| Rule | mean H | mean Acc |")
    lines.append("|---|---:|---:|")
    for r in summary["lodo_grid"]:
        if r["kind"] == "soft_w" or r["key"] == sel["key"]:
            mark = " **←**" if r["key"] == sel["key"] else ""
            lines.append(
                f"| `{r['key']}`{mark} | {r['mean_LODO_H']:.4f} | {r['mean_LODO_Acc']:.2f} |"
            )
    lines.append("\n## External (preset)\n")
    lines.append("| Set | selected H/Acc | sw2_only | swmix_only | linear_hp30 | SW2 baseline |")
    lines.append("|---|---|---|---|---|---|")
    for ds in ("AASD", "Carta2026"):
        s = ext[ds]["selected"]
        w = ext[ds]["sw2_only"]
        m = ext[ds]["swmix_only"]
        b = LINEAR_HP30_EXT[ds]
        swb = SW2_ALONE_EXT[ds]
        lines.append(
            f"| {ds} | {s['H']:.4f} / **{s['Acc']:.2f}** | {w['H']:.4f}/{w['Acc']:.2f} | "
            f"{m['H']:.4f}/{m['Acc']:.2f} | {b['H']:.4f}/{b['Acc']:.2f} | "
            f"{swb['H']:.4f}/{swb['Acc']:.2f} |"
        )
    aasd = ext["AASD"]["selected"]
    carta = ext["Carta2026"]["selected"]
    d_hp = aasd["Acc"] - LINEAR_HP30_EXT["AASD"]["Acc"]
    d_sw2 = aasd["Acc"] - SW2_ALONE_EXT["AASD"]["Acc"]
    lines.append("\n## Targets\n")
    lines.append("| Target | Result |")
    lines.append("|---|---|")
    lines.append(
        f"| AASD Acc vs linear_hp30 53.12 / SW2 53.46 | Acc **{aasd['Acc']:.2f}** "
        f"(Δhp {d_hp:+.2f}; ΔSW2 {d_sw2:+.2f}); H {aasd['H']:.4f} |"
    )
    lines.append(
        f"| Carta vs linear_hp30 60.54 | Acc **{carta['Acc']:.2f}**; H {carta['H']:.4f} |"
    )
    lines.append(
        f"| LODO mean | H {sel['mean_LODO_H']:.4f} Acc {sel['mean_LODO_Acc']:.2f} |"
    )
    lines.append(f"| AASD Acc>60? | {'YES' if aasd['Acc'] > 60 else 'NO'} |\n")
    lines.append("## Verdict\n")
    if aasd["Acc"] > 60:
        lines.append("Selected Acc-stream×Acc-stream blend clears AASD Acc>60.\n")
    else:
        lines.append(
            "Honest LODO Acc/H selector on SW2↔swmix does not create AASD Acc>60. "
            "Mixing two mid-50s Acc streams stays in the mid-50s; Carta stays near ~60.\n"
        )
    lines.append("## NEXT IDEA\n")
    lines.append(
        "Do not re-grid SW2↔swmix soft/hard under LODO Acc/H. Prefer a **qualitatively new** "
        "frame-evidence Acc path (front-end that clears chance and lifts AASD acc1), not another "
        "Acc-stream×Acc-stream blend of published SW2 / synth-switch clf. Keep SW2 Acc 53.46 and "
        "`linear_hp30` Carta 60.54 as portfolio leaders.\n"
    )
    with open(RESULTS_MD, "w") as fh:
        fh.write("\n".join(lines))


def main():
    os.makedirs(CACHE_DIR, exist_ok=True)
    os.makedirs(os.path.dirname(LOG), exist_ok=True)
    os.makedirs(os.path.dirname(OUT), exist_ok=True)
    open(LOG, "w").close()
    t_all = time.time()
    log_line(
        f"sw2-swmix-blend start  p_stay={P_STAY} scale={SCALE} a_sw2={A_SW2} OFF={OFF}"
    )

    try:
        Z, meta = ensure_sw2_lodo()
        swmix_full, la_sm = ensure_swmix_lodo()
        log_line(f"lookahead LA={LOOKAHEAD} swmix_fold_la={la_sm}")
    except FileNotFoundError as e:
        log_line(f"ABORT: {e}")
        summary = dict(
            status="abandoned",
            reason=str(e),
            next_idea=(
                "Restore SW2 caches / swmix folds; do not rebuild decoder LODO for a blend."
            ),
        )
        with open(OUT, "w") as fh:
            json.dump(summary, fh, indent=2)
        write_md_abandon(str(e))
        return

    # sanity: pure SW2 and pure swmix on AVGC
    sw2_avgc = fuse_sw2_held(Z, "AVGC")
    sm_a = align_swmix_to_sw2(swmix_full, sw2_avgc)
    r_sw2 = score_lodo_held(sw2_avgc, meta, "AVGC")
    r_sm = score_lodo_held(sm_a, meta, "AVGC")
    log_line(
        f"sanity AVGC sw2 H {r_sw2['H']:.4f} Acc {r_sw2['Acc']:.2f} "
        f"(expect ~0.71 Acc~68 @0.994/0.8)"
    )
    log_line(
        f"sanity AVGC swmix-aligned H {r_sm['H']:.4f} Acc {r_sm['Acc']:.2f} "
        f"(technique reported 0.6965/65.70)"
    )

    rules = candidate_rules()
    log_line(f"scoring {len(rules)} rules on mean LODO Acc then H")
    rows = []
    best = None
    for kind, thr, sharp in rules:
        t0 = time.time()
        mean_h, mean_a, per = mean_lodo_for_rule(Z, meta, swmix_full, kind, thr, sharp)
        key = rule_key(kind, thr, sharp)
        row = dict(
            kind=kind,
            thresh=thr,
            sharp=sharp,
            key=key,
            mean_LODO_H=mean_h,
            mean_LODO_Acc=mean_a,
            per_ds=per,
        )
        rows.append(row)
        log_line(
            f"  LODO {key:32s} H {mean_h:.4f} Acc {mean_a:.2f} ({time.time() - t0:.0f}s)"
        )
        sel = (mean_a, mean_h)
        if best is None or sel > best[0]:
            best = (sel, row)

    selected = best[1]
    log_line(
        f"SELECTED {selected['key']} mean LODO H {selected['mean_LODO_H']:.4f} "
        f"Acc {selected['mean_LODO_Acc']:.2f}"
    )

    try:
        EV_sw2, emis_sw2 = ensure_sw2_external()
        sm_ext = ensure_swmix_external()
    except FileNotFoundError as e:
        log_line(f"ABORT external: {e}")
        summary = dict(
            status="partial",
            selected=selected,
            lodo_rows=rows,
            reason=str(e),
            next_idea="Restore swmix external evidence pickles under results/research/.",
        )
        with open(OUT, "w") as fh:
            json.dump(summary, fh, indent=2, default=_json_default)
        write_md_partial(selected, rows, str(e))
        return

    kind, thr, sharp = selected["kind"], selected["thresh"], selected["sharp"]
    mu_c, sd_c = corpus_emis_for_blend(Z, meta, swmix_full, kind, thr, sharp)
    log_line(f"corpus blend emis mu={mu_c:.4f} sd={sd_c:.4f}")

    # swmix-only corpus emissions (aligned average of held SW2-meta streams)
    mu_sm, sd_sm = corpus_emis_for_blend(Z, meta, swmix_full, "const_swmix", 0.0, 1.0)
    log_line(f"corpus swmix emis mu={mu_sm:.4f} sd={sd_sm:.4f}")

    ext_rows = {}
    for ds in ("AASD", "Carta2026"):
        sw2_ev = EV_sw2[ds][A_SW2]
        sm_al = align_ext_swmix_to_sw2(sm_ext[ds], sw2_ev)
        blended = blend_ext_ev(sw2_ev, sm_al, kind, thr, sharp)
        sm_only = _swmix_as_ev(sm_ext[ds], sm_ext[ds + "__meta"], off_align_to=sw2_ev)
        for tag, ev_use, mu, sd in (
            ("selected", blended, mu_c, sd_c),
            ("sw2_only", sw2_ev, emis_sw2[A_SW2][0], emis_sw2[A_SW2][1]),
            ("swmix_only", sm_only, mu_sm, sd_sm),
        ):
            r = E.score(ev_use, mu, sd * SCALE, P_STAY, LOOKAHEAD)
            pl = E.plain(ev_use)
            ext_rows.setdefault(ds, {})[tag] = dict(
                H=r["H"],
                Acc=r["Acc"],
                SDT=r["SDT"],
                L=r["L"],
                acc1=pl["acc1"],
                nSwitches=r["nSwitches"],
                nUndetected=r["nUndetected"],
            )
            ref = LINEAR_HP30_EXT[ds]["Acc"]
            log_line(
                f"EXT {ds} {tag:10s} H {r['H']:.4f} Acc {r['Acc']:.2f} "
                f"(hp30 {ref:.2f}; SW2 {SW2_ALONE_EXT[ds]['Acc']:.2f}; "
                f"swmix {SWMIX_ALONE_EXT[ds]['Acc']:.2f})"
            )

    summary = dict(
        status="done",
        method="sw2-swmix-blend",
        selected=selected,
        p_stay=P_STAY,
        scale=SCALE,
        a_sw2=A_SW2,
        OFF=OFF,
        lodo_grid=rows,
        external=ext_rows,
        baselines=dict(
            linear_hp30_ext=LINEAR_HP30_EXT,
            sw2_alone_ext=SW2_ALONE_EXT,
            swmix_alone_ext=SWMIX_ALONE_EXT,
        ),
        elapsed_s=time.time() - t_all,
    )
    with open(OUT, "w") as fh:
        json.dump(summary, fh, indent=2, default=_json_default)
    write_md(summary)
    log_line(f"done in {time.time() - t_all:.0f}s → {OUT}")


if __name__ == "__main__":
    main()
