"""Build sph_lap_eaP cache: Perrin spherical-spline / CSD Laplacian, then causal EA.

Mirrors derive_lap_eap.py but uses spherical_surface_laplacian (global spline CSD)
instead of nearest-neighbour surface_laplacian. C stays 58. Distinct from bipolar.

Corpus and AASD / Carta are derived from the existing `mat` cache.
Fuglsang is rebuilt from stage_a like lap_eaP.

usage: python derive_sph_lap_eap.py
"""
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 common import MONTAGES  # noqa: E402
from prepare_data import (  # noqa: E402
    causal_ea, ea_prior, spherical_csd_matrix, spherical_surface_laplacian, zscore_trial,
)

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


def show_csd():
    L = spherical_csd_matrix()
    names = MONTAGES[CFG["montage"]]
    for ch in ("CZ", "T7", "O1", "FPZ", "PZ"):
        i = names.index(ch)
        w = L[i]
        top = np.argsort(-np.abs(w))[:6]
        print(ch, "CSD row |w| tops:",
              [(names[j], float(w[j])) for j in top])
    print("L diag mean", float(np.diag(L).mean()), "offdiag rms",
          float(np.sqrt(((L - np.diag(np.diag(L))) ** 2).mean())))


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 = spherical_surface_laplacian(z["eeg"].astype(np.float64))
        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=z["env"], 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", "sph_lap_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 = zscore_trial(x)
        x = spherical_surface_laplacian(x)
        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"))
        x = x[TRIM:TRIM + len(envz["env"])]
        if len(x) != len(envz["env"]):
            raise RuntimeError(f"{key}: eeg {len(x)} vs env {len(envz['env'])}")
        np.savez(out, eeg=x.astype(np.float32), env=envz["env"], 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__":
    show_csd()
    save_from_mat(os.path.join(DATA, "decoder_lodo", "cache", "mat"),
                  os.path.join(EXP, "cache", "sph_lap_eaP"), "corpus")
    save_from_mat(os.path.join(EXTERNAL_DATA, "AASD", "cache", "mat"),
                  os.path.join(EXTERNAL_DATA, "AASD", "cache", "sph_lap_eaP"), "AASD")
    save_from_mat(os.path.join(EXTERNAL_DATA, "Carta2026", "cache", "mat"),
                  os.path.join(EXTERNAL_DATA, "Carta2026", "cache", "sph_lap_eaP"), "Carta")
    fuglsang()
