"""T3 CF-Null fine-tune/evaluation driver on the honest SW2 classifier."""
from __future__ import annotations

import os
import time

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

import clf_noise_aug_ft_lodo as B
import decoders
import direct_classifier as DC
from common_exp import CFG, EXP, FS, resolve_model
from decoders import D, DEV

LAMBDA = float(os.environ.get("CFNULL_LAMBDA", "0.1"))
SHIFT = int(20 * FS)


def null_eeg_batch(trials, trial_idx, starts, rng):
    out = np.empty((len(trial_idx), DC.W, 58), np.float32)
    for j, (ti, start) in enumerate(zip(trial_idx, starts)):
        ti, start = int(ti), int(start)
        if rng.random() < 0.5 and start >= SHIFT:
            out[j] = trials[ti]["eeg"][start - SHIFT:start - SHIFT + DC.W]
            continue
        choices = [k for k, tr in enumerate(trials) if k != ti and len(tr["eeg"]) >= DC.W]
        other = int(rng.choice(choices))
        max_start = len(trials[other]["eeg"]) - DC.W
        s = int(rng.integers(0, max_start + 1))
        out[j] = trials[other]["eeg"][s:s + DC.W]
    return torch.from_numpy(out)


def fit_net(train, val, log, a):
    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)
    init_from = resolve_model(a.init_from)
    net.load_state_dict(torch.load(init_from, map_location=DEV, weights_only=False))
    log(f"  CF-Null init {init_from}; lambda={LAMBDA} shift={SHIFT / FS:.1f}s")
    aug = decoders.DNNDec.__new__(decoders.DNNDec)
    aug.W, aug.fut, aug.hop, aug.C = DC.W, DC.FUT, DC.HOP, 58
    rng = np.random.default_rng(seed)
    xv, sv, yv = DC.windows(val, D["val_windows"], rng, None, a.p_switch, False)
    opt = torch.optim.AdamW(net.parameters(), lr=D["lr"], weight_decay=D["weight_decay"])
    best, state = np.inf, None
    started = time.time()
    for epoch in range(D["max_epochs"]):
        losses, null_terms = [], []
        net.train()
        for _ in range(D["steps_per_epoch"]):
            x, s, y = DC.windows(train, D["batch_size"], rng, aug, a.p_switch, False)
            xn = null_eeg_batch(train, DC.windows.last_ti, DC.windows.last_start, rng)
            x, xn, s, y = x.to(DEV), xn.to(DEV), s.to(DEV), y.to(DEV)
            main = F.binary_cross_entropy_with_logits(net(x, s), y)
            null = net(xn, s).square().mean()
            loss = main + LAMBDA * null
            opt.zero_grad(set_to_none=True)
            loss.backward()
            torch.nn.utils.clip_grad_norm_(net.parameters(), 5.0)
            opt.step()
            losses.append(float(main.detach()))
            null_terms.append(float(null.detach()))
        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)
            ])
        val = float(F.binary_cross_entropy_with_logits(lv, yv))
        acc = float(((lv > 0).float() == yv).float().mean())
        log(
            f"    epoch {epoch:02d} main {np.mean(losses):.4f} "
            f"null {np.mean(null_terms):.4f} val {val:.4f} acc {acc:.3f} "
            f"({time.time() - started:.0f}s)"
        )
        if val < best:
            best = val
            state = {k: v.detach().clone() for k, v in net.state_dict().items()}
    net.load_state_dict(state)
    net.eval()
    return net, best


def main():
    tag = f"cfnull_l{str(LAMBDA).replace('.', 'p')}"
    B.TAG_BASE = f"_w10b3_ptSW2_{tag}_aug-sw2"
    B.EXT_TAG = f"_w10b3_{tag}_aug-sw2"
    B.LOG_PATH = os.path.join(EXP, "experiments", f"{tag}.log")
    B.OUT_JSON = os.path.join(EXP, "results", "research", f"{tag}.json")
    B.RESULTS_MD = os.path.join(EXP, "multi_agent_opt", f"results_{tag}.md")
    B.CKPT_ROOT = os.path.join(EXP, "models", tag)
    B.NOISE_AUG = {
        "p_chan_mask": 0.0, "p_chan": 0.2, "gain": 0.25, "noise": 0.1,
        "p_zero_prefix": 0.1, "p_cluster": 0.3, "cluster_min": 3,
        "cluster_max": 8, "p_tilt": 0.0, "tilt": 0.0,
        "p_time_mask": 0.0, "time_mask_max_s": 0.0, "n_time_masks": 0,
        "p_freq_mask": 0.0, "freq_mask_hz": 0.0, "n_freq_masks": 0,
        "clf_p_switch2": B.P_SWITCH2,
    }
    B.fit_net = fit_net
    B.mark_claim = lambda *args, **kwargs: None
    B.append_already = lambda *args, **kwargs: None
    B.update_board = lambda *args, **kwargs: None
    B.main()


if __name__ == "__main__":
    main()
