"""Domain emission-LL gate: Acc tip hard_abs_swmix|t1 ↔ linear_hp30.

DISTINCT from domain_emis_ll (IRM↔SWA fuse ↔ hp30) and Acc soft/hard w re-grids
(sw2-hp30, tri-acc, sw2-swmix) and online-moment-sw2.

Streams (frozen, CPU caches):
  tip  = hard_abs_swmix|t1 from sw2_swmix_blend (AASD Acc 53.53)
  hp30 = linear_hp30 4-seed, DEC_OFFSET-aligned to tip/SW2 (Carta Acc 60.54)

Method:
  1. Fit Gaussian emissions (μ,σ) on LODO train folds only, per stream
     (2-state ±μ mixture and/or IID on raw logit).
  2. Causal frame LL under each stream's train emissions (no test labels).
  3. Gate g = sigmoid(T·EWMA/raw(LL_tip−LL_hp30)) or hard cum/EWMA pick.
     Evidence = g·tip + (1−g)·hp30.
  4. Select kind/temp/τ/emis family on mean LODO Acc then H @0.994/0.8
     (never AASD/Carta labels).
  5. Score LODO5 + AASD + Carta.

usage:
  PYTHONPATH=.../reports/eda_full/scripts:$PYTHONPATH \\
    /root/disk_3tb/EEG-sAAD-Grand-Challenge-Training-Dataset/.venv/bin/python -u domain_emis_acc_tip.py
"""
from __future__ import annotations

import json
import os
import time

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

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__))
LOG = os.path.join(EXP, "experiments", "domain_emis_acc_tip.log")
OUT = os.path.join(EXP, "results", "research", "domain_emis_acc_tip.json")
RESULTS_MD = os.path.join(EXP, "multi_agent_opt", "results_domain_emis_acc_tip.md")

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

TIP_KIND, TIP_THR, TIP_SHARP = "hard_abs_swmix", 1.0, 1.0

LINEAR_HP30_EXT = dict(AASD=dict(H=0.6422, Acc=53.12), Carta2026=dict(H=0.6520, Acc=60.54))
TIP_EXT = dict(AASD=dict(H=0.6424, Acc=53.53), Carta2026=dict(H=0.6460, Acc=59.71))
SW2_ALONE_EXT = dict(AASD=dict(H=0.6439, Acc=53.46), Carta2026=dict(H=0.6470, Acc=59.60))
TEST_NAMES = ("AASD", "Carta2026")


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 ewma_1d(x, tau_s, hop=HOP):
    x = np.asarray(x, np.float64)
    if tau_s <= 0:
        return x.copy()
    alpha = 1.0 - np.exp(-hop / tau_s)
    return lfilter([alpha], [1.0, -(1.0 - alpha)], x)


def tip_stream(sw2, swmix_aligned):
    return SM.apply_gate_all(sw2, swmix_aligned, TIP_KIND, TIP_THR, TIP_SHARP)


def fit_signed_emis(streams, meta, datasets):
    """HMM emissions from signed train evidence (labels on train only)."""
    parts = []
    for ds in datasets:
        if ds not in streams:
            continue
        for key, d in streams[ds].items():
            if key not in meta[ds]:
                continue
            att = meta[ds][key][0]
            n = min(len(d), len(att))
            parts.append(
                np.asarray(d[:n], np.float64)
                * np.where(np.asarray(att)[:n] == 0, 1.0, -1.0)
            )
    A = np.concatenate(parts)
    return float(A.mean()), float(max(A.std(), 1e-6))


def fit_iid_emis(streams, datasets):
    """IID Gaussian on raw (unsigned) logits — train moments only, no labels."""
    parts = []
    for ds in datasets:
        if ds not in streams:
            continue
        for d in streams[ds].values():
            parts.append(np.asarray(d, np.float64).reshape(-1))
    A = np.concatenate(parts)
    return float(A.mean()), float(max(A.std(), 1e-6))


def ll_two_state(d, mu, sd):
    """Marginal loglik under 0.5 N(+mu,sd)+0.5 N(-mu,sd)."""
    d = np.asarray(d, np.float64)
    inv = 1.0 / sd
    c = -0.5 * np.log(2.0 * np.pi * sd * sd)
    a = c - 0.5 * ((d - mu) * inv) ** 2
    b = c - 0.5 * ((d + mu) * inv) ** 2
    return logsumexp(np.stack([a, b], 0), axis=0) - np.log(2.0)


def ll_iid(d, mu, sd):
    d = np.asarray(d, np.float64)
    inv = 1.0 / sd
    c = -0.5 * np.log(2.0 * np.pi * sd * sd)
    return c - 0.5 * ((d - mu) * inv) ** 2


def gate_series(tip, hp30, emis_t, emis_h, kind, temp, ewma_tau, ll_fn):
    """g∈[0,1]; high g → trust tip. Uses unlabeled evidence only."""
    f = np.asarray(tip, np.float64)
    h = np.asarray(hp30, np.float64)
    n = min(len(f), len(h))
    f, h = f[:n], h[:n]
    if kind == "const_tip":
        return np.ones(n, np.float64)
    if kind == "const_hp30":
        return np.zeros(n, np.float64)
    ll_f = ll_fn(f, *emis_t)
    ll_h = ll_fn(h, *emis_h)
    delta = ll_f - ll_h
    if kind == "hard_cum":
        return (np.cumsum(delta) >= 0.0).astype(np.float64)
    if kind == "soft_raw":
        return expit(temp * delta)
    if kind == "soft_ewma":
        return expit(temp * ewma_1d(delta, ewma_tau))
    if kind == "hard_ewma":
        return (ewma_1d(delta, ewma_tau) >= 0.0).astype(np.float64)
    raise ValueError(kind)


def apply_gate_stream(tip_st, hp_st, emis_t, emis_h, kind, temp, ewma_tau, ll_fn):
    out = {}
    for key in tip_st:
        if key not in hp_st:
            continue
        f = np.asarray(tip_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], emis_t, emis_h, kind, temp, ewma_tau, ll_fn)
        out[key] = (g * f[:n] + (1.0 - g) * h[:n]).astype(np.float64)
    return out


def apply_gate_all(tip_all, hp_all, emis_t, emis_h, kind, temp, ewma_tau, ll_fn):
    return {
        ds: apply_gate_stream(
            tip_all[ds], hp_all[ds], emis_t, emis_h, kind, temp, ewma_tau, ll_fn
        )
        for ds in tip_all
        if ds in hp_all
    }


def candidate_rules():
    rules = [
        ("const_tip", "two_state", 1.0, 4.0),
        ("const_hp30", "two_state", 1.0, 4.0),
    ]
    for emis_kind in ("two_state", "iid"):
        rules.append(("hard_cum", emis_kind, 1.0, 4.0))
        for tau in (1.0, 2.0, 4.0, 8.0, 16.0):
            rules.append(("hard_ewma", emis_kind, 1.0, tau))
        for temp in (0.5, 1.0, 2.0, 4.0, 8.0):
            rules.append(("soft_raw", emis_kind, temp, 4.0))
            for tau in (1.0, 2.0, 4.0, 8.0, 16.0):
                rules.append(("soft_ewma", emis_kind, temp, tau))
    seen, out = set(), []
    for r in rules:
        if r not in seen:
            seen.add(r)
            out.append(r)
    return out


def rule_key(kind, emis_kind, temp, tau):
    return f"{kind}|{emis_kind}|T{temp:g}|τ{tau:g}"


def emis_pair(tip_all, hp_all, meta, datasets, emis_kind):
    if emis_kind == "two_state":
        return (
            fit_signed_emis(tip_all, meta, datasets),
            fit_signed_emis(hp_all, meta, datasets),
            ll_two_state,
        )
    if emis_kind == "iid":
        return (
            fit_iid_emis(tip_all, datasets),
            fit_iid_emis(hp_all, datasets),
            ll_iid,
        )
    raise ValueError(emis_kind)


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


def build_tip_and_hp_held(Z, swmix_full, hp30_full):
    """Per held: tip (hard_abs_swmix|t1) and DEC_OFFSET-aligned hp30."""
    tip_held, hp_held = {}, {}
    for held in DS_KEYS:
        sw2 = SW2.fuse_sw2_held(Z, held, a=A_SW2)
        sm = SM.align_swmix_to_sw2(swmix_full, sw2)
        tip = tip_stream(sw2, sm)
        tip_held[held] = tip
        hp_held[held] = SW2.align_hp30_to_sw2(hp30_full, tip)
    return tip_held, hp_held


def mean_lodo_for_rule(tip_held, hp_held, meta, kind, emis_kind, temp, tau):
    """Fit gate emissions on 4 train sets; score held-out; mean Acc/H."""
    hs, acs, per = [], [], {}
    for held in DS_KEYS:
        tip = tip_held[held]
        hp = hp_held[held]
        train = [d for d in DS_KEYS if d != held]
        emis_t, emis_h, ll_fn = emis_pair(tip, hp, meta, train, emis_kind)
        gated = apply_gate_all(tip, hp, emis_t, emis_h, kind, temp, tau, ll_fn)
        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"),
            emis_t=emis_t, emis_h=emis_h,
        )
    return float(np.mean(hs)), float(np.mean(acs)), per


def avg_corpus_stream(streams_by_held):
    acc = {ds: {} for ds in DS_KEYS}
    counts = {ds: {} for ds in DS_KEYS}
    for held in DS_KEYS:
        stream = streams_by_held[held]
        for ds in DS_KEYS:
            for k, d in stream[ds].items():
                d = np.asarray(d, np.float64)
                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
    return {
        ds: {k: acc[ds][k] / max(counts[ds][k], 1) for k in acc[ds]}
        for ds in DS_KEYS
    }


def emissions_from_stream(streams, meta, datasets):
    parts = []
    for ds in datasets:
        for k, d in streams[ds].items():
            att = meta[ds][k][0]
            n = min(len(d), len(att))
            parts.append(
                np.asarray(d[:n], np.float64)
                * np.where(np.asarray(att)[:n] == 0, 1.0, -1.0)
            )
    A = np.concatenate(parts)
    return float(A.mean()), float(A.std())


def blend_ext_arrays(tip_ev, hp_aligned, emis_t, emis_h, kind, temp, tau, ll_fn):
    """Gate tip vs aligned hp30 into external evidence dicts."""
    out = {}
    for k, e in tip_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], emis_t, emis_h, kind, temp, tau, ll_fn)
        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 mean_g_frac_ext(tip_ev, hp_aligned, emis_t, emis_h, kind, temp, tau, ll_fn):
    fracs = []
    for k, e in tip_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], emis_t, emis_h, kind, temp, tau, ll_fn)
        fracs.append(float(g.mean()))
    return float(np.mean(fracs)) if fracs else float("nan")


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(summary):
    sel = summary["selected"]
    ext = summary["external"]
    tip_acc = TIP_EXT["AASD"]["Acc"]
    hp_acc = LINEAR_HP30_EXT["AASD"]["Acc"]
    aasd = ext["AASD"]["gate"]
    carta = ext["Carta2026"]["gate"]
    lines = []
    lines.append("# results_domain_emis_acc_tip\n")
    lines.append(
        "Unlabeled-target **domain-aware emission LL** gate between Acc tip "
        "`hard_abs_swmix|t1` (sw2_swmix_blend; AASD Acc 53.53) and 4-seed "
        "`linear_hp30` (Carta Acc 60.54), DEC_OFFSET-aligned. **No retrain.** "
        "CPU on SW2/swmix/hp30 caches.\n"
    )
    lines.append(
        "**DISTINCT from** `results_domain_emis.md` (IRM↔SWA fuse↔hp30), Acc soft/hard "
        "w re-grids (sw2-hp30 / tri-acc / sw2-swmix), and `online-moment-sw2`.\n"
    )
    lines.append(
        "Evidence: `g·tip + (1−g)·hp30`. Emissions `(μ,σ)` fit on **train corpus only** "
        "(signed two-state ±μ or IID). At test: frame LL; "
        "`g = sigmoid(T·EWMA(LL_tip−LL_hp30))` or hard cum/EWMA.\n"
    )
    lines.append(
        f"HMM preset p_stay **{P_STAY}** scale **{SCALE}**. "
        f"Code: `domain_emis_acc_tip.py`. JSON: `results/research/domain_emis_acc_tip.json`.\n"
    )
    lines.append("## Gate selection (mean LODO Acc then H; never AASD/Carta)\n")
    n_cand = len(summary["lodo_grid"])
    lines.append(
        f"{n_cand} candidates; select by mean LODO Acc then H.\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 | gate H | gate Acc % | tip H/Acc | hp30 H/Acc |")
    lines.append("|---|---:|---:|---|---|")
    for ds in DS_KEYS:
        p = sel["per_ds"][ds]
        t = summary["baselines_lodo"]["tip"][ds]
        h = summary["baselines_lodo"]["hp30"][ds]
        lines.append(
            f"| {ds} | {p['H']:.4f} | {p['Acc']:.2f} | "
            f"{t['H']:.4f}/{t['Acc']:.2f} | {h['H']:.4f}/{h['Acc']:.2f} |"
        )
    lines.append(
        f"| **mean** | **{sel['mean_LODO_H']:.4f}** | **{sel['mean_LODO_Acc']:.2f}** | | |\n"
    )
    # compact family summary
    fam = {}
    for r in summary["lodo_grid"]:
        fam.setdefault(r["kind"], []).append(r)
    lines.append("### Candidate family peaks\n")
    lines.append("| Family | Best Acc / H | Key |")
    lines.append("|---|---|---|")
    for kind in ("const_tip", "const_hp30", "soft_raw", "soft_ewma", "hard_cum", "hard_ewma"):
        rows = fam.get(kind) or []
        if not rows:
            continue
        best = max(rows, key=lambda x: (x["mean_LODO_Acc"], x["mean_LODO_H"]))
        mark = " **←**" if best["key"] == sel["key"] else ""
        lines.append(
            f"| `{kind}`{mark} | {best['mean_LODO_Acc']:.2f} / {best['mean_LODO_H']:.4f} | "
            f"`{best['key']}` |"
        )
    lines.append("\n## External (preset)\n")
    lines.append("| Set | gate H/Acc | tip_only | hp30_aligned | linear_hp30 pub | tip pub |")
    lines.append("|---|---|---|---|---|---|")
    for ds in TEST_NAMES:
        g = ext[ds]["gate"]
        t = ext[ds]["tip"]
        h = ext[ds]["hp30"]
        bp = LINEAR_HP30_EXT[ds]
        tp = TIP_EXT[ds]
        lines.append(
            f"| {ds} | {g['H']:.4f} / **{g['Acc']:.2f}** | "
            f"{t['H']:.4f}/{t['Acc']:.2f} | {h['H']:.4f}/{h['Acc']:.2f} | "
            f"{bp['H']:.4f}/{bp['Acc']:.2f} | {tp['H']:.4f}/{tp['Acc']:.2f} |"
        )
    gfrac = summary.get("mean_g_frac", {})
    lines.append(
        f"\nMean tip-gate weight `g` on AASD/Carta = "
        f"{gfrac.get('AASD', float('nan')):.3f} / {gfrac.get('Carta2026', float('nan')):.3f}.\n"
    )
    lines.append("## Targets\n")
    lines.append("| Target | Result |")
    lines.append("|---|---|")
    d_tip = aasd["Acc"] - tip_acc
    d_hp = aasd["Acc"] - hp_acc
    lines.append(
        f"| AASD Acc vs tip 53.53 / hp30 53.12 | Acc **{aasd['Acc']:.2f}** "
        f"(Δtip {d_tip:+.2f}; Δhp {d_hp:+.2f}); H {aasd['H']:.4f} |"
    )
    lines.append(
        f"| AASD Acc>60? | {'YES' if aasd['Acc'] > 60 else 'NO'} |"
    )
    lines.append(
        f"| Carta vs linear_hp30 60.54 | Acc **{carta['Acc']:.2f}** "
        f"(Δ {carta['Acc'] - LINEAR_HP30_EXT['Carta2026']['Acc']:+.2f}); "
        f"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"] > 60:
        lines.append("Selected emission-LL tip↔hp30 gate clears AASD Acc>60.\n")
    elif aasd["Acc"] > tip_acc + 0.15:
        lines.append(
            "Selected rule lifts AASD Acc vs tip 53.53 but does not clear Acc>60.\n"
        )
    elif sel["key"].startswith("const_tip"):
        lines.append(
            "Honest LODO Acc/H selector collapses to **const_tip** (= Acc tip "
            "`hard_abs_swmix|t1`). Emission-LL mixing with hp30 loses train Acc/H; "
            "same qualitative failure mode as fuse↔hp30 domain-emis-ll, now on the "
            "Acc tip family.\n"
        )
    else:
        lines.append(
            "Honest LODO Acc/H selector on tip↔hp30 emission-LL does not create "
            "AASD Acc>60. Mixing Acc tip with Carta-strong hp30 via frame LL does not "
            "transfer the external Acc lift under this selector.\n"
        )
    lines.append("## NEXT IDEA\n")
    lines.append(
        "Do not rerun framewise Gaussian emission-LL tip↔hp30 (or fuse↔hp30). "
        "Bottleneck is not unlabeled stream-likelihood choice between mid-50s Acc tip "
        "and Carta-strong hp30. Prefer a **qualitatively new** Acc front-end that clears "
        "chance and lifts AASD acc1, not another frozen-stream gate. Keep tip AASD 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(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"domain_emis_acc_tip CPU  p_stay={P_STAY} scale={SCALE} "
        f"tip={TIP_KIND}|t{TIP_THR:g} OFF={OFF}"
    )
    log_line(
        "honesty: train-fit Gaussian emissions only; never AASD/Carta labels for select"
    )

    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={la_sm} hp30={la_hp}")

    log_line("building tip (hard_abs_swmix|t1) + aligned hp30 per held …")
    tip_held, hp_held = build_tip_and_hp_held(Z, swmix_full, hp30_full)

    # sanity
    r_tip = score_lodo_held(tip_held["AVGC"], meta, "AVGC")
    r_hp = score_lodo_held(hp_held["AVGC"], meta, "AVGC")
    log_line(
        f"sanity AVGC tip H {r_tip['H']:.4f} Acc {r_tip['Acc']:.2f} "
        f"(expect ~0.7159/67.94)"
    )
    log_line(f"sanity AVGC hp30-aligned H {r_hp['H']:.4f} Acc {r_hp['Acc']:.2f}")

    # baseline LODO tip / hp30 for the results table
    baselines_lodo = dict(tip={}, hp30={})
    for held in DS_KEYS:
        baselines_lodo["tip"][held] = score_lodo_held(tip_held[held], meta, held)
        baselines_lodo["hp30"][held] = score_lodo_held(hp_held[held], meta, held)
        log_line(
            f"baseline LODO {held}  tip "
            f"{baselines_lodo['tip'][held]['H']:.4f}/{baselines_lodo['tip'][held]['Acc']:.2f}  "
            f"hp30 {baselines_lodo['hp30'][held]['H']:.4f}/{baselines_lodo['hp30'][held]['Acc']:.2f}"
        )

    rules = candidate_rules()
    log_line(f"scoring {len(rules)} emission-LL gates on LODO held-outs")
    grid = []
    best = None
    for kind, emis_kind, temp, tau in rules:
        t0 = time.time()
        mean_h, mean_a, per = mean_lodo_for_rule(
            tip_held, hp_held, meta, kind, emis_kind, temp, tau
        )
        row = dict(
            kind=kind,
            emis_kind=emis_kind,
            temp=temp,
            ewma_tau=tau,
            mean_LODO_H=mean_h,
            mean_LODO_Acc=mean_a,
            per_ds={k: dict(H=v["H"], Acc=v["Acc"], SDT=v["SDT"], L=v.get("L"))
                    for k, v in per.items()},
            key=rule_key(kind, emis_kind, temp, tau),
        )
        grid.append(row)
        log_line(
            f"  LODO {row['key']:40s} H {mean_h:.4f} Acc {mean_a:.2f} "
            f"({time.time() - t0:.0f}s)"
        )
        key = (mean_a, mean_h)
        if best is None or key > best[0]:
            best = (key, row, per)

    selected = best[1]
    selected_per = best[2]
    selected["per_ds"] = {
        k: dict(H=v["H"], Acc=v["Acc"], SDT=v["SDT"], L=v.get("L"))
        for k, v in selected_per.items()
    }
    log_line(
        f"SELECTED {selected['key']} LODO H {selected['mean_LODO_H']:.4f} "
        f"Acc {selected['mean_LODO_Acc']:.2f}"
    )

    # External
    log_line("=== external (tip + aligned hp30) ===")
    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()

    # Corpus tip / hp for gate emissions + HMM emissions
    tip_corp = avg_corpus_stream(tip_held)
    hp_corp = avg_corpus_stream(hp_held)
    emis_t, emis_h, ll_fn = emis_pair(
        tip_corp, hp_corp, meta, list(DS_KEYS), selected["emis_kind"]
    )
    log_line(f"ext gate emis tip={emis_t} hp30={emis_h} kind={selected['emis_kind']}")

    # Build tip external evidence once
    tip_ext_ev = {}
    hp_ext_al = {}
    for ds in TEST_NAMES:
        sw2_ev = EV_sw2[ds][A_SW2]
        sm_al = SM.align_ext_swmix_to_sw2(sm_ext[ds], sw2_ev)
        tip_ext_ev[ds] = SM.blend_ext_ev(sw2_ev, sm_al, TIP_KIND, TIP_THR, TIP_SHARP)
        hp_ext_al[ds] = SW2.align_ext_hp_to_sw2(ext_hp[ds], tip_ext_ev[ds])

    # Corpus gated stream for HMM emissions (avg tip/hp already; apply gate)
    gated_corp = apply_gate_all(
        tip_corp, hp_corp, emis_t, emis_h,
        selected["kind"], selected["temp"], selected["ewma_tau"], ll_fn,
    )
    mu_g, sd_g = emissions_from_stream(gated_corp, meta, list(DS_KEYS))
    mu_t, sd_t = emissions_from_stream(tip_corp, meta, list(DS_KEYS))
    mu_h, sd_h = emissions_from_stream(hp_corp, meta, list(DS_KEYS))
    log_line(f"HMM emis gate μ={mu_g:.4f} σ={sd_g:.4f}  tip={mu_t:.4f}/{sd_t:.4f}  "
             f"hp={mu_h:.4f}/{sd_h:.4f}")

    external = {}
    mean_g_frac = {}
    for ds in TEST_NAMES:
        gated_ev = blend_ext_arrays(
            tip_ext_ev[ds], hp_ext_al[ds], emis_t, emis_h,
            selected["kind"], selected["temp"], selected["ewma_tau"], ll_fn,
        )
        # tip-only and hp30-aligned as evidence
        tip_only = tip_ext_ev[ds]
        hp_only = {}
        for k, e in tip_ext_ev[ds].items():
            if k not in hp_ext_al[ds]:
                continue
            h = np.asarray(hp_ext_al[ds][k], np.float64)
            n = len(h)
            hp_only[k] = dict(
                r0=h,
                r1=np.zeros(n),
                att=e["att"][:n],
                t_end=e["t_end"][:n],
                att128=e["att128"],
                n128=e["n128"],
                subject=e["subject"],
            )
        r_g = E.score(gated_ev, mu_g, sd_g * SCALE, P_STAY, LOOKAHEAD)
        r_t = E.score(tip_only, mu_t, sd_t * SCALE, P_STAY, LOOKAHEAD)
        r_h = E.score(hp_only, mu_h, sd_h * SCALE, P_STAY, LOOKAHEAD)
        external[ds] = dict(
            gate=dict(H=r_g["H"], Acc=r_g["Acc"], SDT=r_g["SDT"], L=r_g["L"]),
            tip=dict(H=r_t["H"], Acc=r_t["Acc"], SDT=r_t["SDT"], L=r_t["L"]),
            hp30=dict(H=r_h["H"], Acc=r_h["Acc"], SDT=r_h["SDT"], L=r_h["L"]),
        )
        mean_g_frac[ds] = mean_g_frac_ext(
            tip_ext_ev[ds], hp_ext_al[ds], emis_t, emis_h,
            selected["kind"], selected["temp"], selected["ewma_tau"], ll_fn,
        )
        log_line(
            f"EXT {ds}  gate H {r_g['H']:.4f} Acc {r_g['Acc']:.2f}  "
            f"tip {r_t['H']:.4f}/{r_t['Acc']:.2f}  "
            f"hp30 {r_h['H']:.4f}/{r_h['Acc']:.2f}  "
            f"g_frac={mean_g_frac[ds]:.3f}  "
            f"(pub tip {TIP_EXT[ds]['Acc']:.2f} hp30 {LINEAR_HP30_EXT[ds]['Acc']:.2f})"
        )

    aasd = external["AASD"]["gate"]
    d_tip = aasd["Acc"] - TIP_EXT["AASD"]["Acc"]
    d_hp = aasd["Acc"] - LINEAR_HP30_EXT["AASD"]["Acc"]
    summary = dict(
        p_stay=P_STAY,
        scale=SCALE,
        tip=dict(kind=TIP_KIND, thresh=TIP_THR, sharp=TIP_SHARP),
        selected=selected,
        lodo_grid=grid,
        baselines_lodo={
            "tip": {k: dict(H=v["H"], Acc=v["Acc"]) for k, v in baselines_lodo["tip"].items()},
            "hp30": {k: dict(H=v["H"], Acc=v["Acc"]) for k, v in baselines_lodo["hp30"].items()},
        },
        external=external,
        mean_g_frac=mean_g_frac,
        ext_gate_emis=dict(emis_t=emis_t, emis_h=emis_h),
        hmm_emis=dict(gate=(mu_g, sd_g), tip=(mu_t, sd_t), hp30=(mu_h, sd_h)),
        baselines=dict(
            tip_ext=TIP_EXT,
            linear_hp30_ext=LINEAR_HP30_EXT,
            sw2_alone_ext=SW2_ALONE_EXT,
        ),
        AASD_Acc_delta_vs_tip=d_tip,
        AASD_Acc_delta_vs_linear_hp30=d_hp,
        AASD_Acc_gt_60=bool(aasd["Acc"] > 60),
        seconds=time.time() - t_all,
        claim=(
            "Framewise Gaussian emission-LL gate Acc tip hard_abs_swmix|t1 ↔ linear_hp30. "
            "Distinct from domain-emis-ll fuse↔hp30 and Acc soft-w re-grids."
        ),
    )
    with open(OUT, "w") as fh:
        json.dump(summary, fh, indent=1, default=_json_default)
    write_md(summary)
    log_line(
        f"AASD Acc {aasd['Acc']:.2f} (Δtip {d_tip:+.2f}, Δhp {d_hp:+.2f}; "
        f">60={'YES' if aasd['Acc'] > 60 else 'NO'})  "
        f"Carta {external['Carta2026']['gate']['Acc']:.2f}  wrote {OUT} + {RESULTS_MD} "
        f"in {time.time() - t_all:.0f}s"
    )


if __name__ == "__main__":
    main()
