"""Caches for MULTITASK_EXPERIMENTS.md (M1, M4, M6e). One pass over the recordings, numpy/scipy/mne only.

  post_*      windows AFTER the first N2 (M1: awake/asleep auxiliary task). Same pipeline as the E4 caches (first second zeroed,
              causal Butterworth low-pass 45 Hz with the state carried from the start of the recording, 217 features, artifact
              columns from the untouched signal). The first post window (index n_pre) is the one that contains the N2 onset:
              it stays in the stream but is not labelled "asleep". At most MAXPOST windows per recording.
                post_raw_f16.npy (n_post, 4, 640), post_X.npy (n_post, 217) float32, post_rec.npy, post_asleep.npy (1 = starts
                at or after the N2 onset, 0 = straddling window)
  lp30_*      the pre-N2 windows with a low-pass at 30 Hz instead of 45 Hz (M6e), same rows as mask_X.npy / mask_raw_f16.npy.
"""
import os
import sys
import time

import mne
import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
for p in ("experiments", "experiments/e4_start", "experiments/iir_filter", "experiments/cnn_gru_feat"):
    sys.path.insert(0, os.path.join(ROOT, p))
import run_cnn_gru_feat as C  # noqa: E402
import run_iir_filter as I  # noqa: E402

R = C.R
WIN, FS, MAXPOST = R.WIN, 128, 72
CACHE = os.path.join(HERE, "cache")


def main():
    X0, names, win, rec = R.extract()
    art = [i for i, n in enumerate(names) if n.startswith(("clip_frac_", "log_maxabs_")) or n == "n_bad"]
    counts = win.groupby("rec").size()
    n_all = len(win)
    sos45 = I.design(None)
    I.FS_LP = 30.0
    sos30 = I.design(None)
    X30 = np.empty((n_all, X0.shape[1]), np.float32); raw30 = np.empty((n_all, 4, WIN), np.float16)
    px, pr, pq, pa = [], [], [], []
    pos, t0 = 0, time.time()
    for i, r in rec.iterrows():
        vhdr = f"{R.BIDS}/{r.subject}/{r.session_id}/eeg/{r.rec_id}_task-sleeponset_eeg.vhdr"
        x = mne.io.read_raw_brainvision(vhdr, preload=True, verbose="ERROR").get_data(picks=R.CH) * 1e6
        n = int(counts[i]); n_tot = x.shape[1] // WIN
        m = min(MAXPOST, n_tot - n)
        x = x[:, : (n + m) * WIN].copy()
        raw_x = x.copy()
        x[:, :128] = 0.0
        # lp30, pre-N2 windows only
        xf, _ = I.filter_stream(sos30, x[:, : n * WIN])
        xw = xf.reshape(4, n, WIN).transpose(1, 0, 2)
        X30[pos:pos + n], _ = R.window_features(xw)
        X30[pos:pos + n, art] = X0[pos:pos + n, art]
        raw30[pos:pos + n] = xw.astype(np.float16)
        pos += n
        # post-N2 windows, lp45, filter run over the whole stream (same state as for the pre-N2 windows)
        if m > 0:
            xf, _ = I.filter_stream(sos45, x)
            xw = xf[:, n * WIN:].reshape(4, m, WIN).transpose(1, 0, 2)
            F, _ = R.window_features(xw)
            F[:, art] = R.window_features(raw_x[:, n * WIN:].reshape(4, m, WIN).transpose(1, 0, 2))[0][:, art]
            start = (n + np.arange(m)) * (WIN / FS)
            px.append(F.astype(np.float32)); pr.append(xw.astype(np.float16)); pq.append(np.full(m, i)); pa.append((start >= r.n2_onset - 1e-6).astype(np.int8))
        if (i + 1) % 50 == 0:
            print(f"{i + 1}/{len(rec)} recordings, {time.time() - t0:.0f} s", flush=True)
    assert pos == n_all
    np.save(f"{CACHE}/lp30_X.npy", X30); np.save(f"{CACHE}/lp30_raw_f16.npy", raw30)
    np.save(f"{CACHE}/post_X.npy", np.concatenate(px)); np.save(f"{CACHE}/post_raw_f16.npy", np.concatenate(pr))
    np.save(f"{CACHE}/post_rec.npy", np.concatenate(pq)); np.save(f"{CACHE}/post_asleep.npy", np.concatenate(pa))
    print(f"done {time.time() - t0:.0f} s; post windows {sum(len(a) for a in pq)}, asleep {int(np.concatenate(pa).sum())}", flush=True)


if __name__ == "__main__":
    main()
