"""Freeze SWA stem_ms96 encoder; train a residual causal GRU on post-encoder features.

Init from models/stem_ms96_swa/held-*.pt (and all5). Gate starts at 0 so step-0
matches the frozen SWA forward. Only GRU + gate + head + skip are trainable.

HMM preset p_stay 0.994 scale 0.8. Also report causal tau-30 high-pass readout.

usage:
  flock multi_agent_opt/gpu.lock python -u stem_ms96_frozen_gru.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__))
SWA_DIR = os.path.join(EXP, "models", "stem_ms96_swa")
CKPT_DIR = os.path.join(EXP, "models", "stem_ms96_frozen_gru")
LOG = os.path.join(EXP, "experiments", "stem_ms96_frozen_gru.log")
OUT = os.path.join(EXP, "results", "research", "stem_ms96_frozen_gru.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", "1000"))
BATCH = int(os.environ.get("BATCH", "512"))
LR = float(os.environ.get("LR", "8e-4"))
P_STAY = 0.994
SCALE = 0.8
WINDOW = 96
CFG = ("stem_ms96_frozen_gru", "ms", 96, 64, 2, True, LR)


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


class FrozenGRUStem(nn.Module):
    """Frozen LogitTransformer body + residual gated GRU before the head."""

    def __init__(self, base: V.LogitTransformer):
        super().__init__()
        self.base = base
        for p in self.base.parameters():
            p.requires_grad = False
        d_model = base.head.in_features
        self.gru = nn.GRU(d_model, d_model, num_layers=1, batch_first=True)
        # Small nonzero init so the residual branch gets gradients. A zero gate
        # with a zero GRU blocks learning entirely (dL/dGRU = 0 when scale=0).
        for name, p in self.gru.named_parameters():
            if "weight" in name:
                nn.init.xavier_uniform_(p, gain=0.01)
            else:
                nn.init.zeros_(p)
        # softplus(-3) ≈ 0.05: step-0 close to SWA, but grads reach the GRU.
        self.gate = nn.Parameter(torch.tensor(-3.0))
        for p in self.base.head.parameters():
            p.requires_grad = True
        for p in self.base.skip.parameters():
            p.requires_grad = True

    def encode(self, x):
        raw = x
        b = self.base
        if b.dw is not None:
            x = x + b.dw(F.pad(x.transpose(1, 2), (b.dw_pad, 0))).transpose(1, 2)
        h = b.proj(x)
        for block in b.blocks:
            h = block(h)
        h = h + b.pos[:, : h.size(1)]
        h = b.enc(h, mask=b.mask)
        return h, raw

    def forward(self, x):
        h, raw = self.encode(x)
        h2, _ = self.gru(h)
        h = h + F.softplus(self.gate) * h2
        return self.base.head(h).squeeze(-1) + self.base.skip(raw).squeeze(-1)

    def trainable_parameters(self):
        for p in self.parameters():
            if p.requires_grad:
                yield p


def load_swa_wrapped(path, device):
    blob = torch.load(path, map_location="cpu", weights_only=False)
    c_in = int(np.asarray(blob["mu"]).shape[0])
    base = V.LogitTransformer(c_in, WINDOW, d_model=64, nlayers=2, stem=True)
    base.load_state_dict(blob["state"])
    net = FrozenGRUStem(base).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 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_fold(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.trainable_parameters(), lr=LR, weight_decay=1e-4)
    rng = np.random.default_rng(V.TRAIN_SEED)
    ema = copy.deepcopy(model).eval()
    model.train()
    # keep frozen parts in eval for BN-free modules; GRU/head train
    model.base.eval()
    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_(list(model.trainable_parameters()), 1.0)
        opt.step()
        V.ema_update(model, ema, 0.995)
        last = float(loss.item())
        if step == 0 or (step + 1) % 200 == 0 or step + 1 == steps:
            g = float(F.softplus(model.gate).detach().cpu())
            log_line(f"    {tag} step {step + 1}/{steps} loss {last:.4f} softplus(gate) {g:.4f}")
    ema.eval()
    acc = V.train_frame_acc(ema, groups, WINDOW, mu, sd, device)
    log_line(f"  trained {tag} loss {last:.4f} frame-acc {acc:.3f} ({time.time() - t0:.0f}s)")
    return ema


def fit_with_oom(path, groups, y_all, device, steps, batch, tag, halved=False):
    model, mu, sd, _ = load_swa_wrapped(path, device)
    try:
        ema = train_fold(model, groups, y_all, mu, sd, device, steps, batch, tag)
        return ema, mu, sd, batch
    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(path, groups, y_all, device, steps, batch // 2, tag, 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 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}")
    log_line(f"LODO_hp30 {held} p {P_STAY} sc {SCALE}  H {off_hp['H']:.4f} Acc {off_hp['Acc']:.2f}")
    return dict(gru=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())
    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())
    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)
        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(gru=r, hp30=r_hp)
        log_line(f"EXT {ds} H {r['H']:.4f} Acc {r['Acc']:.2f} | hp30 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"]))
    return logits, meta


def write_results_md(out):
    path = os.path.join(EXP, "multi_agent_opt", "results_stem_next.md")
    lines = [
        "# results_stem_next — frozen SWA encoder + residual GRU",
        "",
        "Init `models/stem_ms96_swa`. Freeze body; train GRU (zero-init) + tanh(gate) residual + head/skip.",
        f"STEPS={STEPS} BATCH={BATCH} HMM {P_STAY}/{SCALE}.",
        "",
        "| Set | GRU H/Acc | hp30 H/Acc |",
        "|---|---:|---:|",
    ]
    for d in DS_KEYS:
        g = out["lodo"][d]["gru"]
        h = out["lodo"][d]["hp30"]
        lines.append(f"| {d} | {g['H']:.4f}/{g['Acc']:.2f} | {h['H']:.4f}/{h['Acc']:.2f} |")
    m = out["lodo_mean"]
    lines.append(f"| **mean** | **{m['H']:.4f}/{m['Acc']:.2f}** | — |")
    for ds in TEST_NAMES:
        g = out["external"][ds]["gru"]
        h = out["external"][ds]["hp30"]
        lines.append(f"| {ds} | {g['H']:.4f}/{g['Acc']:.2f} | {h['H']:.4f}/{h['Acc']:.2f} |")
    lines += [
        "",
        "Refs: fuse LODO 0.8725/82.58 AVGC 0.8100/75.14; linear_hp30 AASD 0.6422/53.12 Carta 0.6520/60.54.",
        "",
    ]
    with open(path, "w") as fh:
        fh.write("\n".join(lines))
    log_line(f"wrote {path}")


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} LR {LR}")
    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)

    # step-0 identity check on one batch
    probe_path = os.path.join(SWA_DIR, "held-AVGC.pt")
    if not os.path.isfile(probe_path):
        raise FileNotFoundError(probe_path)
    wrapped, mu0, sd0, _ = load_swa_wrapped(probe_path, device)
    base_only = V.LogitTransformer(int(mu0.shape[0]), WINDOW, d_model=64, nlayers=2, stem=True)
    base_only.load_state_dict(torch.load(probe_path, map_location="cpu", weights_only=False)["state"])
    base_only = base_only.to(device).eval()
    wrapped.eval()
    with torch.no_grad():
        xb, _, _ = V.sample_batch(np.random.default_rng(0), V.trial_groups(feat_all, ["DTU"])[0], WINDOW, 8, mu0, sd0)
        xt = torch.from_numpy(xb).to(device)
        d0 = (wrapped(xt) - base_only(xt)).abs().max().item()
    log_line(f"step0 max|wrapped-swa|={d0:.3e} (softplus gate≈0.05; expect small)")
    del wrapped, base_only
    if device.type == "cuda":
        torch.cuda.empty_cache()

    per = {}
    for held in DS_KEYS:
        path = os.path.join(SWA_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)
        log_line(f"fold held-out={held} from {path}")
        ema, mu, sd, used = fit_with_oom(path, groups, y_all, device, STEPS, BATCH, f"held-{held}")
        torch.save({"state": ema.state_dict(), "mu": mu, "sd": sd, "swa": path,
                    "train": train_ds, "steps": STEPS, "batch": used, "cfg": CFG},
                   os.path.join(CKPT_DIR, f"held-{held}.pt"))
        scores, _ = score_lodo(ema, feat_all, mu, sd, held, device)
        per[held] = dict(scores=scores, batch=used)
        del ema
        if device.type == "cuda":
            torch.cuda.empty_cache()

    log_line("all-5 frozen-GRU for external, init SWA all5.pt")
    groups, y_all = V.trial_groups(feat_all, list(DS_KEYS))
    all_path = os.path.join(SWA_DIR, "all5.pt")
    if not os.path.isfile(all_path):
        all_path = os.path.join(SWA_DIR, "held-AVGC.pt")
    ema, mu, sd, used = fit_with_oom(all_path, groups, y_all, device, STEPS, BATCH, "all5")
    torch.save({"state": ema.state_dict(), "mu": mu, "sd": sd, "swa": all_path,
                "train": list(DS_KEYS), "steps": STEPS, "batch": used, "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)

    mean_h = float(np.mean([per[d]["scores"]["gru"]["H"] for d in DS_KEYS]))
    mean_acc = float(np.mean([per[d]["scores"]["gru"]["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,
        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)
    write_results_md(out)
    log_line(f"wrote {OUT}")


if __name__ == "__main__":
    main()
