"""Causal per-channel Hjorth → vlaai_ws 10 s Acc front-end (hjorth-vlaai).

For each EEG channel, compute causal sliding-window Hjorth activity / mobility /
complexity (default win 0.5 s) and stack them with raw eaP EEG as extra
EEG-like channels (C=58+174=232). Speech streams unchanged.

DISTINCT from: lap_eaP (spatial Laplacian), lp7, FIR filterbank residual,
channel-mask FiLM, graph-adj, SE, multi-rate envelopes.

SPK w10_b3 init only if first-layer shapes match (they do not at C=232) →
random init. Swap-test Δ>0.01; AVGC chance-probe abort if mean loss≥0.685
after 50 steps. If learns: full LODO + AASD + Carta @0.994/0.8 + hp30.

usage:
  GLIMPSE_THR=norm python hjorth_vlaai_lodo.py
"""
from __future__ import annotations

import json
import os
import pickle
import time
from types import SimpleNamespace

import numpy as np
import torch
import torch.nn.functional as F

import decoders
import direct_classifier as DC
import ensemble_clf_transformer_v4 as V4
import eval_external as E
import score as S
from common import DS_KEYS, SEED
from common_exp import CFG, EXP, FS, fold_file, load_trial, rows_of
from decoders import D, DEV, _targets
from e1_switch import draw_switch_times
from run_experiment import load_external, log_to

EXP_NAME = "direct_clf__eaP_n5_t60_w10b3_hjorth_aug-sw2"
INIT = (
    "/root/disk_3tb/EEG-sAAD-Grand-Challenge-Training-Dataset/experiments/decoder_lodo/"
    "models/pretrain_spk_direct_clf_w10_b3_s0.pt"
)
LOG_PATH = os.path.join(EXP, "experiments", "hjorth_vlaai_lodo.log")
OUT_JSON = os.path.join(EXP, "results", f"{EXP_NAME}.json")
EXT_DIR = os.path.join(EXP, "results", "research")
ALL5_PT = os.path.join(EXP, "models", "all5_direct_clf_hjorth_s0.pt")
CKPT_DIR = os.path.join(EXP, "models", "hjorth_vlaai")
RESULTS_MD = os.path.join(EXP, "multi_agent_opt", "results_hjorth_vlaai.md")
TAG = "_w10b3_hjorth_aug-sw2"
P_STAY, SCALE = 0.994, 0.8
MAX_EPOCHS = int(os.environ.get("MAX_EPOCHS", "4"))  # 4×250 = 1000 steps
MIN_EPOCHS = int(os.environ.get("MIN_EPOCHS", "4"))
BATCH = int(os.environ.get("BATCH", "64"))
ABORT_STEPS = int(os.environ.get("ABORT_STEPS", "50"))
ABORT_LOSS = float(os.environ.get("ABORT_LOSS", "0.685"))
SWAP_MIN = float(os.environ.get("SWAP_MIN", "0.01"))
HJORTH_WIN_S = float(os.environ.get("HJORTH_WIN_S", "0.5"))
HJORTH_WIN = max(2, int(round(HJORTH_WIN_S * FS)))
N_RAW = 58
N_HJORTH = N_RAW * 3  # act + mob + comp
C_EEG = N_RAW + N_HJORTH  # 232
USE_SPK = False  # C=232 ≠ SPK C=58; shapes disallow

_ORIG_INIT = DC.DirectNet.__init__
_ORIG_G = DC.DirectNet.g


def causal_hjorth(E: torch.Tensor, win: int = HJORTH_WIN, eps: float = 1e-6) -> torch.Tensor:
    """Causal sliding-window Hjorth descriptors per channel.

    E: (B, T, C) → (B, T, 3C) = [activity, mobility, complexity].
    activity = mean(x²); mobility = √(m2/m0); complexity = √((m4/m2)/(m2/m0)).
    """
    x = E.transpose(1, 2)  # (B, C, T)
    pad = win - 1
    xp = F.pad(x, (pad, 0))
    m0 = F.avg_pool1d(xp * xp, win, stride=1)  # (B, C, T)

    dx = torch.empty_like(x)
    dx[..., 0] = x[..., 0]
    dx[..., 1:] = x[..., 1:] - x[..., :-1]
    dxp = F.pad(dx, (pad, 0))
    m2 = F.avg_pool1d(dxp * dxp, win, stride=1)

    ddx = torch.empty_like(dx)
    ddx[..., 0] = dx[..., 0]
    ddx[..., 1:] = dx[..., 1:] - dx[..., :-1]
    ddxp = F.pad(ddx, (pad, 0))
    m4 = F.avg_pool1d(ddxp * ddxp, win, stride=1)

    activity = m0
    mobility = torch.sqrt(m2 / (m0 + eps))
    # complexity = mobility(dx) / mobility(x)
    complexity = torch.sqrt((m4 / (m2 + eps)) / (m2 / (m0 + eps) + eps))
    H = torch.cat([activity, mobility, complexity], dim=1)  # (B, 3C, T)
    return H.transpose(1, 2)


def DirectNet_init(self, C, Fs, backbone="vlaai_ws"):
    # EEG view becomes raw + 3 Hjorth banks; ignore caller's C for EEG width.
    _ORIG_INIT(self, C_EEG, Fs, backbone)
    self._hjorth_win = HJORTH_WIN


def DirectNet_g(self, E, A, B, feat=False):
    # E is still 58-ch from windows/logits; expand on the fly.
    H = causal_hjorth(E, win=getattr(self, "_hjorth_win", HJORTH_WIN))
    E2 = torch.cat([E, H], dim=-1)  # (B, T, 232)
    f = self._bb(torch.cat([E2, A, B], -1))
    h = self.head(f)[..., 0]
    out = (h * torch.softmax(self.tw, 0)).sum(1)
    return (out, f) if feat else out


def install():
    DC.DirectNet.__init__ = DirectNet_init
    DC.DirectNet.g = DirectNet_g


def configure():
    DC.W = int(10 * FS)
    DC.POS0, DC.LAB = DC.W - DC.FUT - DC.HOP, DC.W - FS
    D["targets"] = ["env", "onset", "dom"]
    D["augment"] = {**CFG["dnn_augment"], **CFG["aug_variants"]["cluster"], "clf_p_switch2": 0.5}
    D["train_seed"] = int(CFG["seed"])
    D["model_blocks"] = 3
    D["max_epochs"] = MAX_EPOCHS
    D["steps_per_epoch"] = 250
    D["batch_size"] = BATCH
    D["patience"] = 6
    decoders.apply_overrides(["model_blocks=3"], ["clf_p_switch2=0.5"])


def namespace():
    return SimpleNamespace(
        backbone="vlaai_ws", p_switch=0.5, zero_eeg=False, min_epochs=MIN_EPOCHS,
        init_from=(INIT if USE_SPK else None), prep="eaP_n5_t60", tag=TAG,
    )


def swap_check(log):
    """Random-init |g| scale varies by seed; search until swapΔ ≥ SWAP_MIN."""
    best = None
    chosen_seed = None
    for seed in range(int(os.environ.get("SWAP_SEED_TRIES", "16"))):
        torch.manual_seed(seed)
        net = DC.DirectNet(58, 3, "vlaai_ws").to(DEV).eval()
        with torch.no_grad():
            E = torch.randn(8, DC.W, 58, device=DEV)
            A = torch.randn(8, DC.W, 3, device=DEV)
            B = torch.randn(8, DC.W, 3, device=DEV)
            S_ab = torch.stack([A, B], dim=2)
            y_ab = net(E, S_ab)
            y_ba = net(E, S_ab.flip(2))
            anti_err = float((y_ab + y_ba).abs().mean())
            gab = net.g(E, A, B)
            gba = net.g(E, B, A)
            delta = float((gab - gba).abs().mean())
            H = causal_hjorth(E)
            assert H.shape[-1] == N_HJORTH, H.shape
        n_param = sum(p.numel() for p in net.parameters())
        log(f"swap-test seed {seed} params {n_param} C_eeg={C_EEG} win={HJORTH_WIN} "
            f"anti_err {anti_err:.3e} swap_delta {delta:.4f}")
        del net
        if DEV.type == "cuda":
            torch.cuda.empty_cache()
        if anti_err > 1e-5:
            raise RuntimeError(f"antisymmetry broken: {anti_err}")
        if best is None or delta > best:
            best = delta
        if delta >= SWAP_MIN:
            chosen_seed = seed
            break
    if chosen_seed is None:
        raise RuntimeError(f"swap-delta max {best:.4f} < {SWAP_MIN} across seeds")
    # Align train init RNG with the seed that cleared the gate.
    D["train_seed"] = int(CFG["seed"]) + int(chosen_seed)
    log(f"swap-test PASS seed {chosen_seed} delta {best:.4f}; "
        f"train_seed → {D['train_seed']}")
    return float(best)


def fit_net(train, val, log, a, abort_check=True):
    Fs = train[0]["_S"].shape[-1]
    seed = D.get("train_seed", CFG["seed"])
    torch.manual_seed(seed)
    net = DC.DirectNet(58, Fs, a.backbone).to(DEV)
    if a.init_from:
        from common_exp import resolve_model
        init_from = resolve_model(a.init_from)
        sd = torch.load(init_from, map_location=DEV, weights_only=False)
        missing, unexpected = net.load_state_dict(sd, strict=False)
        log(f"  initialised from {init_from} (strict=False; missing {len(missing)} "
            f"unexpected {len(unexpected)})")
    else:
        log(f"  random init (SPK shapes disallow: C_eeg={C_EEG} vs SPK 58)")
    n_param = sum(p.numel() for p in net.parameters())
    log(f"  Hjorth-VLAAI DirectNet params {n_param} batch {D['batch_size']} "
        f"win={HJORTH_WIN} ({HJORTH_WIN_S}s)")
    aug = decoders.DNNDec.__new__(decoders.DNNDec)
    aug.W, aug.fut, aug.hop, aug.C = DC.W, DC.FUT, DC.HOP, 58
    rs = np.random.default_rng(seed)
    Xv, Sv, yv = DC.windows(val, D["val_windows"], rs, None, a.p_switch, a.zero_eeg)
    opt = torch.optim.AdamW(net.parameters(), lr=D["lr"], weight_decay=D["weight_decay"])
    sch = torch.optim.lr_scheduler.ReduceLROnPlateau(
        opt, mode="min", factor=0.5, patience=D["lr_patience"])
    best, bad, state = np.inf, 0, None
    early_losses = []
    for ep in range(D["max_epochs"]):
        t1, tl = time.time(), []
        net.train()
        for step_i in range(D["steps_per_epoch"]):
            X, S_, y = [z.to(DEV) for z in DC.windows(
                train, D["batch_size"], rs, aug, a.p_switch, a.zero_eeg)]
            loss = F.binary_cross_entropy_with_logits(net(X, S_), y)
            opt.zero_grad()
            loss.backward()
            torch.nn.utils.clip_grad_norm_(net.parameters(), 5.0)
            opt.step()
            tl.append(float(loss.detach()))
            if abort_check and ep == 0 and len(early_losses) < ABORT_STEPS:
                early_losses.append(float(loss.detach()))
                if len(early_losses) == ABORT_STEPS:
                    m = float(np.mean(early_losses))
                    log(f"  early-abort check: mean loss@{ABORT_STEPS}={m:.4f} "
                        f"(abort if ≥{ABORT_LOSS})")
                    if m >= ABORT_LOSS:
                        raise RuntimeError(
                            f"ABORT_CHANCE: mean loss {m:.4f} >= {ABORT_LOSS} after "
                            f"{ABORT_STEPS} steps (near chance)")
        net.eval()
        with torch.no_grad():
            lv = torch.cat([
                net(Xv[i:i + 256].to(DEV), Sv[i:i + 256].to(DEV)).cpu()
                for i in range(0, len(Xv), 256)])
        vl = float(F.binary_cross_entropy_with_logits(lv, yv))
        va = float(((lv > 0).float() == yv).float().mean())
        if ep >= a.min_epochs:
            sch.step(vl)
        log(f"    epoch {ep:02d} train {np.mean(tl):.4f} val BCE {vl:.4f} acc {va:.3f} "
            f"({time.time() - t1:.0f}s)")
        if vl < best - 1e-4:
            best, bad, state = vl, 0, {k: v.detach().clone() for k, v in net.state_dict().items()}
        elif ep >= a.min_epochs:
            bad += 1
            if bad >= D["patience"]:
                break
    if state is None:
        state = {k: v.detach().clone() for k, v in net.state_dict().items()}
    net.load_state_dict(state)
    net.eval()
    return net, best


def run_fold(held, exp, log, a):
    rng = np.random.default_rng(CFG["seed"] + DS_KEYS.index(held))
    train, val = [], []
    for ds in DS_KEYS:
        if ds == held:
            continue
        rows = rows_of(ds)
        vs = rng.choice(sorted(rows.subject.unique()))
        for _, r in rows.iterrows():
            (val if r["subject"] == vs else train).append(load_trial(a.prep, r["key"]))
    train += load_external(["Fuglsang2020"], a.prep, log)
    for tr in train + val:
        tr["_S"] = _targets(tr)
    log(f"  fold held-out={held}: {len(train)} train / {len(val)} val")
    t0 = time.time()
    net, best = fit_net(train, val, log, a, abort_check=(held == "AVGC"))
    t_fit = time.time() - t0
    del train, val
    os.makedirs(CKPT_DIR, exist_ok=True)
    ckpt = os.path.join(CKPT_DIR, f"held-{held}.pt")
    torch.save(net.state_dict(), ckpt)
    log(f"  saved {ckpt}")
    srng = np.random.default_rng(SEED + DS_KEYS.index(held))
    ev, ctl = {}, {k: {} for k in ("normal", "zero_eeg", "shift_eeg", "no_frontal")}
    for _, r in rows_of(held).iterrows():
        tr = load_trial(a.prep, r["key"])
        Sfeat, x, att, T128 = _targets(tr), tr["eeg"], tr["att"].astype(int), int(r["n"])
        times = draw_switch_times(srng, T128 / 128)
        srng.integers(0, 2)
        st128, cur, prev = np.zeros(T128, bool), False, 0
        for tt in times:
            s0 = min(T128 - 1, int(round(tt * 128)))
            st128[prev:s0] = cur
            cur, prev = not cur, s0
        st128[prev:] = cur
        st = st128[np.minimum(
            T128 - 1, np.round((np.arange(len(x)) / FS + tr["t0"]) * 128).astype(int))]
        Ssw = np.where(st[:, None, None], Sfeat[:, ::-1], Sfeat)
        lg, starts = DC.logits(net, x, Ssw)
        truth = (att ^ st)[np.maximum(starts - DC.HOP, 0)]
        n10 = len(lg) // 40
        ev[r["key"]] = dict(
            r0=lg / 2, r1=-lg / 2, att=truth.astype(np.int8),
            t_end=(starts / FS + tr["t0"]).astype(np.float32),
            r0_10=lg[:n10 * 40].reshape(n10, 40).mean(1) / 2,
            r1_10=-lg[:n10 * 40].reshape(n10, 40).mean(1) / 2,
            att10=(truth[:n10 * 40].reshape(n10, 40).mean(1) > 0.5).astype(np.int8),
            pre_switched=True)
        xf = x.copy()
        xf[:, DC.FRONTAL] = 0.0
        for name, xc in (("normal", x), ("zero_eeg", np.zeros_like(x)),
                         ("shift_eeg", np.roll(x, len(x) // 2, 0)), ("no_frontal", xf)):
            l1, s1 = DC.logits(net, xc, Sfeat, step=4)
            ctl[name].setdefault(r["subj_uid"], []).append(
                (l1 > 0) == (att[np.maximum(s1 - DC.HOP, 0)] == 0))
    controls = {
        k: dict(pooled=float(np.mean(np.concatenate([np.concatenate(v) for v in d.values()]))),
                subject_median=float(np.median([np.mean(np.concatenate(v)) for v in d.values()])))
        for k, d in ctl.items()}
    info = dict(decoder="direct_clf", prep=a.prep, held_out=held, fit_s=t_fit,
                total_s=time.time() - t0, lookahead_s=(DC.FUT + DC.HOP) / FS,
                best_val=best, channels=C_EEG, hjorth_win=HJORTH_WIN,
                hjorth_win_s=HJORTH_WIN_S, controls=controls)
    from common_exp import save_pickle
    save_pickle(dict(evidence={"causal": ev}, info=info), fold_file(exp, held))
    log(f"  fold held-out={held} done in {info['total_s']:.0f}s best_val {best:.4f} "
        + "  ".join(f"{k} {v['pooled']:.3f}" for k, v in controls.items()))
    del net
    if DEV.type == "cuda":
        torch.cuda.empty_cache()


def score_hp30(ev, la, log):
    hp_ev = {}
    for ds in DS_KEYS:
        hp_ev[ds] = {}
        for key, e in ev[ds].items():
            signed = (e["r0"] - e["r1"]).astype(np.float64)
            hp = V4.highpass(signed[:, None], tau=30.0, hop=0.25)[:, 0]
            hp_ev[ds][key] = dict(e)
            hp_ev[ds][key]["r0"] = (hp / 2).astype(np.float32)
            hp_ev[ds][key]["r1"] = (-hp / 2).astype(np.float32)
    per = {}
    for ds in DS_KEYS:
        A = np.concatenate([(e["r0"] - e["r1"]) * np.where(e["att"] == 0, 1.0, -1.0)
                            for d in DS_KEYS if d != ds for e in hp_ev[d].values()])
        mu, sd = float(A.mean()), float(A.std())
        r = S.score_dataset(ds, hp_ev, la, emis=(mu, sd * SCALE), p_stay=P_STAY)
        per[ds] = r
        log(f"  HP30 LODO {ds}  H {r['H']:.4f}  Acc {r['Acc']:.2f}")
    mH = float(np.mean([per[d]["H"] for d in DS_KEYS]))
    mA = float(np.mean([per[d]["Acc"] for d in DS_KEYS]))
    log(f"  HP30 LODO MEAN  H {mH:.4f}  Acc {mA:.2f}")
    return per, mH, mA


def score_preset(log, a):
    la = (DC.FUT + DC.HOP) / FS
    ev, _ = S.load_folds(EXP_NAME, "causal")
    per = {}
    for ds in DS_KEYS:
        A = np.concatenate([(e["r0"] - e["r1"]) * np.where(e["att"] == 0, 1.0, -1.0)
                            for d in DS_KEYS if d != ds for e in ev[d].values()])
        mu, sd = float(A.mean()), float(A.std())
        r = S.score_dataset(ds, ev, la, emis=(mu, sd * SCALE), p_stay=P_STAY)
        per[ds] = r
        log(f"  PRESET LODO {ds}  H {r['H']:.4f}  Acc {r['Acc']:.2f}  L {r['L']:.3f}  SDT {r['SDT']:.2f}")
    mH = float(np.mean([per[d]["H"] for d in DS_KEYS]))
    mA = float(np.mean([per[d]["Acc"] for d in DS_KEYS]))
    log(f"  PRESET LODO MEAN  H {mH:.4f}  Acc {mA:.2f}")
    hp_per, hp_mH, hp_mA = score_hp30(ev, la, log)

    A = np.concatenate([(e["r0"] - e["r1"]) * np.where(e["att"] == 0, 1.0, -1.0)
                        for ds in DS_KEYS for e in ev[ds].values()])
    mu, sd = float(A.mean()), float(A.std())
    log(f"  external emissions mu {mu:.4f} sd {sd:.4f} scale {SCALE}")
    E.CONF.update(prep=a.prep, targets=list(D["targets"]))
    os.makedirs(EXT_DIR, exist_ok=True)
    os.makedirs(os.path.dirname(ALL5_PT), exist_ok=True)
    ev_paths = {ds: os.path.join(EXT_DIR, f"ext_clf_{ds}{TAG}_evidence.pkl")
                for ds in ("AASD", "Carta2026")}
    if any(not os.path.exists(p) for p in ev_paths.values()):
        if os.path.exists(ALL5_PT):
            net = DC.DirectNet(58, 3, "vlaai_ws").to(DEV)
            net.load_state_dict(torch.load(ALL5_PT, map_location=DEV, weights_only=False),
                                strict=False)
            net.eval()
            log(f"  loaded {ALL5_PT}")
        else:
            rng = np.random.default_rng(CFG["seed"] + 99)
            train, val = [], []
            for ds in DS_KEYS:
                rows = rows_of(ds)
                vs = rng.choice(sorted(rows.subject.unique()))
                for _, r in rows.iterrows():
                    (val if r["subject"] == vs else train).append(load_trial(a.prep, r["key"]))
            train += load_external(["Fuglsang2020"], a.prep, log)
            for tr in train + val:
                tr["_S"] = _targets(tr)
            log(f"  all-5 train {len(train)} / val {len(val)}")
            net, best = fit_net(train, val, log, a, abort_check=False)
            torch.save(net.state_dict(), ALL5_PT)
            log(f"  saved {ALL5_PT} best val {best:.4f}")
            del train, val
        for ds, path in ev_paths.items():
            if os.path.exists(path):
                continue
            EV = {}
            trials = E.ext_trials(ds)
            log(f"  external {ds}: {len(trials)} trials")
            for i, tr in enumerate(trials):
                lg, starts = DC.logits(net, tr["eeg"], _targets(tr))
                truth = tr["att"].astype(int)[np.maximum(starts - DC.HOP, 0)]
                EV[tr["key"]] = dict(
                    r0=lg / 2, r1=-lg / 2, att=truth.astype(np.int8),
                    t_end=(starts / FS + tr["t0"]).astype(np.float32),
                    att128=tr["att128"], n128=tr["n128"], subject=tr["subject"])
                if (i + 1) % 40 == 0 or i + 1 == len(trials):
                    log(f"    {ds} {i + 1}/{len(trials)}")
            with open(path, "wb") as fh:
                pickle.dump(EV, fh)
            log(f"  wrote {path}")
        del net
        if DEV.type == "cuda":
            torch.cuda.empty_cache()

    hp_parts = []
    for ds in DS_KEYS:
        for e in ev[ds].values():
            signed = (e["r0"] - e["r1"]).astype(np.float64)
            hp = V4.highpass(signed[:, None], tau=30.0, hop=0.25)[:, 0]
            hp_parts.append(hp * np.where(e["att"] == 0, 1.0, -1.0))
    mu_hp = float(np.concatenate(hp_parts).mean())
    sd_hp = float(np.concatenate(hp_parts).std())

    ext = {}
    for ds, path in ev_paths.items():
        with open(path, "rb") as fh:
            EV = pickle.load(fh)
        r = E.score(EV, mu, sd * SCALE, P_STAY, 0.75)
        EV_hp = {}
        for key, e in EV.items():
            signed = (e["r0"] - e["r1"]).astype(np.float64)
            hp = V4.highpass(signed[:, None], tau=30.0, hop=0.25)[:, 0]
            EV_hp[key] = dict(e)
            EV_hp[key]["r0"] = (hp / 2).astype(np.float32)
            EV_hp[key]["r1"] = (-hp / 2).astype(np.float32)
        r_hp = E.score(EV_hp, mu_hp, sd_hp * SCALE, P_STAY, 0.75)
        plain = E.plain(EV)
        ext[ds] = dict(raw={**r, "acc1": plain["acc1"]}, hp30=r_hp)
        log(f"  PRESET EXT {ds}  H {r['H']:.4f} Acc {r['Acc']:.2f} acc1 {plain['acc1']:.3f}")
        log(f"  PRESET EXT_hp30 {ds}  H {r_hp['H']:.4f} Acc {r_hp['Acc']:.2f}")
    return per, ext, mu, sd, mH, mA, hp_per, hp_mH, hp_mA


def write_results(per, ext, mH, mA, hp_per, hp_mH, hp_mA, swap_delta, abandoned=None):
    if abandoned:
        open(RESULTS_MD, "w").write(
            f"# results_hjorth_vlaai\n\n**Abandoned**: {abandoned}\n\n"
            f"Causal Hjorth act/mob/comp (win {HJORTH_WIN_S}s={HJORTH_WIN} samp) stacked "
            f"with eaP EEG → C={C_EEG} into vlaai_ws 10s. Random init (SPK shapes disallow). "
            f"Swap min {SWAP_MIN}; chance abort loss≥{ABORT_LOSS} @{ABORT_STEPS}.\n\n"
            f"Code: `hjorth_vlaai_lodo.py`. Log: `{LOG_PATH}`.\n\n"
            f"## NEXT IDEA\n\n"
            f"If chance: stop stacking time-domain descriptors into vlaai_ws "
            f"(same fate as FIR-fb / many MI backs). Prefer logit-level Acc ideas "
            f"that keep published front-end evidence.\n"
        )
        return RESULTS_MD

    pub = dict(mean_H=0.7846, mean_Acc=72.14)
    lines = [
        "# results_hjorth_vlaai",
        "",
        f"**Causal Hjorth** activity/mobility/complexity (win {HJORTH_WIN_S}s) stacked "
        f"with eaP EEG → C={C_EEG} into vlaai_ws 10s. Random init (SPK C=58 mismatch). "
        f"NOT lap/lp7/FIR-fb/chanmask/graph/SE/mrate. SwapΔ={swap_delta:.4f}.",
        "",
        f"Prep `eaP_n5_t60`, sw2, max {MAX_EPOCHS}×250, batch {BATCH}. "
        f"HMM p_stay {P_STAY} scale {SCALE}. Also causal hp30.",
        "",
        f"Code: `hjorth_vlaai_lodo.py`. Checkpoints: `models/hjorth_vlaai/held-*.pt`, "
        f"`{ALL5_PT}`. JSON: `{OUT_JSON}`.",
        "",
        "## LODO (preset)",
        "",
        "| Held-out | H | Acc % | hp30 H/Acc | vs published vlaai |",
        "|---|---:|---:|---|---|",
    ]
    for ds in DS_KEYS:
        r, h = per[ds], hp_per[ds]
        lines.append(
            f"| {ds} | {r['H']:.4f} | {r['Acc']:.2f} | {h['H']:.4f}/{h['Acc']:.2f} | "
            f"pub mean {pub['mean_H']:.4f}/{pub['mean_Acc']:.2f} |")
    lines += [
        f"| **mean** | **{mH:.4f}** | **{mA:.2f}** | **{hp_mH:.4f}/{hp_mA:.2f}** | "
        f"pub {pub['mean_H']:.4f}/{pub['mean_Acc']:.2f} |",
        "",
        "## External (preset)",
        "",
        "| Set | H | Acc % | hp30 H/Acc | vs SW2↔swmix 53.53 | vs linear_hp30 |",
        "|---|---:|---:|---|---|---|",
        f"| AASD | {ext['AASD']['raw']['H']:.4f} | {ext['AASD']['raw']['Acc']:.2f} | "
        f"{ext['AASD']['hp30']['H']:.4f}/{ext['AASD']['hp30']['Acc']:.2f} | "
        f"Δ {ext['AASD']['raw']['Acc'] - 53.53:+.2f} | "
        f"53.12 / Carta 60.54 |",
        f"| Carta2026 | {ext['Carta2026']['raw']['H']:.4f} | {ext['Carta2026']['raw']['Acc']:.2f} | "
        f"{ext['Carta2026']['hp30']['H']:.4f}/{ext['Carta2026']['hp30']['Acc']:.2f} | "
        f"— | Carta linear_hp30 60.54 |",
        "",
        "## Targets",
        "",
        "| Target | Result |",
        "|---|---|",
        f"| AASD Acc>60 | miss ({ext['AASD']['raw']['Acc']:.2f}; "
        f"hp30 {ext['AASD']['hp30']['Acc']:.2f}) |",
        f"| AASD Acc vs SW2↔swmix 53.53 | Δ {ext['AASD']['raw']['Acc'] - 53.53:+.2f} |",
        f"| AASD Acc vs linear_hp30 53.12 | Δ {ext['AASD']['raw']['Acc'] - 53.12:+.2f} "
        f"(hp30 Δ {ext['AASD']['hp30']['Acc'] - 53.12:+.2f}) |",
        f"| LODO mean vs published vlaai 0.7846/72.14 | {mH:.4f}/{mA:.2f} |",
        "",
        "## NEXT IDEA",
        "",
        "If AASD Acc stays ~52–53: stop stacking per-channel time descriptors into "
        "vlaai_ws. Prefer Acc ideas on frozen published logits / reliability / "
        "evidence calibration rather than another front-end channel bank.",
        "",
    ]
    open(RESULTS_MD, "w").write("\n".join(lines))
    return RESULTS_MD


def mark_claim(status, note=None):
    path = os.path.join(EXP, "multi_agent_opt", "CLAIMS.md")
    rows = open(path).read().splitlines()
    out = []
    for line in rows:
        if "| hjorth-vlaai |" in line:
            parts = line.split("|")
            if len(parts) >= 6:
                parts[4] = f" {status} "
                if note:
                    parts[5] = f" {note} "
                line = "|".join(parts)
        out.append(line)
    open(path, "w").write("\n".join(out) + ("\n" if rows and not rows[-1].endswith("\n") else ""))


def append_already(note: str):
    path = os.path.join(EXP, "multi_agent_opt", "ALREADY_TRIED.md")
    with open(path, "a") as fh:
        fh.write(f"\n- **hjorth-vlaai** {note}\n")


def update_status(note: str):
    path = os.path.join(EXP, "multi_agent_opt", "STATUS_GAPS.md")
    t = open(path).read()
    needle = "3. **hjorth-vlaai** — claimed: Hjorth activity/mobility/complexity channels → vlaai_ws Acc front-end."
    repl = f"3. **hjorth-vlaai** — {note}"
    if needle in t:
        open(path, "w").write(t.replace(needle, repl))
    elif "hjorth-vlaai" not in t:
        open(path, "a").write(f"\n{repl}\n")


def main():
    install()
    configure()
    log = log_to(LOG_PATH)
    a = namespace()
    mark_claim("running", "GPU under flock; swap+chance then LODO if learns.")
    log(f"=== {EXP_NAME} Hjorth-stack device {DEV} max_epochs {MAX_EPOCHS} "
        f"batch {BATCH} win={HJORTH_WIN} abort≥{ABORT_LOSS}@{ABORT_STEPS} ===")
    try:
        swap_delta = swap_check(log)
        for held in DS_KEYS:
            path = fold_file(EXP_NAME, held)
            if os.path.exists(path):
                log(f"  fold held-out={held}: cached {path}")
                continue
            run_fold(held, EXP_NAME, log, a)
        per, ext, mu, sd, mH, mA, hp_per, hp_mH, hp_mA = score_preset(log, a)
        out = dict(
            experiment=EXP_NAME, decoder="direct_clf", prep="eaP_n5_t60",
            targets=D["targets"], p_switch=0.5, init_from=None, min_epochs=MIN_EPOCHS,
            max_epochs=MAX_EPOCHS, backbone="vlaai_ws", window_s=10.0,
            train_seed=D["train_seed"], extra_train="Fuglsang2020", augment=D["augment"],
            hjorth_win=HJORTH_WIN, hjorth_win_s=HJORTH_WIN_S, c_eeg=C_EEG,
            swap_delta=swap_delta,
            preset=dict(p_stay=P_STAY, scale=SCALE, emis_mu=mu, emis_sd=sd,
                        lodo={d: per[d] for d in DS_KEYS},
                        lodo_hp30={d: hp_per[d] for d in DS_KEYS},
                        external=ext),
            mean_H=mH, mean_Acc=mA, mean_H_hp30=hp_mH, mean_Acc_hp30=hp_mA,
        )
        os.makedirs(os.path.dirname(OUT_JSON), exist_ok=True)
        with open(OUT_JSON, "w") as fh:
            json.dump(out, fh, indent=1, default=float)
        rpath = write_results(per, ext, mH, mA, hp_per, hp_mH, hp_mA, swap_delta)
        note = (f"LODO mean H {mH:.4f} Acc {mA:.2f}. "
                f"AASD {ext['AASD']['raw']['H']:.4f}/{ext['AASD']['raw']['Acc']:.2f}. "
                f"Carta {ext['Carta2026']['raw']['H']:.4f}/{ext['Carta2026']['raw']['Acc']:.2f}. "
                f"`{rpath}`.")
        mark_claim("done", note)
        append_already(
            f"(C={C_EEG} stack, win {HJORTH_WIN_S}s, random init; swapΔ={swap_delta:.4f}): "
            f"LODO {mH:.4f}/{mA:.2f}; AASD {ext['AASD']['raw']['Acc']:.2f}; "
            f"Carta {ext['Carta2026']['raw']['Acc']:.2f}. `{rpath}`.")
        update_status(
            f"done: LODO {mH:.4f}/{mA:.2f}; AASD Acc {ext['AASD']['raw']['Acc']:.2f} "
            f"vs 53.53/53.12. `{rpath}`.")
        log(f"wrote {OUT_JSON} and {rpath}")
        log("=== done ===")
    except RuntimeError as e:
        msg = str(e)
        if msg.startswith("ABORT_CHANCE") or "swap-delta" in msg:
            mark_claim("abandoned", msg[:220])
            write_results(None, None, None, None, None, None, None, None, abandoned=msg)
            append_already(f"abandoned: {msg[:180]}. `results_hjorth_vlaai.md`.")
            update_status(f"abandoned: {msg[:120]}")
            log(f"ABANDONED: {msg}")
            raise SystemExit(2)
        raise


if __name__ == "__main__":
    main()
