"""Phase D feature cache (one pass per trial), common57 montage, causal filters only.

cache/spatial/<key>.npz:
  cov5_19   (n5, 1653)    5-s epochs, 1-9 Hz (c19 cache), CAR, NOT z-scored (raw scale)       [D1]
  cov5_813  (n5, 1653)    5-s epochs, 8-13 Hz (causal BP on cwide), CAR, raw scale          [D1]
  fb5       (n5, 4, 1653) 5-s epochs, filter bank [1-4, 4-8, 8-13, 13-30] Hz on cwide -> CAR -> running z [D3]
  fb1       (n1, 4, 1653) 1-s windows, same filter bank                                        [D3]
  amp5_raw  (n5, 118)     amplitude features from the raw 128 Hz data: log SD (57), log RMS/SD (57),
                          log relative band power delta/theta/alpha/beta of the channel-median PSD   [D2]
  amp5_rz   (n5, 118)     the same after causal running z-scoring (128 Hz, tau 30 s)                [D2]
  lab5/lab1 attended side (0 left, 1 right) = majority of sign(azimuth) in the window
  t5/t1     window start (s, trial time)
Covariances are stored as float32 upper triangles (incl. diagonal). Windows: up to 24 5-s epochs and 30 1-s
windows per trial, evenly spaced over the trimmed trial (a cap to bound memory; documented).
"""
import os
import sys

import numpy as np
from joblib import Parallel, delayed
from scipy import signal

sys.path.insert(0, os.path.dirname(__file__))
from common import (CACHE, CFG, FS, get_logger, load_eeg, load_labels, load_pp, montage_idx, running_z,  # noqa: E402
                    sos_bp, trial_index)

log = get_logger("d0_spatial_cache")
BANDS = [(1, 4), (4, 8), (8, 13), (13, 30)]
C = 57
IU = np.triu_indices(C)
D = os.path.join(CACHE, "spatial")
os.makedirs(D, exist_ok=True)


def pick(n_avail, cap):
    if n_avail <= cap:
        return np.arange(n_avail)
    return np.unique(np.round(np.linspace(0, n_avail - 1, cap)).astype(int))


def covs(x, starts, W):
    out = np.empty((len(starts), len(IU[0])), np.float32)
    for i, s in enumerate(starts):
        seg = x[s:s + W]
        seg = seg - seg.mean(0)
        out[i] = (seg.T @ seg / W)[IU]
    return out


def amp_feats(x, fs):
    sd = x.std(0)
    rms = np.sqrt((x ** 2).mean(0))
    f, P = signal.welch(x - x.mean(0), fs=fs, nperseg=2 * fs, axis=0)
    p = np.median(P, 1)
    tot = max(p[(f >= 1) & (f < 30)].sum(), 1e-20)
    rel = [p[(f >= a) & (f < b)].sum() / tot for a, b in ((1, 4), (4, 8), (8, 13), (13, 30))]
    return np.r_[np.log(sd + 1e-12), np.log(rms / (sd + 1e-12)), np.log(np.array(rel) + 1e-12)]


def build(row):
    p = os.path.join(D, f"{row['key']}.npz")
    if os.path.exists(p):
        return 0
    lab = load_labels(row["key"])
    side = (lab["att_az"] > 0).astype(float)                  # 128 Hz
    # 1-9 Hz raw-scale (no running z) and wide band
    d19 = load_pp(row, "c19", "common57", do_runz=False)
    dw_raw = load_pp(row, "cwide", "common57", do_runz=False)
    dw = load_pp(row, "cwide", "common57")                     # CAR + running z
    fs19, fsw = d19["fs"], dw["fs"]
    t0 = d19["t0_s"]
    n5 = int((len(d19["eeg"]) / fs19) // 5)
    i5 = pick(n5, 24)
    t5 = t0 + i5 * 5.0
    n1 = int(len(dw["eeg"]) / fsw)
    i1 = pick(n1, 30)
    t1 = t0 + i1 * 1.0
    cov5_19 = covs(d19["eeg"], (i5 * 5 * fs19).astype(int), 5 * fs19)
    x813 = signal.sosfilt(sos_bp(8.0, 13.0, 4, fsw), dw_raw["eeg"], axis=0)
    cov5_813 = covs(x813, (i5 * 5 * fsw).astype(int), 5 * fsw)
    fb5 = np.empty((len(i5), len(BANDS), len(IU[0])), np.float32)
    fb1 = np.empty((len(i1), len(BANDS), len(IU[0])), np.float32)
    for b, (lo, hi) in enumerate(BANDS):
        xb = signal.sosfilt(sos_bp(float(lo), float(hi), 4, fsw), dw["eeg"], axis=0)
        fb5[:, b] = covs(xb, (i5 * 5 * fsw).astype(int), 5 * fsw)
        fb1[:, b] = covs(xb, (i1 * fsw).astype(int), fsw)
    # amplitude features from raw 128 Hz
    raw = np.asarray(load_eeg(row["key"])[:, montage_idx(row, "common57")], dtype=np.float64)
    rz = running_z(raw, FS)
    a_raw, a_rz = [], []
    for t in t5:
        s = int(t * FS)
        a_raw.append(amp_feats(raw[s:s + 5 * FS], FS))
        a_rz.append(amp_feats(rz[s:s + 5 * FS], FS))
    lab5 = np.array([side[int(t * FS):int((t + 5) * FS)].mean() > 0.5 for t in t5]).astype(np.int8)
    lab1 = np.array([side[int(t * FS):int((t + 1) * FS)].mean() > 0.5 for t in t1]).astype(np.int8)
    np.savez(p, cov5_19=cov5_19, cov5_813=cov5_813, fb5=fb5, fb1=fb1, amp5_raw=np.array(a_raw, np.float32),
             amp5_rz=np.array(a_rz, np.float32), lab5=lab5, lab1=lab1, t5=t5, t1=t1)
    return 1


if __name__ == "__main__":
    ti = trial_index()
    if len(sys.argv) > 1 and sys.argv[1] == "dry":
        ti = ti[ti.subject == ti.groupby("ds", observed=True).subject.transform("min")]
    n = Parallel(n_jobs=int(sys.argv[2]) if len(sys.argv) > 2 else CFG["n_jobs"])(
        delayed(build)(r) for _, r in ti.iterrows())
    log.info(f"built {sum(n)} trials")
