"""Builds cache/F12.npy (+ F12_names.npy): CWT features (ffeat3.py), rows in the order of R.extract()'s `win`; E4 filtering. One process."""
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))
sys.path.insert(0, HERE)
for p in ("experiments/stft_tree", "experiments/iir_filter"):
    sys.path.insert(0, os.path.join(ROOT, p))
import ffeat3 as G  # noqa: E402
import run_iir_filter as I  # noqa: E402
import run_stft_tree as R  # noqa: E402

mne.set_log_level("ERROR")
_, _, win, rec = R.extract()
counts = win.groupby("rec").size()
sos = I.design(None)
t0, out = time.time(), []
for i, r in rec.iterrows():
    n = int(counts[i])
    x = mne.io.read_raw_brainvision(f"{R.BIDS}/{r.subject}/{r.session_id}/eeg/{r.rec_id}_task-sleeponset_eeg.vhdr", preload=True,
                                    verbose="ERROR").get_data(picks=R.CH) * 1e6
    x = x[:, : n * G.WIN].copy(); x[:, :128] = 0.0
    xf, _ = I.filter_stream(sos, x)
    out.append(G.features(xf.reshape(4, n, G.WIN).transpose(1, 0, 2), chunk=250))
    if (i + 1) % 50 == 0:
        print(f"{i + 1}/{len(rec)} recordings, {time.time() - t0:.0f} s", flush=True)
F = np.concatenate(out)
assert len(F) == len(win)
np.save(os.path.join(HERE, "cache", "F12.npy"), F); np.save(os.path.join(HERE, "cache", "F12_names.npy"), np.array(G.NAMES))
print("done", F.shape, f"{time.time() - t0:.0f} s", flush=True)
