"""Build bipolar_eaP cache: nearest-neighbour bipolar, then causal EA.

Mirrors derive_lap_eap.py but uses nearest_bipolar (ch − single NN) instead of
surface_laplacian (ch − mean of ≤k neighbours). C stays 58.

usage: python derive_bipolar_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 LAP_NEIGH, causal_ea, ea_prior, nearest_bipolar, zscore_trial  # noqa: E402

P = CFG["preps"]["bipolar_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_pairs():
    names = MONTAGES[CFG["montage"]]
    for ch in ("CZ", "T7", "O1", "FP1", "PZ"):
        i = names.index(ch)
        j = LAP_NEIGH[i][0]
        print(f"{ch} - {names[j]}")


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 = nearest_bipolar(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", "bipolar_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 = nearest_bipolar(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_pairs()
    save_from_mat(os.path.join(DATA, "decoder_lodo", "cache", "mat"),
                  os.path.join(EXP, "cache", "bipolar_eaP"), "corpus")
    save_from_mat(os.path.join(EXTERNAL_DATA, "AASD", "cache", "mat"),
                  os.path.join(EXTERNAL_DATA, "AASD", "cache", "bipolar_eaP"), "AASD")
    save_from_mat(os.path.join(EXTERNAL_DATA, "Carta2026", "cache", "mat"),
                  os.path.join(EXTERNAL_DATA, "Carta2026", "cache", "bipolar_eaP"), "Carta")
    fuglsang()
