"""Path B: longer SWA (2000 steps, avg last 400) — distinct from SWA-1000/last-200.

Init from models/stem_ms96_swa/held-*.pt when present, else published stem_ms96.
Same stem_ms96 architecture/recipe. Score LODO + AASD + Carta + hp30.

usage:
  STEPS=2000 SWA_STEPS=400 python stem_ms96_swa2k.py
"""
import copy
import json
import math
import os
import pickle
import time

import numpy as np
import torch
import torch.nn as nn
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
from common import DS_KEYS

EXP = os.path.dirname(os.path.abspath(__file__))
STEM_DIR = os.path.join(EXP, "models", "logit_tf_v2")
CKPT_DIR = os.path.join(EXP, "models", "stem_ms96_swa2k")
LOG = os.path.join(EXP, "experiments", "stem_ms96_swa2k.log")
OUT = os.path.join(EXP, "results", "research", "stem_ms96_swa2k.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", "2000"))
BATCH = int(os.environ.get("BATCH", "512"))
SWA_STEPS = int(os.environ.get("SWA_STEPS", "400"))
SWA_DECAY = float(os.environ.get("SWA_DECAY", "0.0"))  # 0 = equal average; ~0.99 = Polyak
LR = 8e-4
P_STAY = 0.994
SCALE = 0.8
CFG = ("stem_ms96", "ms", 96, 64, 2, True, LR)
WINDOW = 96


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")


SWA1_DIR = os.path.join(EXP, "models", "stem_ms96_swa")


def resolve_init(held):
    """Prefer prior SWA-1000 held/all5; else published stem_ms96."""
    if held == "all5":
        cand = [
            os.path.join(SWA1_DIR, "all5.pt"),
            os.path.join(STEM_DIR, "stem_ms96__held-AVGC.pt"),
        ]
    else:
        cand = [
            os.path.join(SWA1_DIR, f"held-{held}.pt"),
            os.path.join(STEM_DIR, f"stem_ms96__held-{held}.pt"),
        ]
    for path in cand:
        if os.path.exists(path):
            return path
    raise FileNotFoundError(f"no init for {held}: {cand}")


def restore_causal_mask(net):
    """SWA equal-avg of float buffers turns causal -inf mask entries into nan."""
    good = torch.triu(torch.full_like(net.mask, float("-inf")), diagonal=1)
    net.mask.copy_(good)
    if torch.isnan(net.mask).any():
        raise RuntimeError("causal mask still has nan after restore")


def load_stem(path, device):
    blob = torch.load(path, map_location="cpu", weights_only=False)
    cfg = blob.get("cfg", CFG)
    name, family, window, d_model, nlayers, stem, _lr = cfg
    if name != "stem_ms96" or not stem or window != WINDOW:
        raise RuntimeError(f"unexpected stem cfg {cfg} from {path}")
    c_in = int(np.asarray(blob["mu"]).shape[0])
    net = V.LogitTransformer(c_in, window, d_model=d_model, nlayers=nlayers, stem=True)
    # Keep constructed causal mask; SWA-1k state may have nan in mask buffer.
    good_mask = net.mask.detach().clone()
    net.load_state_dict(blob["state"])
    net.mask.copy_(good_mask)
    restore_causal_mask(net)
    net = net.to(device)
    mu = np.asarray(blob["mu"], np.float32)
    sd = np.asarray(blob["sd"], np.float32)
    return net, mu, sd, list(blob.get("train", []))


def swa_update(src, dst, n_averaged, decay):
    """Equal average when decay==0; otherwise Polyak with the given decay.

    Skip the causal `mask` buffer: averaging -inf yields nan (see IRM restore).
    """
    with torch.no_grad():
        if decay > 0:
            for ps, pd in zip(src.parameters(), dst.parameters()):
                pd.mul_(decay).add_(ps, alpha=1.0 - decay)
            for (name, bs), bd in zip(src.named_buffers(), dst.buffers()):
                if name == "mask" or not bd.is_floating_point():
                    bd.copy_(bs)
                else:
                    bd.mul_(decay).add_(bs, alpha=1.0 - decay)
            return n_averaged + 1
        # equal average: dst = dst + (src - dst) / (n+1)
        n = n_averaged + 1
        for ps, pd in zip(src.parameters(), dst.parameters()):
            pd.add_(ps - pd, alpha=1.0 / n)
        for (name, bs), bd in zip(src.named_buffers(), dst.buffers()):
            if name == "mask" or not bd.is_floating_point():
                bd.copy_(bs)
            else:
                bd.add_(bs - bd, alpha=1.0 / n)
        return n


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_swa(model, groups, y_all, mu, sd, device, steps, batch, tag):
    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)
    swa_start = max(0, steps - SWA_STEPS)
    swa = copy.deepcopy(model).eval()
    n_avg = 0
    model.train()
    t0 = time.time()
    last = 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)
        sw = V.switch_weights(y, m)
        bce = F.binary_cross_entropy_with_logits(logit, y, pos_weight=pos_weight, reduction="none")
        denom = (sw * m).sum().clamp_min(1.0)
        loss = (bce * sw * m).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)
        if not torch.isfinite(loss):
            raise RuntimeError(f"non-finite loss at step {step} for {tag}")
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()
        last = float(loss.item())
        if step >= swa_start:
            if n_avg == 0:
                swa.load_state_dict(copy.deepcopy(model.state_dict()))
                n_avg = 1
            else:
                n_avg = swa_update(model, swa, n_avg, SWA_DECAY)
        if step == 0 or (step + 1) % 200 == 0 or step + 1 == steps:
            log_line(f"    {tag} step {step + 1}/{steps} loss {last:.4f} swa_n {n_avg}")
    restore_causal_mask(swa)
    swa.eval()
    acc = V.train_frame_acc(swa, groups, WINDOW, mu, sd, device)
    log_line(f"  trained {tag} loss {last:.4f} frame-acc {acc:.3f} swa_n {n_avg} ({time.time() - t0:.0f}s)")
    return swa, n_avg


def fit_with_oom(stem_path, groups, y_all, device, steps, batch, tag, halved=False):
    model, mu, sd, _train = load_stem(stem_path, device)
    try:
        swa, n_avg = train_swa(model, groups, y_all, mu, sd, device, steps, batch, tag)
        return swa, mu, sd, batch, n_avg
    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(stem_path, groups, y_all, device, steps, batch // 2, tag, halved=True)


def hp30_stream(stream):
    """Causal tau-30 high-pass of a single evidence stream (same as linear_hp30 on 1 channel)."""
    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 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}
    ev_hp = N.to_ev(hp)
    off_hp = N.official(held, 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(swa=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}")

    # also fit emissions on hp30 corpus streams for the hp30 external readout
    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():
            m = meta[ds][key]
            d = np.asarray(d, np.float64)
            ev[key] = dict(r0=d, r1=np.zeros(len(d)), att=m["att"], t_end=m["t_end"],
                           att128=m["att128"], n128=m["n128"], subject=m["subject"])
        r = E.score(ev, mu_e, sd_e * SCALE, P_STAY, 0.75)
        # hp30 of SWA logits
        stream_hp = hp30_stream(stream)
        ev_hp = {}
        for key, d in stream_hp.items():
            m = meta[ds][key]
            d = np.asarray(d, np.float64)
            ev_hp[key] = dict(r0=d, r1=np.zeros(len(d)), att=m["att"], t_end=m["t_end"],
                              att128=m["att128"], n128=m["n128"], subject=m["subject"])
        r_hp = E.score(ev_hp, mu_hp, sd_hp * SCALE, P_STAY, 0.75)
        rows[ds] = dict(swa=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 main():
    # wipe log for a clean run
    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} swa_steps {SWA_STEPS} swa_decay {SWA_DECAY}")
    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)

    per = {}
    corpus_for_ext = None
    for held in DS_KEYS:
        path = resolve_init(held)
        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} from {path}")
        swa, mu, sd, used, n_avg = fit_with_oom(
            path, groups, y_all, device, STEPS, BATCH, f"held-{held}")
        torch.save({"state": swa.state_dict(), "mu": mu, "sd": sd, "stem": path,
                    "train": train_ds, "steps": STEPS, "batch": used, "swa_n": n_avg,
                    "swa_steps": SWA_STEPS, "swa_decay": SWA_DECAY, "cfg": CFG},
                   os.path.join(CKPT_DIR, f"held-{held}.pt"))
        scores, streams = score_lodo(swa, feat_all, mu, sd, held, device)
        per[held] = dict(scores=scores, swa_n=n_avg, batch=used)
        del swa
        if device.type == "cuda":
            torch.cuda.empty_cache()

    # all-5 fine-tune for external (prefer prior SWA all5)
    all_path = resolve_init("all5")
    log_line(f"all-5 SWA-2k fine-tune for AASD and Carta, init {all_path}")
    groups, y_all = V.trial_groups(feat_all, list(DS_KEYS))
    swa, mu, sd, used, n_avg = fit_with_oom(
        all_path, groups, y_all, device, STEPS, BATCH, "all5")
    torch.save({"state": swa.state_dict(), "mu": mu, "sd": sd, "stem": all_path,
                "train": list(DS_KEYS), "steps": STEPS, "batch": used, "swa_n": n_avg,
                "swa_steps": SWA_STEPS, "swa_decay": SWA_DECAY, "cfg": CFG},
               os.path.join(CKPT_DIR, "all5.pt"))
    corpus_streams = V.infer_all(swa, feat_all, mu, sd, WINDOW, device)
    ext_logits, ext_meta = load_external()
    ext_feat = V4.build_features_from(ext_logits)["ms"]
    ext = score_external(swa, ext_feat, ext_meta, mu, sd, corpus_streams, N.G["att"], device)

    mean_h = float(np.mean([per[d]["scores"]["swa"]["H"] for d in DS_KEYS]))
    mean_acc = float(np.mean([per[d]["scores"]["swa"]["Acc"] for d in DS_KEYS]))
    log_line(f"LODO mean H {mean_h:.4f} Acc {mean_acc:.2f}")

    out = dict(
        p_stay=P_STAY, scale=SCALE, steps=STEPS, batch=BATCH,
        swa_steps=SWA_STEPS, swa_decay=SWA_DECAY,
        lodo={d: per[d]["scores"] for d in DS_KEYS},
        lodo_mean=dict(H=mean_h, Acc=mean_acc),
        external=ext,
    )
    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}")
    md = os.path.join(EXP, "multi_agent_opt", "results_swa2k.md")
    lines = [
        "# results_swa2k",
        "",
        f"**Path B: SWA-2000 / last-{SWA_STEPS}** fine-tune of stem_ms96 (init prior SWA-1000 when present). "
        f"Distinct from completed SWA last-200 of 1000. Equal avg (decay={SWA_DECAY}).",
        "",
        f"STEPS={STEPS} SWA_STEPS={SWA_STEPS} BATCH={BATCH}. HMM p_stay {P_STAY} scale {SCALE}. Also causal hp30.",
        "",
        f"Code: `stem_ms96_swa2k.py`. Checkpoints: `models/stem_ms96_swa2k/`. JSON: `{OUT}`.",
        "",
        "## LODO (preset)",
        "",
        "| Held-out | H | Acc % | hp30 H/Acc |",
        "|---|---:|---:|---|",
    ]
    for d in DS_KEYS:
        r = per[d]["scores"]["swa"]; h = per[d]["scores"]["hp30"]
        lines.append(f"| {d} | {r['H']:.4f} | {r['Acc']:.2f} | {h['H']:.4f}/{h['Acc']:.2f} |")
    lines += [
        f"| **mean** | **{mean_h:.4f}** | **{mean_acc:.2f}** | |",
        "",
        "## External (preset)",
        "",
        "| Set | H | Acc % | hp30 H/Acc | linear_hp30 | SWA-1k |",
        "|---|---:|---:|---|---|---|",
        f"| AASD | {ext['AASD']['swa']['H']:.4f} | {ext['AASD']['swa']['Acc']:.2f} | "
        f"{ext['AASD']['hp30']['H']:.4f}/{ext['AASD']['hp30']['Acc']:.2f} | 0.6422/53.12 | 0.6202/51.08 |",
        f"| Carta2026 | {ext['Carta2026']['swa']['H']:.4f} | {ext['Carta2026']['swa']['Acc']:.2f} | "
        f"{ext['Carta2026']['hp30']['H']:.4f}/{ext['Carta2026']['hp30']['Acc']:.2f} | 0.6520/60.54 | 0.5507/48.68 |",
        "",
        "## Targets",
        "",
        "| Target | Result |",
        "|---|---|",
        f"| AVGC H>=0.85 Acc>=78 | "
        f"{'met' if per['AVGC']['scores']['swa']['H']>=0.85 and per['AVGC']['scores']['swa']['Acc']>=78 else 'miss'} "
        f"({per['AVGC']['scores']['swa']['H']:.4f}/{per['AVGC']['scores']['swa']['Acc']:.2f}) |",
        f"| UHD H>=0.85 | "
        f"{'met' if per['UHD']['scores']['swa']['H']>=0.85 else 'miss'} "
        f"({per['UHD']['scores']['swa']['H']:.4f}) |",
        f"| AASD Acc>60 | "
        f"{'met' if ext['AASD']['swa']['Acc']>60 else 'miss'} "
        f"({ext['AASD']['swa']['H']:.4f}/{ext['AASD']['swa']['Acc']:.2f}) |",
        f"| vs SWA-1k 0.8700/82.61 | {mean_h:.4f}/{mean_acc:.2f} |",
        f"| vs IRM AVGC 0.8095/75.12 | AVGC {per['AVGC']['scores']['swa']['H']:.4f}/{per['AVGC']['scores']['swa']['Acc']:.2f} |",
        "",
    ]
    open(md, "w").write("\n".join(lines) + "\n")
    log_line(f"wrote {md}")


if __name__ == "__main__":
    main()
