"""Soft/hard **3-way** Acc-stream blend: SW2 fuse ↔ swmix clf ↔ linear_hp30.

Acc-relevant streams (reuse prior caches; no retrain):
  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 = technique-synth-switch clf (direct_clf … aug-sw2_swmix)
          (partner in SW2↔swmix leader AASD Acc 53.53)
  hp30  = causal τ=30 high-pass of mean of the same 4 clf seeds (AASD 53.12, Carta 60.54)

DISTINCT from pairwise SW2↔swmix, SW2↔hp30, TRF↔SW2, SW2-as-5th.

Grid: simplex weights (w_sw2, w_swmix, w_hp30) sum=1 on {0,0.25,0.5,0.75,1}
      sparse corners + a few interior points; plus causal |stream| gates favoring Acc streams.
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.

Reuse loaders from sw2_swmix_blend.py / sw2_hp30_blend.py.

usage:
  /root/disk_3tb/EEG-sAAD-Grand-Challenge-Training-Dataset/.venv/bin/python -u tri_acc_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, softmax

import ensemble_clf as EC
import ensemble_clf_nested as N
import ensemble_clf_transformer_v4 as V4
import eval_external as E
import sw2_hp30_blend as SW2
import sw2_swmix_blend as SM
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", "tri_acc_blend", "cache")
LOG = os.path.join(EXP, "experiments", "tri_acc_blend.log")
OUT = os.path.join(EXP, "results", "research", "tri_acc_blend.json")
RESULTS_MD = os.path.join(EXP, "multi_agent_opt", "results_tri_acc_blend.md")

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))
SW2_SWMIX_LEADER = dict(AASD=dict(H=0.6424, Acc=53.53), Carta2026=dict(H=0.6460, Acc=59.71))


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 _on_grid(x, tol=1e-9):
    """True if x is (near) a multiple of 0.25 in [0,1]."""
    if x < -tol or x > 1.0 + tol:
        return False
    q = round(x * 4.0) / 4.0
    return abs(x - q) < tol


def simplex_weights():
    """Sparse simplex on {0,0.25,0.5,0.75,1}^3 sum=1 + a few interiors."""
    pts = []
    vals = (0.0, 0.25, 0.5, 0.75, 1.0)
    for a in vals:
        for b in vals:
            c = 1.0 - a - b
            if _on_grid(c):
                pts.append((round(a, 4), round(b, 4), round(c, 4)))
    # explicit interiors not forced by the 0.25 lattice alone
    extras = [
        (1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0),
        (0.5, 0.25, 0.25),
        (0.25, 0.5, 0.25),
        (0.25, 0.25, 0.5),
        (0.6, 0.2, 0.2),
        (0.4, 0.4, 0.2),
        (0.4, 0.2, 0.4),
        (0.2, 0.4, 0.4),
    ]
    for p in extras:
        pts.append(tuple(round(x, 6) for x in p))
    # dedupe
    seen, out = set(), []
    for p in pts:
        key = tuple(round(x, 6) for x in p)
        if key in seen:
            continue
        if abs(sum(key) - 1.0) > 1e-6:
            continue
        seen.add(key)
        out.append(key)
    return out


def gate_weights(sw2, swmix, hp30, kind, thresh, sharp, ewma_tau=4.0):
    """Return (w_sw2, w_swmix, w_hp30) arrays length n summing to 1 per frame.

    Soft simplex uses thresh as unused; kind encodes weights via rule params elsewhere.
    Causal |stream| gates favor the Acc stream with larger |logit|.
    """
    f = np.asarray(sw2, np.float64)
    m = np.asarray(swmix, np.float64)
    h = np.asarray(hp30, np.float64)
    n = min(len(f), len(m), len(h))
    f, m, h = f[:n], m[:n], h[:n]
    ones = np.ones(n, np.float64)
    zeros = np.zeros(n, np.float64)

    if kind == "soft_w":
        # thresh unused; sharp unused — weights passed separately via apply path
        raise RuntimeError("soft_w handled outside gate_weights")

    if kind == "const_sw2":
        return ones, zeros, zeros
    if kind == "const_swmix":
        return zeros, ones, zeros
    if kind == "const_hp30":
        return zeros, zeros, ones

    af = np.abs(f)
    am = np.abs(m)
    ah = np.abs(h)

    if kind == "hard_abs_max":
        stack = np.stack([af, am, ah], axis=0)
        idx = np.argmax(stack, axis=0)
        w = np.zeros((3, n), np.float64)
        w[idx, np.arange(n)] = 1.0
        return w[0], w[1], w[2]

    if kind == "ewma_hard_abs_max":
        ef = ewma_1d(af, ewma_tau)
        em = ewma_1d(am, ewma_tau)
        eh = ewma_1d(ah, ewma_tau)
        stack = np.stack([ef, em, eh], axis=0)
        idx = np.argmax(stack, axis=0)
        w = np.zeros((3, n), np.float64)
        w[idx, np.arange(n)] = 1.0
        return w[0], w[1], w[2]

    if kind == "softmax_abs":
        # sharp = temperature inverse; thresh unused
        logits = sharp * np.stack([af, am, ah], axis=1)  # (n,3)
        w = softmax(logits, axis=1)
        return w[:, 0], w[:, 1], w[:, 2]

    if kind == "ewma_softmax_abs":
        ef = ewma_1d(af, ewma_tau)
        em = ewma_1d(am, ewma_tau)
        eh = ewma_1d(ah, ewma_tau)
        logits = sharp * np.stack([ef, em, eh], axis=1)
        w = softmax(logits, axis=1)
        return w[:, 0], w[:, 1], w[:, 2]

    if kind == "abs_sw2_vs_rest":
        # high |sw2| → trust sw2; else equal mix of swmix+hp30
        g = expit(sharp * (af - thresh))
        rest = 0.5 * (1.0 - g)
        return g, rest, rest

    if kind == "abs_hp30_vs_acc":
        # high |hp30| → trust hp30 (Carta Acc stream); else equal SW2+swmix
        g = expit(sharp * (ah - thresh))
        rest = 0.5 * (1.0 - g)
        return rest, rest, g

    if kind == "ewma_abs_sw2_vs_rest":
        g = expit(sharp * (ewma_1d(af, ewma_tau) - thresh))
        rest = 0.5 * (1.0 - g)
        return g, rest, rest

    if kind == "ewma_abs_hp30_vs_acc":
        g = expit(sharp * (ewma_1d(ah, ewma_tau) - thresh))
        rest = 0.5 * (1.0 - g)
        return rest, rest, g

    if kind == "acc_pair_then_hp30":
        # Soft Acc-pair (SW2 vs swmix by |·|), then blend with hp30 by |hp30| gate
        # g_acc: trust max(|sw2|,|swmix|) Acc pair vs hp30
        # inside Acc pair: softmax on |sw2|,|swmix|
        pair_logits = sharp * np.stack([af, am], axis=1)
        pair = softmax(pair_logits, axis=1)
        g_hp = expit(sharp * (ah - thresh))  # high |hp30| → more hp30
        w_s = (1.0 - g_hp) * pair[:, 0]
        w_m = (1.0 - g_hp) * pair[:, 1]
        w_h = g_hp
        return w_s, w_m, w_h

    raise ValueError(kind)


def blend_arrays(f, m, h, w_s, w_m, w_h):
    return (w_s * f + w_m * m + w_h * h).astype(np.float64)


def apply_gate_stream(sw2_st, sm_st, hp_st, kind, thresh, sharp, soft_w=None):
    out = {}
    for key in sw2_st:
        if key not in sm_st or key not in hp_st:
            continue
        f = np.asarray(sw2_st[key], np.float64)
        m = np.asarray(sm_st[key], np.float64)
        h = np.asarray(hp_st[key], np.float64)
        n = min(len(f), len(m), len(h))
        f, m, h = f[:n], m[:n], h[:n]
        if kind == "soft_w":
            ws, wm, wh = soft_w
            w_s = np.full(n, ws, np.float64)
            w_m = np.full(n, wm, np.float64)
            w_h = np.full(n, wh, np.float64)
        else:
            w_s, w_m, w_h = gate_weights(f, m, h, kind, thresh, sharp)
        out[key] = blend_arrays(f, m, h, w_s, w_m, w_h)
    return out


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


def candidate_rules():
    rules = []
    for w in simplex_weights():
        rules.append(("soft_w", w, 1.0))
    # causal |stream| gates favoring Acc streams
    rules += [
        ("const_sw2", 0.0, 1.0),
        ("const_swmix", 0.0, 1.0),
        ("const_hp30", 0.0, 1.0),
        ("hard_abs_max", 0.0, 1.0),
        ("ewma_hard_abs_max", 0.0, 1.0),
        ("softmax_abs", 0.0, 2.0),
        ("softmax_abs", 0.0, 4.0),
        ("softmax_abs", 0.0, 8.0),
        ("ewma_softmax_abs", 0.0, 2.0),
        ("ewma_softmax_abs", 0.0, 4.0),
        ("ewma_softmax_abs", 0.0, 8.0),
        ("abs_sw2_vs_rest", 0.5, 4.0),
        ("abs_sw2_vs_rest", 1.0, 4.0),
        ("abs_sw2_vs_rest", 1.5, 4.0),
        ("ewma_abs_sw2_vs_rest", 0.5, 4.0),
        ("ewma_abs_sw2_vs_rest", 1.0, 4.0),
        ("abs_hp30_vs_acc", 0.5, 4.0),
        ("abs_hp30_vs_acc", 1.0, 4.0),
        ("abs_hp30_vs_acc", 1.5, 4.0),
        ("ewma_abs_hp30_vs_acc", 0.5, 4.0),
        ("ewma_abs_hp30_vs_acc", 1.0, 4.0),
        ("acc_pair_then_hp30", 0.5, 4.0),
        ("acc_pair_then_hp30", 1.0, 4.0),
        ("acc_pair_then_hp30", 1.5, 4.0),
    ]
    return rules


def rule_key(kind, thr, sharp):
    if kind == "soft_w":
        ws, wm, wh = thr
        return f"soft_w=({ws:g},{wm:g},{wh: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_to_sw2(full, sw2, off=OFF):
    """Truncate/shift full-length stream to SW2 DEC_OFFSET alignment."""
    out = {}
    for ds in sw2:
        out[ds] = {}
        for k, f in sw2[ds].items():
            if k not in full[ds]:
                continue
            h = np.asarray(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 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, hp30_full, kind, thr, sharp):
    hs, acs, per = [], [], {}
    soft_w = thr if kind == "soft_w" else None
    for held in DS_KEYS:
        sw2 = fuse_sw2_held(Z, held)
        sm = align_to_sw2(swmix_full, sw2)
        hp = align_to_sw2(hp30_full, sw2)
        gated = apply_gate_all(sw2, sm, hp, kind, thr if kind != "soft_w" else 0.0, sharp, soft_w=soft_w)
        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 align_ext_to_sw2(stream, sw2_ev, off=OFF):
    out = {}
    for k, e in sw2_ev.items():
        if k not in stream:
            continue
        f = np.asarray(e["r0"], np.float64)
        h = np.asarray(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_al, hp_al, kind, thr, sharp, soft_w=None):
    out = {}
    for k, e in sw2_ev.items():
        if k not in sm_al or k not in hp_al:
            continue
        f = np.asarray(e["r0"], np.float64)
        m = np.asarray(sm_al[k], np.float64)
        h = np.asarray(hp_al[k], np.float64)
        n = min(len(f), len(m), len(h))
        f, m, h = f[:n], m[:n], h[:n]
        if kind == "soft_w":
            ws, wm, wh = soft_w
            w_s = np.full(n, ws, np.float64)
            w_m = np.full(n, wm, np.float64)
            w_h = np.full(n, wh, np.float64)
        else:
            w_s, w_m, w_h = gate_weights(f, m, h, kind, thr, sharp)
        d = blend_arrays(f, m, h, w_s, w_m, w_h)
        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, hp30_full, kind, thr, sharp, soft_w=None):
    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_to_sw2(swmix_full, sw2)
        hp = align_to_sw2(hp30_full, sw2)
        gated = apply_gate_all(
            sw2, sm, hp, kind, thr if kind != "soft_w" else 0.0, sharp, soft_w=soft_w
        )
        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 _json_default(o):
    if isinstance(o, (np.floating, np.integer)):
        return float(o)
    if isinstance(o, np.ndarray):
        return o.tolist()
    if isinstance(o, tuple):
        return list(o)
    raise TypeError(type(o))


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

**Status: abandoned**

Could not load SW2 / swmix / linear_hp30 evidence caches.

Reason:
```
{reason}
```

## NEXT IDEA

Restore caches under `models/sw2_hp30_blend/cache/` and `models/sw2_swmix_blend/cache/` before retrying. Do not retrain Acc streams for a blend experiment.
"""
    with open(RESULTS_MD, "w") as fh:
        fh.write(text)


def write_md_partial(selected, reason):
    with open(RESULTS_MD, "w") as fh:
        fh.write("# results_tri_acc_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_tri_acc_blend\n")
    lines.append(
        "Soft/hard **3-way** blend of Acc-relevant streams: "
        "**SW2 fuse** (README_BEST a=0.5; AASD Acc 53.46) × "
        "**technique-synth-switch / swmix** (partner in SW2↔swmix leader 53.53) × "
        "**linear_hp30** (4-seed τ=30; AASD 53.12, Carta 60.54), "
        f"aligned by `DEC_OFFSET={OFF}`. "
        "**Not** pairwise SW2↔swmix / SW2↔hp30 / TRF↔SW2 / SW2-as-5th.\n"
    )
    lines.append(
        f"HMM preset **{P_STAY} / {SCALE}**. Code: `tri_acc_blend.py`. "
        f"JSON: `results/research/tri_acc_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 simplex (reference; top Acc + corners)\n")
    lines.append("| Rule | mean H | mean Acc |")
    lines.append("|---|---:|---:|")
    soft = [r for r in summary["lodo_grid"] if r["kind"] == "soft_w"]
    soft_sorted = sorted(soft, key=lambda r: (-r["mean_LODO_Acc"], -r["mean_LODO_H"]))
    corner_keys = {
        "soft_w=(1,0,0)",
        "soft_w=(0,1,0)",
        "soft_w=(0,0,1)",
        "soft_w=(0.5,0.5,0)",
        "soft_w=(0.5,0,0.5)",
        "soft_w=(0,0.5,0.5)",
        "soft_w=(0.75,0.25,0)",
        "soft_w=(0.75,0,0.25)",
        "soft_w=(0.5,0.25,0.25)",
    }
    shown = set()
    for r in soft_sorted[:8] + [r for r in soft if r["key"] in corner_keys]:
        if r["key"] in shown:
            continue
        shown.add(r["key"])
        mark = " **←**" if r["key"] == sel["key"] else ""
        lines.append(
            f"| `{r['key']}`{mark} | {r['mean_LODO_H']:.4f} | {r['mean_LODO_Acc']:.2f} |"
        )
    if sel["key"] not in shown:
        lines.append(
            f"| `{sel['key']}` **←** | {sel['mean_LODO_H']:.4f} | {sel['mean_LODO_Acc']:.2f} |"
        )
    lines.append("\n## External (preset)\n")
    lines.append(
        "| Set | selected H/Acc | sw2_only | swmix_only | hp30_only | SW2↔swmix 53.53 | linear_hp30 |"
    )
    lines.append("|---|---|---|---|---|---|---|")
    for ds in ("AASD", "Carta2026"):
        s = ext[ds]["selected"]
        w = ext[ds]["sw2_only"]
        m = ext[ds]["swmix_only"]
        h = ext[ds]["hp30_only"]
        lead = SW2_SWMIX_LEADER[ds]
        b = LINEAR_HP30_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} | {h['H']:.4f}/{h['Acc']:.2f} | "
            f"{lead['H']:.4f}/{lead['Acc']:.2f} | {b['H']:.4f}/{b['Acc']:.2f} |"
        )
    aasd = ext["AASD"]["selected"]
    carta = ext["Carta2026"]["selected"]
    d_lead = aasd["Acc"] - SW2_SWMIX_LEADER["AASD"]["Acc"]
    d_hp = aasd["Acc"] - LINEAR_HP30_EXT["AASD"]["Acc"]
    d_carta = carta["Acc"] - LINEAR_HP30_EXT["Carta2026"]["Acc"]
    lines.append("\n## Targets\n")
    lines.append("| Target | Result |")
    lines.append("|---|---|")
    lines.append(
        f"| AASD Acc vs SW2↔swmix 53.53 / hp30 53.12 | Acc **{aasd['Acc']:.2f}** "
        f"(Δlead {d_lead:+.2f}; Δhp {d_hp:+.2f}); H {aasd['H']:.4f} |"
    )
    lines.append(
        f"| Carta vs linear_hp30 60.54 | Acc **{carta['Acc']:.2f}** "
        f"(Δ {d_carta:+.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 3-way Acc blend clears AASD Acc>60.\n")
    else:
        lines.append(
            "Honest LODO Acc/H selector on SW2×swmix×hp30 does not create AASD Acc>60. "
            "3-way Acc-stream mixing stays in the mid-50s; Carta stays near ~60.\n"
        )
    lines.append("## NEXT IDEA\n")
    lines.append(
        "Do not re-grid 3-way SW2↔swmix↔hp30 soft/hard under LODO Acc/H. Prefer a "
        "**qualitatively new** frame-evidence Acc path (front-end that clears chance and "
        "lifts AASD acc1) — e.g. decoder-sw3 denser-switch decoder — not another Acc-stream "
        "blend. Keep SW2↔swmix Acc 53.53 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"tri-acc-blend start  p_stay={P_STAY} scale={SCALE} a_sw2={A_SW2} OFF={OFF}"
    )

    try:
        Z, meta = SM.ensure_sw2_lodo()
        swmix_full, la_sm = SM.ensure_swmix_lodo()
        hp30_full, _mean4, la_hp = SW2.ensure_hp30_lodo()
        log_line(f"lookahead LA={LOOKAHEAD} swmix_fold_la={la_sm} hp30_la={la_hp}")
    except FileNotFoundError as e:
        log_line(f"ABORT: {e}")
        summary = dict(
            status="abandoned",
            reason=str(e),
            next_idea="Restore SW2/swmix/hp30 caches; 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 AVGC parents
    sw2_avgc = fuse_sw2_held(Z, "AVGC")
    sm_a = align_to_sw2(swmix_full, sw2_avgc)
    hp_a = align_to_sw2(hp30_full, sw2_avgc)
    r_sw2 = score_lodo_held(sw2_avgc, meta, "AVGC")
    r_sm = score_lodo_held(sm_a, 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.71 Acc~68 @0.994/0.8)"
    )
    log_line(
        f"sanity AVGC swmix-aligned H {r_sm['H']:.4f} Acc {r_sm['Acc']:.2f}"
    )
    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, swmix_full, hp30_full, kind, thr, sharp
        )
        key = rule_key(kind, thr, sharp)
        row = dict(
            kind=kind,
            thresh=thr if kind != "soft_w" else list(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:40s} 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 = SM.ensure_sw2_external()
        sm_ext = SM.ensure_swmix_external()
        corp_hp, ext_hp, train_att, test_meta = SW2.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 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, str(e))
        return

    kind = selected["kind"]
    thr = tuple(selected["thresh"]) if kind == "soft_w" else selected["thresh"]
    sharp = selected["sharp"]
    soft_w = thr if kind == "soft_w" else None
    mu_c, sd_c = corpus_emis_for_blend(
        Z, meta, swmix_full, hp30_full, kind, thr if kind != "soft_w" else 0.0, sharp, soft_w=soft_w
    )
    log_line(f"corpus blend emis mu={mu_c:.4f} sd={sd_c:.4f}")

    mu_sm, sd_sm = corpus_emis_for_blend(
        Z, meta, swmix_full, hp30_full, "const_swmix", 0.0, 1.0
    )
    mu_hp, sd_hp = V4.emissions(
        {d: corp_hp[d] for d in V4.CORPUS},
        {d: train_att[d] for d in V4.CORPUS},
    )
    log_line(f"corpus swmix emis mu={mu_sm:.4f} sd={sd_sm:.4f}")
    log_line(f"corpus hp30 emis mu={mu_hp:.4f} sd={sd_hp:.4f}")

    ext_rows = {}
    for ds in ("AASD", "Carta2026"):
        sw2_ev = EV_sw2[ds][A_SW2]
        sm_al = align_ext_to_sw2(sm_ext[ds], sw2_ev)
        hp_al = align_ext_to_sw2(ext_hp[ds], sw2_ev)
        blended = blend_ext_ev(sw2_ev, sm_al, hp_al, kind, thr if kind != "soft_w" else 0.0, sharp, soft_w=soft_w)
        sm_only = SM._swmix_as_ev(sm_ext[ds], sm_ext[ds + "__meta"], off_align_to=sw2_ev)
        hp_only = SW2._hp_as_ev(ext_hp[ds], test_meta[ds], 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),
            ("hp30_only", hp_only, mu_hp, sd_hp),
        ):
            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"]
            lead = SW2_SWMIX_LEADER[ds]["Acc"]
            log_line(
                f"EXT {ds} {tag:10s} H {r['H']:.4f} Acc {r['Acc']:.2f} "
                f"(hp30 {ref:.2f}; lead53.53={lead:.2f}; SW2 {SW2_ALONE_EXT[ds]['Acc']:.2f})"
            )

    summary = dict(
        status="done",
        method="tri-acc-blend",
        selected=selected,
        p_stay=P_STAY,
        scale=SCALE,
        a_sw2=A_SW2,
        OFF=OFF,
        n_rules=len(rows),
        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,
            sw2_swmix_leader=SW2_SWMIX_LEADER,
        ),
        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()
