"""Focal-BCE fine-tune of stem_ms96 from IRM (preferred) or SWA.

Replace recipe BCE with focal BCE (Lin et al.):
  FL = α_t * (1 − p_t)^γ * BCE_with_logits
keeping post-switch sample weights + TV. Architecture unchanged (ms, w96).

Init models/stem_ms96_irm/{held-*,all5}.pt (fallback SWA via INIT_DIR);
restore causal -inf mask. EMA 0.995 eval. HMM preset 0.994 / 0.8.
Also report causal tau-30 high-pass of the evidence.

Smoke: γ ∈ {1.0, 2.0}; optional α=0.25 (when α set, skip class pos_weight).
After LODO, also score fuse w=0.5 with frozen stem_synth_switch
(focal-IRM ↔ synth) — tip comparison vs IRM↔synth 0.8192/75.52.

Distinct from AVGC λ upweight, avgc-curriculum, soft-H, fuse-conf-resid,
PCGrad/SAM.

usage:
  FOCAL_GAMMA=2.0 STEPS=800 python stem_ms96_focal_avgc.py
  SMOKE=1 STEPS=40 python stem_ms96_focal_avgc.py   # pick γ; no full score
  TUNE_GAMMA=1 python ...   # smoke then full LODO
"""
import copy
import json
import math
import os
import pickle
import time

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

import ensemble_clf_nested as N
import ensemble_clf_transformer_v2 as V
import ensemble_clf_transformer_v4 as V4
import eval_external as E
import stem_ms96_irm_swa_fuse as Fuse
from common import DS_KEYS

EXP = os.path.dirname(os.path.abspath(__file__))
INIT_DIR = os.environ.get(
    "INIT_DIR", os.path.join(EXP, "models", "stem_ms96_irm"))
SYNTH_DIR = os.environ.get(
    "SYNTH_DIR", os.path.join(EXP, "models", "stem_ms96_synth_switch"))
CKPT_DIR = os.path.join(EXP, "models", "stem_ms96_focal_avgc")
LOG = os.path.join(EXP, "experiments", "stem_ms96_focal_avgc.log")
OUT = os.path.join(EXP, "results", "research", "stem_ms96_focal_avgc.json")
EVID = "/root/disk_3tb/EEG-sAAD-Grand-Challenge-Training-Dataset/experiments/decoder_lodo/results/research"
TEST_NAMES = ("AASD", "Carta2026")

STEPS = int(os.environ.get("STEPS", "800"))
BATCH = int(os.environ.get("BATCH", "512"))
FOCAL_GAMMA = float(os.environ.get("FOCAL_GAMMA", "2.0"))
# empty / unset → no α (use recipe pos_weight); set FOCAL_ALPHA=0.25 to enable
_FOCAL_ALPHA_RAW = os.environ.get("FOCAL_ALPHA", "").strip()
FOCAL_ALPHA = float(_FOCAL_ALPHA_RAW) if _FOCAL_ALPHA_RAW else None
SMOKE = os.environ.get("SMOKE", "0") == "1"
EMA_DECAY = 0.995
LR = 8e-4
P_STAY = 0.994
SCALE = 0.8
CFG = ("stem_ms96", "ms", 96, 64, 2, True, LR)
WINDOW = 96
FUSE_W = 0.5  # blend = w * focal + (1-w) * synth
TIP_AVGC = dict(H=0.8192, Acc=75.52)


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 load_init(path, device):
    blob = torch.load(path, map_location="cpu", weights_only=False)
    name, family, window, d_model, nlayers, stem, _lr = blob["cfg"]
    if name != "stem_ms96" or not stem or window != WINDOW:
        raise RuntimeError(f"unexpected stem cfg {blob['cfg']}")
    c_in = int(np.asarray(blob["mu"]).shape[0])
    net = V.LogitTransformer(c_in, window, d_model=d_model, nlayers=nlayers, stem=True)
    good_mask = net.mask.detach().clone()
    net.load_state_dict(blob["state"])
    net.mask.copy_(good_mask)
    if torch.isnan(net.mask).any():
        raise RuntimeError(f"causal mask still has nan after restore from {path}")
    net = net.to(device)
    mu = np.asarray(blob["mu"], np.float32)
    sd = np.asarray(blob["sd"], np.float32)
    return net, mu, sd, list(blob["train"])


def focal_bce(logit, y, m, pos_weight, gamma, alpha=None):
    """Focal BCE + post-switch weights + TV (matches stem recipe skeleton)."""
    sw = V.switch_weights(y, m)
    p = torch.sigmoid(logit)
    pt = p * y + (1.0 - p) * (1.0 - y)
    mod = (1.0 - pt).clamp(0.0, 1.0).pow(gamma)
    if alpha is not None:
        alpha_t = alpha * y + (1.0 - alpha) * (1.0 - y)
        bce = F.binary_cross_entropy_with_logits(logit, y, reduction="none")
        mod = mod * alpha_t
    else:
        bce = F.binary_cross_entropy_with_logits(
            logit, y, pos_weight=pos_weight, reduction="none")
    w = sw * m * mod
    denom = (sw * m).sum().clamp_min(1.0)
    loss = (bce * w).sum() / denom
    dv = (logit[:, 1:] - logit[:, :-1]).abs()
    m2 = m[:, 1:] * m[:, :-1]
    loss = loss + 0.05 * (dv * m2).sum() / m2.sum().clamp_min(1.0)
    mean_mod = float((mod * m).sum().item() / m.sum().clamp_min(1.0).item())
    return loss, mean_mod


def set_lr(opt, step, total, base):
    warm = min(40, max(total // 10, 1))
    if step < warm:
        lr = base * (step + 1) / warm
    else:
        p = (step - warm) / max(total - warm, 1)
        lr = 1e-5 + 0.5 * (base - 1e-5) * (1.0 + math.cos(math.pi * p))
    for group in opt.param_groups:
        group["lr"] = lr
    return lr


def train_focal(model, groups, y_all, mu, sd, device, steps, batch, tag, gamma, alpha):
    pos = float(y_all.mean())
    pos_weight = torch.tensor([(1.0 - pos) / max(pos, 1e-3)], device=device)
    opt = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=1e-4)
    rng = np.random.default_rng(V.TRAIN_SEED)
    ema = copy.deepcopy(model).eval()
    model.train()
    t0 = time.time()
    last = last_mod = None
    for step in range(steps):
        set_lr(opt, step, steps, LR)
        xb, yb, mb = V.sample_batch(rng, groups, WINDOW, batch, mu, sd)
        x = torch.from_numpy(xb).to(device, non_blocking=True)
        y = torch.from_numpy(yb).to(device, non_blocking=True)
        m = torch.from_numpy(mb).to(device, non_blocking=True)
        x = V.augment(x)
        opt.zero_grad(set_to_none=True)
        logit = model(x)
        loss, mean_mod = focal_bce(logit, y, m, pos_weight, gamma, alpha)
        if not torch.isfinite(loss):
            raise RuntimeError(
                f"non-finite loss at step {step} for {tag}: "
                f"loss={loss.item()} mean_mod={mean_mod}")
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()
        V.ema_update(model, ema, EMA_DECAY)
        last = float(loss.item())
        last_mod = mean_mod
        if step == 0 or (step + 1) % 200 == 0 or step + 1 == steps:
            log_line(
                f"    {tag} step {step + 1}/{steps} loss {last:.4f} "
                f"mean_mod {last_mod:.4f} γ {gamma} α {alpha}")
    ema.eval()
    acc = V.train_frame_acc(ema, groups, WINDOW, mu, sd, device)
    log_line(
        f"  trained {tag} loss {last:.4f} mean_mod {last_mod:.4f} "
        f"frame-acc {acc:.3f} γ {gamma} α {alpha} ({time.time() - t0:.0f}s)")
    return ema, dict(
        loss=last, mean_mod=last_mod, frame_acc=acc,
        gamma=gamma, alpha=alpha, n_env=len(groups))


def fit_with_oom(init_path, groups, y_all, device, steps, batch, tag, gamma, alpha, halved=False):
    model, mu, sd, _train = load_init(init_path, device)
    try:
        ema, stats = train_focal(
            model, groups, y_all, mu, sd, device, steps, batch, tag, gamma, alpha)
        return ema, mu, sd, batch, stats
    except torch.cuda.OutOfMemoryError:
        if halved:
            raise
        log_line(f"  OOM on {tag} at batch {batch}; halving once")
        del model
        if device.type == "cuda":
            torch.cuda.empty_cache()
        return fit_with_oom(
            init_path, groups, y_all, device, steps, batch // 2, tag, gamma, alpha,
            halved=True)


def hp30_stream(stream):
    out = {}
    for key, d in stream.items():
        out[key] = V4.highpass(np.asarray(d, np.float64)[:, None]).reshape(-1).astype(np.float64)
    return out


def blend_one(a_stream, b_stream, w):
    out = {}
    for key in a_stream:
        a = np.asarray(a_stream[key], np.float64)
        b = np.asarray(b_stream[key], np.float64)
        n = min(len(a), len(b))
        out[key] = (w * a[:n] + (1.0 - w) * b[:n]).astype(np.float64)
    return out


def score_lodo(model, feat, mu, sd, held, device):
    streams = V.infer_all(model, feat, mu, sd, WINDOW, device)
    ev = N.to_ev(streams)
    off = N.official(held, ev, P_STAY, SCALE)
    hp = {ds: hp30_stream(streams[ds]) for ds in streams}
    off_hp = N.official(held, N.to_ev(hp), P_STAY, SCALE)
    log_line(f"LODO {held} p {P_STAY} sc {SCALE}  H {off['H']:.4f} Acc {off['Acc']:.2f} "
             f"L {off['L']:.3f} SDT {off['SDT']:.2f}")
    log_line(f"LODO_hp30 {held} p {P_STAY} sc {SCALE}  H {off_hp['H']:.4f} Acc {off_hp['Acc']:.2f}")
    return dict(focal=off, hp30=off_hp), streams


def score_external(model, feat_ext, meta, mu_in, sd_in, corpus_streams, corpus_att, device):
    parts = []
    for ds, table in corpus_streams.items():
        labels = corpus_att[ds]
        for key, d in table.items():
            parts.append(np.asarray(d, np.float64) * np.where(labels[key] == 0, 1.0, -1.0))
    mu_e = float(np.concatenate(parts).mean())
    sd_e = float(np.concatenate(parts).std())
    log_line(f"  external emissions mu {mu_e:.4f} sd {sd_e:.4f} scale {SCALE}")

    hp_corpus = {ds: hp30_stream(corpus_streams[ds]) for ds in corpus_streams}
    parts_hp = []
    for ds, table in hp_corpus.items():
        labels = corpus_att[ds]
        for key, d in table.items():
            parts_hp.append(np.asarray(d, np.float64) * np.where(labels[key] == 0, 1.0, -1.0))
    mu_hp = float(np.concatenate(parts_hp).mean())
    sd_hp = float(np.concatenate(parts_hp).std())
    log_line(f"  external hp30 emissions mu {mu_hp:.4f} sd {sd_hp:.4f} scale {SCALE}")

    rows = {}
    for ds in TEST_NAMES:
        stream = V.infer_all(model, {ds: feat_ext[ds]}, mu_in, sd_in, WINDOW, device)[ds]
        ev = {}
        for key, d in stream.items():
            meta_k = meta[ds][key]
            d = np.asarray(d, np.float64)
            ev[key] = dict(r0=d, r1=np.zeros(len(d)), att=meta_k["att"], t_end=meta_k["t_end"],
                           att128=meta_k["att128"], n128=meta_k["n128"], subject=meta_k["subject"])
        r = E.score(ev, mu_e, sd_e * SCALE, P_STAY, 0.75)
        stream_hp = hp30_stream(stream)
        ev_hp = {}
        for key, d in stream_hp.items():
            meta_k = meta[ds][key]
            d = np.asarray(d, np.float64)
            ev_hp[key] = dict(r0=d, r1=np.zeros(len(d)), att=meta_k["att"], t_end=meta_k["t_end"],
                              att128=meta_k["att128"], n128=meta_k["n128"], subject=meta_k["subject"])
        r_hp = E.score(ev_hp, mu_hp, sd_hp * SCALE, P_STAY, 0.75)
        rows[ds] = dict(focal=r, hp30=r_hp)
        log_line(f"EXT {ds} p {P_STAY} sc {SCALE}  H {r['H']:.4f} Acc {r['Acc']:.2f} "
                 f"L {r['L']:.3f} SDT {r['SDT']:.2f}")
        log_line(f"EXT_hp30 {ds} p {P_STAY} sc {SCALE}  H {r_hp['H']:.4f} Acc {r_hp['Acc']:.2f}")
    return rows


def load_external():
    E.CONF.update(prep="eaP_n5_t60", targets=["env", "onset", "dom"])
    logits, meta = {}, {}
    for ds in TEST_NAMES:
        evs = []
        for i in range(4):
            path = os.path.join(EVID, f"ext_clf_{ds}_w10b3sw2P_evidence_s{i}.pkl")
            with open(path, "rb") as fh:
                evs.append(pickle.load(fh))
        logits[ds], meta[ds] = {}, {}
        for key in evs[0]:
            cols = [(ev[key]["r0"] - ev[key]["r1"]).astype(np.float32) for ev in evs]
            e0 = evs[0][key]
            logits[ds][key] = np.stack(cols, 1)
            meta[ds][key] = dict(
                att=np.asarray(e0["att"]), t_end=np.asarray(e0["t_end"], np.float64),
                att128=np.asarray(e0["att128"]), n128=int(e0["n128"]), subject=int(e0["subject"]))
        log_line(f"  external {ds}: {len(logits[ds])} trials")
    return logits, meta


def smoke_gamma(feat_all, device):
    """Short train on held-AVGC fold for γ (and optional α)."""
    held = "AVGC"
    path = os.path.join(INIT_DIR, f"held-{held}.pt")
    train_ds = [d for d in DS_KEYS if d != held]
    groups, y_all = V.trial_groups(feat_all, train_ds)
    gammas = [float(x) for x in os.environ.get("SMOKE_GAMMAS", "1.0,2.0").split(",")]
    # α candidates: None (= recipe pos_weight) plus optional 0.25
    alphas = [None]
    if os.environ.get("SMOKE_ALPHA", "1") == "1":
        alphas.append(0.25)
    smoke_steps = int(os.environ.get("SMOKE_STEPS", "40"))
    results = []
    for gamma in gammas:
        for alpha in alphas:
            tag = f"smoke-γ{gamma}-α{alpha}"
            log_line(f"SMOKE γ={gamma} α={alpha} steps={smoke_steps}")
            try:
                ema, mu, sd, used, stats = fit_with_oom(
                    path, groups, y_all, device, smoke_steps, BATCH, tag, gamma, alpha)
                del ema
                if device.type == "cuda":
                    torch.cuda.empty_cache()
                ok = (stats["loss"] is not None and math.isfinite(stats["loss"])
                      and stats["frame_acc"] > 0.55)
                row = dict(ok=ok, batch=used, **stats)
                results.append(row)
                log_line(
                    f"SMOKE γ={gamma} α={alpha} ok={ok} loss={stats['loss']:.4f} "
                    f"mod={stats['mean_mod']:.4f} frame={stats['frame_acc']:.3f}")
            except Exception as exc:
                log_line(f"SMOKE γ={gamma} α={alpha} FAILED: {exc}")
                results.append(dict(gamma=gamma, alpha=alpha, ok=False, error=str(exc)))
                if device.type == "cuda":
                    torch.cuda.empty_cache()
    ok_rows = [r for r in results if r.get("ok")]
    if not ok_rows:
        raise RuntimeError(f"all smoke γ failed: {results}")

    def score_row(r):
        # Prefer high frame_acc; prefer milder mean_mod (not collapsed to 0)
        return (r["frame_acc"], r["mean_mod"], -abs(r["gamma"] - 1.5))

    best = max(ok_rows, key=score_row)
    log_line(
        f"SMOKE chose γ={best['gamma']} α={best['alpha']} "
        f"frame={best['frame_acc']:.3f} loss={best['loss']:.4f} mod={best['mean_mod']:.4f}")
    return float(best["gamma"]), best["alpha"], results


def score_fuse_lodo(focal_streams, feat_all, held, device):
    """Score w=0.5 blend of focal held streams with frozen synth held ckpt."""
    path = os.path.join(SYNTH_DIR, f"held-{held}.pt")
    if not os.path.isfile(path):
        log_line(f"FUSE skip {held}: missing {path}")
        return None
    synth_net, synth_mu, synth_sd = Fuse.load_ckpt(path, device)
    synth_all = V.infer_all(synth_net, feat_all, synth_mu, synth_sd, WINDOW, device)
    del synth_net
    if device.type == "cuda":
        torch.cuda.empty_cache()
    blended = {}
    for ds in focal_streams:
        blended[ds] = blend_one(focal_streams[ds], synth_all[ds], FUSE_W)
    off = N.official(held, N.to_ev(blended), P_STAY, SCALE)
    log_line(
        f"FUSE_w{FUSE_W} {held} p {P_STAY} sc {SCALE}  "
        f"H {off['H']:.4f} Acc {off['Acc']:.2f}")
    return off


def main():
    os.makedirs(os.path.dirname(LOG), exist_ok=True)
    open(LOG, "w").close()
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    log_line(
        f"device {device} steps {STEPS} batch {BATCH} γ {FOCAL_GAMMA} α {FOCAL_ALPHA} "
        f"init {INIT_DIR} synth {SYNTH_DIR} smoke={SMOKE}")
    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.allow_tf32 = True
    V.assert_causal(device)
    N.load_all()
    feat_all = V.build_features()["ms"]
    os.makedirs(CKPT_DIR, exist_ok=True)

    gamma = FOCAL_GAMMA
    alpha = FOCAL_ALPHA
    smoke_info = None
    if SMOKE or os.environ.get("TUNE_GAMMA", "0") == "1":
        gamma, alpha, smoke_info = smoke_gamma(feat_all, device)
        if SMOKE:
            out = dict(
                smoke=smoke_info, chosen_gamma=gamma, chosen_alpha=alpha,
                init_dir=INIT_DIR)
            os.makedirs(os.path.dirname(OUT), exist_ok=True)
            with open(OUT.replace(".json", "_smoke.json"), "w") as fh:
                json.dump(out, fh, indent=1, default=float)
            log_line("SMOKE done; exiting without full score")
            return

    per = {}
    for held in DS_KEYS:
        path = os.path.join(INIT_DIR, f"held-{held}.pt")
        if not os.path.isfile(path):
            raise FileNotFoundError(path)
        train_ds = [d for d in DS_KEYS if d != held]
        groups, y_all = V.trial_groups(feat_all, train_ds)
        log_line(f"fold held-out={held} init {path} γ={gamma} α={alpha}")
        ema, mu, sd, used, stats = fit_with_oom(
            path, groups, y_all, device, STEPS, BATCH, f"held-{held}", gamma, alpha)
        torch.save(
            {"state": ema.state_dict(), "mu": mu, "sd": sd, "init": path,
             "train": train_ds, "steps": STEPS, "batch": used,
             "focal_gamma": gamma, "focal_alpha": alpha, "stats": stats, "cfg": CFG},
            os.path.join(CKPT_DIR, f"held-{held}.pt"))
        scores, streams = score_lodo(ema, feat_all, mu, sd, held, device)
        fuse_off = score_fuse_lodo(streams, feat_all, held, device)
        if fuse_off is not None:
            scores["fuse_w05"] = fuse_off
        per[held] = dict(scores=scores, stats=stats, batch=used)
        del ema
        if device.type == "cuda":
            torch.cuda.empty_cache()

    log_line(f"all-5 focal fine-tune for AASD and Carta, "
             f"init {INIT_DIR}/all5.pt γ={gamma} α={alpha}")
    groups, y_all = V.trial_groups(feat_all, list(DS_KEYS))
    all_path = os.path.join(INIT_DIR, "all5.pt")
    ema, mu, sd, used, stats = fit_with_oom(
        all_path, groups, y_all, device, STEPS, BATCH, "all5", gamma, alpha)
    torch.save(
        {"state": ema.state_dict(), "mu": mu, "sd": sd, "init": all_path,
         "train": list(DS_KEYS), "steps": STEPS, "batch": used,
         "focal_gamma": gamma, "focal_alpha": alpha, "stats": stats, "cfg": CFG},
        os.path.join(CKPT_DIR, "all5.pt"))
    corpus_streams = V.infer_all(ema, feat_all, mu, sd, WINDOW, device)
    ext_logits, ext_meta = load_external()
    ext_feat = V4.build_features_from(ext_logits)["ms"]
    ext = score_external(ema, ext_feat, ext_meta, mu, sd, corpus_streams, N.G["att"], device)

    # External fuse w=0.5 with synth all5
    fuse_ext = None
    synth_all5 = os.path.join(SYNTH_DIR, "all5.pt")
    if os.path.isfile(synth_all5):
        synth_net, synth_mu, synth_sd = Fuse.load_ckpt(synth_all5, device)
        synth_corpus = V.infer_all(synth_net, feat_all, synth_mu, synth_sd, WINDOW, device)
        synth_ext = V.infer_all(synth_net, ext_feat, synth_mu, synth_sd, WINDOW, device)
        del synth_net
        if device.type == "cuda":
            torch.cuda.empty_cache()
        blend_corpus = {
            ds: blend_one(corpus_streams[ds], synth_corpus[ds], FUSE_W)
            for ds in corpus_streams}
        parts = []
        for ds, table in blend_corpus.items():
            labels = N.G["att"][ds]
            for key, d in table.items():
                parts.append(np.asarray(d, np.float64) * np.where(labels[key] == 0, 1.0, -1.0))
        mu_e = float(np.concatenate(parts).mean())
        sd_e = float(np.concatenate(parts).std())
        # Re-infer focal external streams once for fuse (all5 EMA still in memory)
        focal_ext = V.infer_all(ema, ext_feat, mu, sd, WINDOW, device)
        fuse_ext = {}
        for ds in TEST_NAMES:
            blend_stream = blend_one(focal_ext[ds], synth_ext[ds], FUSE_W)
            ev = {}
            for key, d in blend_stream.items():
                meta_k = ext_meta[ds][key]
                d = np.asarray(d, np.float64)
                ev[key] = dict(
                    r0=d, r1=np.zeros(len(d)), att=meta_k["att"], t_end=meta_k["t_end"],
                    att128=meta_k["att128"], n128=meta_k["n128"], subject=meta_k["subject"])
            r = E.score(ev, mu_e, sd_e * SCALE, P_STAY, 0.75)
            fuse_ext[ds] = r
            log_line(
                f"FUSE_w{FUSE_W} EXT {ds} p {P_STAY} sc {SCALE}  "
                f"H {r['H']:.4f} Acc {r['Acc']:.2f}")
        del ema
    else:
        del ema
        log_line(f"FUSE ext skipped; missing {synth_all5}")

    mean_h = float(np.mean([per[d]["scores"]["focal"]["H"] for d in DS_KEYS]))
    mean_acc = float(np.mean([per[d]["scores"]["focal"]["Acc"] for d in DS_KEYS]))
    log_line(f"LODO mean H {mean_h:.4f} Acc {mean_acc:.2f}")
    avgc = per["AVGC"]["scores"]["focal"]
    log_line(
        f"AVGC focal {avgc['H']:.4f}/{avgc['Acc']:.2f} vs tip "
        f"{TIP_AVGC['H']:.4f}/{TIP_AVGC['Acc']:.2f} "
        f"ΔH {avgc['H'] - TIP_AVGC['H']:+.4f} ΔAcc {avgc['Acc'] - TIP_AVGC['Acc']:+.2f}")
    if "fuse_w05" in per["AVGC"]["scores"]:
        fav = per["AVGC"]["scores"]["fuse_w05"]
        log_line(
            f"AVGC fuse_w{FUSE_W} {fav['H']:.4f}/{fav['Acc']:.2f} vs tip "
            f"{TIP_AVGC['H']:.4f}/{TIP_AVGC['Acc']:.2f} "
            f"ΔH {fav['H'] - TIP_AVGC['H']:+.4f} ΔAcc {fav['Acc'] - TIP_AVGC['Acc']:+.2f}")
        fuse_mean_h = float(np.mean([per[d]["scores"]["fuse_w05"]["H"] for d in DS_KEYS
                                     if "fuse_w05" in per[d]["scores"]]))
        fuse_mean_acc = float(np.mean([per[d]["scores"]["fuse_w05"]["Acc"] for d in DS_KEYS
                                       if "fuse_w05" in per[d]["scores"]]))
        log_line(f"FUSE_w{FUSE_W} LODO mean H {fuse_mean_h:.4f} Acc {fuse_mean_acc:.2f}")
    else:
        fuse_mean_h = fuse_mean_acc = None

    out = dict(
        p_stay=P_STAY, scale=SCALE, steps=STEPS, batch=BATCH,
        focal_gamma=gamma, focal_alpha=alpha, init_dir=INIT_DIR,
        synth_dir=SYNTH_DIR, fuse_w=FUSE_W, smoke=smoke_info,
        tip_avgc=TIP_AVGC,
        lodo={d: per[d]["scores"] for d in DS_KEYS},
        lodo_stats={d: per[d]["stats"] for d in DS_KEYS},
        lodo_mean=dict(H=mean_h, Acc=mean_acc),
        fuse_lodo_mean=(dict(H=fuse_mean_h, Acc=fuse_mean_acc)
                        if fuse_mean_h is not None else None),
        external=ext,
        fuse_external=fuse_ext,
        all5_stats=stats,
    )
    os.makedirs(os.path.dirname(OUT), exist_ok=True)
    with open(OUT, "w") as fh:
        json.dump(out, fh, indent=1, default=float)
    log_line(f"wrote {OUT}")


if __name__ == "__main__":
    main()
