"""Smoke: raw vlaai_ws vs filterbank-EEG vlaai_ws learning speed."""
import numpy as np
import torch
import torch.nn.functional as F
from scipy.signal import butter, sosfilt

import decoders
import direct_classifier as DC
from common_exp import CFG, FS, load_trial, rows_of
from decoders import D, DEV, _targets

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["batch_size"] = 64
D["model_blocks"] = 3
BANDS = ((1.0, 3.0), (3.0, 5.0), (5.0, 7.0), (7.0, 9.0))


def fb(eeg):
    x = eeg.astype(np.float64)
    parts = [
        sosfilt(butter(2, [lo, hi], "bandpass", fs=FS, output="sos"), x, axis=0).astype(np.float32)
        for lo, hi in BANDS
    ]
    return np.concatenate(parts, -1)


def main():
    rows = rows_of("DTU")
    train = [load_trial("eaP_n5_t60", r["key"]) for _, r in rows.iterrows()]
    for tr in train:
        tr["_S"] = _targets(tr)
    e = train[0]["eeg"]
    f = fb(e)
    print(
        "raw_std", float(e.std()), "fb_std", float(f.std()), "fb_shape", f.shape,
        "band_stds", [float(f[:, i * 58:(i + 1) * 58].std()) for i in range(4)],
        flush=True,
    )
    aug = decoders.DNNDec.__new__(decoders.DNNDec)
    aug.W, aug.fut, aug.hop, aug.C = DC.W, DC.FUT, DC.HOP, 58

    def smoke(label, get_batch, steps=80):
        torch.manual_seed(0)
        rs = np.random.default_rng(0)
        X0, S0, y0 = get_batch(rs)
        C = X0.shape[-1]
        net = DC.DirectNet(C, 3, "vlaai_ws").to(DEV)
        opt = torch.optim.AdamW(net.parameters(), lr=5e-4, weight_decay=5e-4)
        losses = []
        net.train()
        for _ in range(steps):
            X, S, y = [z.to(DEV) for z in get_batch(rs)]
            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)
            opt.step()
            losses.append(float(loss.detach()))
        print(
            label, "C", C, "params", sum(p.numel() for p in net.parameters()),
            "first20", round(float(np.mean(losses[:20])), 4),
            "last20", round(float(np.mean(losses[-20:])), 4),
            flush=True,
        )
        del net
        if DEV.type == "cuda":
            torch.cuda.empty_cache()

    def batch_raw(rs):
        return DC.windows(train, 64, rs, aug, 0.5, False)

    def batch_fb_full(rs):
        lens = np.array([len(t["eeg"]) - DC.W for t in train])
        p = np.maximum(lens, 0).astype(float)
        p /= p.sum()
        n = 64
        ti = rs.choice(len(train), n, p=p)
        X = np.empty((n, DC.W, 232), np.float32)
        S = np.empty((n, DC.W) + train[0]["_S"].shape[1:], np.float32)
        y = np.empty(n, np.float32)
        for j, i in enumerate(ti):
            s = int(rs.integers(0, lens[i] + 1))
            tr = train[i]
            if "_fb" not in tr:
                tr["_fb"] = fb(tr["eeg"])
            X[j] = tr["_fb"][s:s + DC.W]
            S[j] = tr["_S"][s:s + DC.W]
            col = int(tr["att"][s + DC.LAB])
            if rs.random() < 0.5:
                tau = int(rs.integers(FS // 2, DC.W - FS // 2))
                S[j, tau:] = S[j, tau:, ::-1]
                if tau <= DC.LAB:
                    col = 1 - col
            y[j] = 1.0 if col == 0 else 0.0
        return torch.from_numpy(X), torch.from_numpy(S), torch.from_numpy(y)

    smoke("raw_vlaai", batch_raw)
    smoke("fb_vlaai", batch_fb_full)


if __name__ == "__main__":
    main()
