"""Build lp7_eaP: causal 7 Hz low-pass on the mat EEG and envelopes, then eaP-style causal EA.

Fuglsang has no mat cache. Its EEG is rebuilt from stage_a (1-9 Hz filtfilt, CAR, one z-score),
low-passed, then aligned. Envelopes are the existing eaP envelopes, low-passed the same way.
"""
import glob
import os
import sys

import numpy as np
from joblib import Parallel, delayed
from scipy.signal import butter, sosfiltfilt

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from common_exp import CFG, EXP, EXTERNAL_DATA  # noqa: E402
from prepare_data import causal_ea, causal_lowpass, ea_prior, zscore_trial  # noqa: E402

P = CFG["preps"]["lp7_eaP"]
HZ = float(P["lowpass_hz"])
DATA = "/root/disk_3tb/EEG-sAAD-Grand-Challenge-Training-Dataset/experiments"
BP = butter(2, [1, 9], "bandpass", fs=128, output="sos")
TRIM = 32


def save_from_mat(src, dst, name):
    os.makedirs(dst, exist_ok=True)
    files = sorted(f for f in os.listdir(src) if f.endswith(".npz"))

    def one(f):
        out = os.path.join(dst, f)
        if os.path.exists(out):
            return 0
        z = np.load(os.path.join(src, f))
        x = causal_lowpass(z["eeg"].astype(np.float64), HZ)
        e = causal_lowpass(z["env"].astype(np.float64), HZ)
        x = causal_ea(x, CFG["fs"], tau_s=P.get("ea_tau", 60.0), R0=ea_prior(P, x), n0=P.get("ea_n0"),
                      shrink=P.get("ea_shrink", 0.1))
        extra = {k: z[k] for k in ("att128", "n128") if k in z.files}
        np.savez(out, eeg=x.astype(np.float32), env=e.astype(np.float32), att=z["att"], t0=z["t0"], **extra)
        return 1

    n = sum(Parallel(n_jobs=6)(delayed(one)(f) for f in files))
    print(f"{name}: wrote {n} new / {len(files)} trials -> {dst}", flush=True)


def fuglsang():
    here = os.path.join(EXTERNAL_DATA, "Fuglsang2020")
    src_eeg = os.path.join(here, "stage_a")
    src_env = os.path.join(here, "cache", "eaP_n5_t60")
    dst = os.path.join(here, "cache", "lp7_eaP")
    os.makedirs(dst, exist_ok=True)
    files = sorted(glob.glob(os.path.join(src_eeg, "*.npz")))

    def one(f):
        key = "FUG_" + os.path.basename(f)[:-4]
        out = os.path.join(dst, key + ".npz")
        if os.path.exists(out):
            return 0
        z = np.load(f, allow_pickle=True)
        pres = np.asarray(z["present"], bool)
        x = sosfiltfilt(BP, z["eeg"].astype(np.float64), axis=0)[::4]
        x[:, pres] -= x[:, pres].mean(1, keepdims=True)
        x[:, ~pres] = 0.0
        x = causal_lowpass(zscore_trial(x), HZ)
        x = causal_ea(x, 32, tau_s=P.get("ea_tau", 60.0), R0=ea_prior(P, x), n0=P.get("ea_n0"),
                      shrink=P.get("ea_shrink", 0.1))
        envz = np.load(os.path.join(src_env, key + ".npz"))
        e = causal_lowpass(envz["env"].astype(np.float64), HZ)
        x = x[TRIM:TRIM + len(e)]
        if len(x) != len(e):
            raise RuntimeError(f"{key}: eeg {len(x)} vs env {len(e)}")
        np.savez(out, eeg=x.astype(np.float32), env=e.astype(np.float32), att=envz["att"], t0=envz["t0"])
        return 1

    n = sum(Parallel(n_jobs=4)(delayed(one)(f) for f in files))
    print(f"Fuglsang2020: wrote {n} new / {len(files)} trials -> {dst}", flush=True)


if __name__ == "__main__":
    save_from_mat(os.path.join(DATA, "decoder_lodo", "cache", "mat"), os.path.join(EXP, "cache", "lp7_eaP"), "corpus")
    save_from_mat(os.path.join(EXTERNAL_DATA, "AASD", "cache", "mat"),
                  os.path.join(EXTERNAL_DATA, "AASD", "cache", "lp7_eaP"), "AASD")
    save_from_mat(os.path.join(EXTERNAL_DATA, "Carta2026", "cache", "mat"),
                  os.path.join(EXTERNAL_DATA, "Carta2026", "cache", "lp7_eaP"), "Carta")
    fuglsang()
