"""Soft/hard blend: published SW2 decoder+clf fuse evidence ↔ linear_hp30.

NOT IRM↔SWA stem fuse↔hp30 (exhausted → const_fuse). This blends:
  sw2   = README_BEST legal stack: 4 decoder + 4 clf10(sw2) via fuse_general a=0.5
  hp30  = causal τ=30 high-pass of mean of the same 4 clf seeds, aligned by DEC_OFFSET

Grid: soft w∈{0,0.25,0.5,0.75,1} and causal gates on |sw2| / |sw2−hp30|.
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.

Evidence only from existing folds / fuse_external pickles — no decoder retrain.

usage:
  /root/disk_3tb/EEG-sAAD-Grand-Challenge-Training-Dataset/.venv/bin/python -u sw2_hp30_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_nested as N
import ensemble_clf_transformer_v4 as V4
import eval_external as E
import fuse_external as FE
import fuse_general as FG
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_hp30_blend", "cache")
LOG = os.path.join(EXP, "experiments", "sw2_hp30_blend.log")
OUT = os.path.join(EXP, "results", "research", "sw2_hp30_blend.json")
RESULTS_MD = os.path.join(EXP, "multi_agent_opt", "results_sw2_hp30_blend.md")

P_STAY = 0.994
SCALE = 0.8
LOOKAHEAD = float(LA)
A_SW2 = 0.5  # README_BEST published mix

DECS = [
    "vlaai_ws__eaP_n5_t60_aug_cluster_onset_dom_xFUG_ptSPK",
    "vlaai_ws__eaP_n5_t60_aug_cluster_onset_dom_xFUG_ptSPK_s1",
    "vlaai_ws__eaP_n5_t60_aug_cluster_onset_dom_xFUG_ptSPK_s2",
    "vlaai_ws__eaP_n5_t60_aug_cluster_onset_dom_xFUG_ptSPK_s3",
]
CLFS = [
    "direct_clf__eaP_n5_t60_w10b3_ptSPK_aug-sw2",
    "direct_clf__eaP_n5_t60_w10b3_ptSPK_s1_aug-sw2",
    "direct_clf__eaP_n5_t60_w10b3_ptSPK_s2_aug-sw2",
    "direct_clf__eaP_n5_t60_w10b3_ptSPK_s3_aug-sw2",
]

# fuse_external CLI naming (corpus_exp:seed) / (corpus_exp:ext_tag:seed)
EXT_DECS = [f"{d}:{i}" for i, d in enumerate(DECS)]
EXT_CLFS = [
    f"{c}:_w10b3sw2P:{i}" for i, c in enumerate(CLFS)
]

LINEAR_HP30_EXT = dict(AASD=dict(H=0.6422, Acc=53.12), Carta2026=dict(H=0.6520, Acc=60.54))
LINEAR_HP30_LODO = dict(H=0.7899, Acc=69.21)


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, hp30, kind, thresh, sharp, ewma_tau=4.0):
    """g∈[0,1]; high g → trust sw2."""
    f = np.asarray(sw2, np.float64)
    h = np.asarray(hp30, np.float64)
    n = min(len(f), len(h))
    f, h = f[:n], h[:n]
    if kind == "soft_w":
        # thresh stores w; sharp unused
        w = float(thresh)
        return np.full(n, w, np.float64)
    if kind == "const_sw2":
        return np.ones(n, np.float64)
    if kind == "const_hp30":
        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 == "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 == "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, hp_st, kind, thresh, sharp):
    out = {}
    for key in sw2_st:
        if key not in hp_st:
            continue
        f = np.asarray(sw2_st[key], np.float64)
        h = np.asarray(hp_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, hp_all, kind, thresh, sharp):
    return {ds: apply_gate_stream(sw2_all[ds], hp_all[ds], kind, thresh, sharp)
            for ds in sw2_all if ds in hp_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_hp30", 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),
        ("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),
        ("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 {ds: {key: 1d}} fused SW2 evidence for this held-out weight fit."""
    zd, zc = Z[held]
    out = {}
    for ds in DS_KEYS:
        out[ds] = {k: (1.0 - a) * zd[ds][k] + a * zc[ds][k] for k in zd[ds]}
    return out


def align_hp30_to_sw2(hp30_full, sw2, off=OFF):
    """Truncate/shift hp30 to match SW2 DEC_OFFSET alignment (same EEG budget)."""
    out = {}
    for ds in sw2:
        out[ds] = {}
        for k, f in sw2[ds].items():
            if k not in hp30_full[ds]:
                continue
            h = np.asarray(hp30_full[ds][k], np.float64)
            n = len(f)
            if len(h) < off + n:
                # rare: take what we can from the end-aligned slice
                sl = h[off:off + n]
                if len(sl) < n:
                    pad = np.zeros(n, np.float64)
                    pad[: len(sl)] = sl
                    out[ds][k] = pad
                else:
                    out[ds][k] = sl
            else:
                out[ds][k] = h[off:off + n].copy()
    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(CACHE_DIR, "sw2_lodo_Z_meta.pkl")
    if os.path.isfile(path):
        log_line(f"cache hit {path}")
        return load_pkl(path)
    log_line("building SW2 fuse_general Z, meta (4 dec × 4 clf) …")
    t0 = time.time()
    # Abort honestly if any fold is missing
    missing = []
    for name in DECS + CLFS:
        for ds in DS_KEYS:
            from common_exp import fold_file
            p = fold_file(name, ds)
            if not os.path.exists(p):
                missing.append(p)
    if missing:
        raise FileNotFoundError(
            "SW2 evidence folds missing (abort; do not reinvent decoder stack):\n"
            + "\n".join(missing[:12])
        )
    Z, meta = FG.build(DECS, CLFS)
    save_pkl(path, (Z, meta))
    log_line(f"SW2 LODO cache wrote ({time.time() - t0:.0f}s)")
    return Z, meta


def ensure_hp30_lodo():
    path = os.path.join(CACHE_DIR, "linear_hp30_lodo.pkl")
    if os.path.isfile(path):
        log_line(f"cache hit {path}")
        return load_pkl(path)
    log_line("loading linear_hp30 from 4-seed folds …")
    mean_ev, hp_ev, lookahead = V4._mean_and_hp_from_folds()
    hp = {ds: {k: e["r0"] for k, e in hp_ev[ds].items()} for ds in DS_KEYS}
    mean = {ds: {k: e["r0"] for k, e in mean_ev[ds].items()} for ds in DS_KEYS}
    save_pkl(path, (hp, mean, lookahead))
    return hp, mean, lookahead


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, hp30_full, kind, thr, sharp):
    hs, acs, per = [], [], {}
    for held in DS_KEYS:
        sw2 = fuse_sw2_held(Z, held)
        hp = align_hp30_to_sw2(hp30_full, sw2)
        gated = apply_gate_all(sw2, hp, 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(CACHE_DIR, "sw2_external_a05.pkl")
    if os.path.isfile(path):
        log_line(f"cache hit {path}")
        return load_pkl(path)
    log_line("building SW2 external fuse (a=0.5, dec-tag _bestP) …")
    t0 = time.time()
    decs = [x.split(":") for x in EXT_DECS]
    clfs = [x.split(":") for x in EXT_CLFS]
    # Verify external evidence pickles exist
    res = FE.RES
    missing = []
    for d in decs:
        for ds_tag in ("aasd_c1_bestP", "ext_c1_Carta2026_bestP"):
            p = os.path.join(res, f"{ds_tag}_evidence_s{d[1]}.pkl")
            if not os.path.exists(p):
                missing.append(p)
    for c in clfs:
        for ds in ("AASD", "Carta2026"):
            p = os.path.join(res, f"ext_clf_{ds}{c[1]}_evidence_s{c[2]}.pkl")
            if not os.path.exists(p):
                missing.append(p)
    if missing:
        raise FileNotFoundError(
            "SW2 external evidence pickles missing (abort):\n" + "\n".join(missing[:12])
        )
    EV, emis = FE.build_external(decs, clfs, [A_SW2], ["AASD", "Carta2026"], "_bestP")
    # Also keep corpus fused stream for emissions at preset HMM (rebuild via emis dict)
    save_pkl(path, (EV, emis))
    log_line(f"SW2 external cache wrote ({time.time() - t0:.0f}s)")
    return EV, emis


def ensure_hp30_external():
    path = os.path.join(CACHE_DIR, "linear_hp30_external.pkl")
    if os.path.isfile(path):
        log_line(f"cache hit {path}")
        return load_pkl(path)
    log_line("loading linear_hp30 external (V4 4-seed) …")
    train_logits, train_att = V4.load_train()
    test_logits, test_meta = V4.load_test()
    base = {}
    base.update(train_logits)
    base.update(test_logits)
    streams = V4.linear_streams(base, "hp30")
    corp = {ds: streams[ds] for ds in V4.CORPUS}
    ext = {ds: streams[ds] for ds in V4.TEST_NAMES}
    save_pkl(path, (corp, ext, train_att, test_meta))
    return corp, ext, train_att, test_meta


def align_ext_hp_to_sw2(hp_stream, sw2_ev, off=OFF):
    """sw2_ev is {key: evidence dict with r0}; return {key: aligned hp array}."""
    out = {}
    for k, e in sw2_ev.items():
        if k not in hp_stream:
            continue
        f = np.asarray(e["r0"], np.float64)
        h = np.asarray(hp_stream[k], np.float64)
        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, hp_aligned, kind, thr, sharp):
    out = {}
    for k, e in sw2_ev.items():
        if k not in hp_aligned:
            continue
        f = np.asarray(e["r0"], np.float64)
        h = np.asarray(hp_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, hp30_full, kind, thr, sharp):
    """Emissions from all-5 corpus under LODO-style weights averaged? Use held-agnostic:
    fit SW2 weights leaving none out = use average of 5 held fits on train pool.
    Simpler honest approach matching fuse_external: use FE emis at a=0.5 for pure sw2,
    and for blends recompute signed mean/std on corpus blended streams from one
    all-train SW2 build.

    We rebuild corpus SW2 via fuse_external emis path: the FE emis[a] already stores
    (mu, sd) for pure SW2. For blends, fit mu/sd on aligned corpus streams using
    LODO fold evidence with weights from 'pseudo held' that uses all 5 as train —
    approximate by mean of the five held-specific corpus streams on each trial.
    """
    # Mean over held-specific SW2 streams (each is valid OOF on 4/5; averaging is soft)
    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)
        hp = align_hp30_to_sw2(hp30_full, sw2)
        gated = apply_gate_all(sw2, hp, 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]}
    # signed emissions on corpus
    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 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-hp30-blend start  p_stay={P_STAY} scale={SCALE} a_sw2={A_SW2} OFF={OFF}")

    try:
        Z, meta = ensure_sw2_lodo()
        hp30_full, _mean4, lookahead = ensure_hp30_lodo()
        log_line(f"lookahead folds={lookahead} LA={LOOKAHEAD}")
    except FileNotFoundError as e:
        log_line(f"ABORT: {e}")
        summary = dict(status="abandoned", reason=str(e), next_idea=(
            "Use already-cached IRM↔SWA fuse↔hp30 MoE runners, or a new non-stem Acc path "
            "(keep linear_hp30); do not rebuild decoder LODO folds from scratch."
        ))
        with open(OUT, "w") as fh:
            json.dump(summary, fh, indent=2)
        write_md_abandon(str(e))
        return

    # sanity: pure SW2 and pure hp30 on AVGC
    sw2_avgc = fuse_sw2_held(Z, "AVGC")
    hp_a = align_hp30_to_sw2(hp30_full, sw2_avgc)
    r_sw2 = score_lodo_held(sw2_avgc, meta, "AVGC")
    r_hp = score_lodo_held(hp_a, meta, "AVGC")
    log_line(f"sanity AVGC sw2 H {r_sw2['H']:.4f} Acc {r_sw2['Acc']:.2f} "
             f"(expect ~0.73–0.80 @0.994/0.8; published H~0.726 @0.998)")
    log_line(f"sanity AVGC hp30-aligned H {r_hp['H']:.4f} Acc {r_hp['Acc']:.2f}")

    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, hp30_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:28s} 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}")

    # External
    try:
        EV_sw2, emis_sw2 = ensure_sw2_external()
        corp_hp, ext_hp, train_att, test_meta = ensure_hp30_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 fuse_external SW2 evidence pickles under decoder_lodo/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, hp30_full, kind, thr, sharp)
    log_line(f"corpus blend emis mu={mu_c:.4f} sd={sd_c:.4f}")

    ext_rows = {}
    for ds in ("AASD", "Carta2026"):
        sw2_ev = EV_sw2[ds][A_SW2]
        hp_al = align_ext_hp_to_sw2(ext_hp[ds], sw2_ev)
        blended = blend_ext_ev(sw2_ev, hp_al, kind, thr, sharp)
        # also score pure parents for reference
        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]),
            ("hp30_only", _hp_as_ev(ext_hp[ds], test_meta[ds], off_align_to=sw2_ev),
             *V4.emissions({d: corp_hp[d] for d in V4.CORPUS},
                           {d: train_att[d] for d in V4.CORPUS})),
        ):
            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"],
            )
            log_line(f"EXT {ds} {tag:10s} H {r['H']:.4f} Acc {r['Acc']:.2f} "
                     f"(linear_hp30 {LINEAR_HP30_EXT[ds]['Acc']:.2f})")

    summary = dict(
        status="done",
        method="sw2-hp30-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, linear_hp30_lodo=LINEAR_HP30_LODO),
        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}")


def _hp_as_ev(hp_stream, meta, off_align_to=None):
    """Pack hp30 into external evidence dict; optionally align length to SW2 trials."""
    out = {}
    for k, h0 in hp_stream.items():
        h = np.asarray(h0, np.float64)
        m = 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)]
        else:
            att = m["att"][: len(h)]
            te = m["t_end"][: len(h)]
        out[k] = dict(
            r0=h, r1=np.zeros(len(h)), att=att, t_end=te,
            att128=m["att128"], n128=m["n128"], subject=m["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_hp30_blend

**Status: abandoned**

Could not load published SW2 fusion evidence streams without reinventing the decoder stack.

Reason:
```
{reason}
```

## NEXT IDEA

Prefer a non-stem Acc path that already has caches (keep `linear_hp30` as AASD leader), or restore/symlink SW2 fold pickles under `folds/` + `fuse_external` evidence under `results/research/` before retrying this blend. Do not retrain the 4× decoder + 4× clf LODO stack 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_hp30_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_hp30_blend\n")
    lines.append(
        "Soft/hard blend of **published SW2 decoder+classifier fuse** (README_BEST, `fuse_general` a=0.5) "
        "with **linear_hp30** (4-seed τ=30 HP), aligned by `DEC_OFFSET=3`. "
        "**Not** IRM↔SWA stem fuse↔hp30.\n"
    )
    lines.append(f"HMM preset **{P_STAY} / {SCALE}**. Code: `sw2_hp30_blend.py`. "
                 f"JSON: `results/research/sw2_hp30_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 | hp30_only | linear_hp30 baseline |")
    lines.append("|---|---|---|---|---|")
    for ds in ("AASD", "Carta2026"):
        s = ext[ds]["selected"]
        w = ext[ds]["sw2_only"]
        h = ext[ds]["hp30_only"]
        b = LINEAR_HP30_EXT[ds]
        lines.append(
            f"| {ds} | {s['H']:.4f} / **{s['Acc']:.2f}** | {w['H']:.4f}/{w['Acc']:.2f} | "
            f"{h['H']:.4f}/{h['Acc']:.2f} | {b['H']:.4f}/{b['Acc']:.2f} |"
        )
    aasd = ext["AASD"]["selected"]
    carta = ext["Carta2026"]["selected"]
    d_aasd = aasd["Acc"] - LINEAR_HP30_EXT["AASD"]["Acc"]
    lines.append("\n## Targets\n")
    lines.append("| Target | Result |")
    lines.append("|---|---|")
    lines.append(f"| AASD Acc vs linear_hp30 53.12 | Acc **{aasd['Acc']:.2f}** (Δ {d_aasd:+.2f}); "
                 f"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} |\n")
    lines.append("## Verdict\n")
    if aasd["Acc"] > 53.12 + 0.2 and aasd["H"] > 0.63:
        lines.append("Selected blend improves AASD Acc vs linear_hp30 with H>0.63.\n")
    else:
        lines.append(
            "Honest selector on LODO Acc/H does not import linear_hp30's external Acc into the "
            "SW2 fuse stream (or selects near-hp30 and loses LODO). Same qualitative failure mode "
            "as IRM↔SWA↔hp30 MoE, on a **different** SW2 evidence stack.\n"
        )
    lines.append("## NEXT IDEA\n")
    lines.append(
        "Stop soft/hard SW2↔hp30 blends selected by LODO Acc/H. Prefer a train-time change that "
        "reshapes AASD evidence (new front-end / denser real-switch proxy already in flight), "
        "or keep `linear_hp30` as the AASD Acc leader without mixing in SW2 fuse.\n"
    )
    with open(RESULTS_MD, "w") as fh:
        fh.write("\n".join(lines))


if __name__ == "__main__":
    main()
