"""F12 (FEATURE_EXPERIMENTS.md): continuous wavelet features instead of the STFT. numpy only (the Codabench image has no pywt).

Complex Morlet wavelets (6 cycles) at 20 log-spaced frequencies from 1 to 45 Hz, applied by FFT convolution (zero padded) to each
filtered 5 s window (mean removed). Per channel:
  cwt_{k:02d}_{ch}   mean over time of log10 |W|^2 at frequency k (20 columns)
  cwtv_{band}_{ch}   SD over time of log10 |W|^2 averaged inside the band (delta 1-4, theta 4-8, alpha+sigma 8-15, beta 15-30 Hz)
                     over the central 3 s (the wavelet edges are not used): temporal variability at 0.1 s resolution
"""
import numpy as np

FS, WIN = 128, 640
CH = ["TP9", "AF7", "AF8", "TP10"]
FREQS = np.geomspace(1.0, 45.0, 20)
BANDS = {"delta": (1, 4), "theta": (4, 8), "alpha": (8, 15), "beta": (15, 30)}
NFFT = 2048
NAMES = [f"cwt_{k:02d}_{c}" for k in range(len(FREQS)) for c in CH] + [f"cwtv_{b}_{c}" for b in BANDS for c in CH]


def _bank(cycles=6.0):
    t = np.arange(-NFFT // 2, NFFT // 2) / FS
    ws = []
    for f in FREQS:
        s = cycles / (2 * np.pi * f)
        w = np.exp(2j * np.pi * f * t) * np.exp(-t ** 2 / (2 * s ** 2))
        ws.append(np.fft.fft(np.fft.ifftshift(w / np.abs(w).sum())))        # energy-normalised in amplitude
    return np.array(ws)                                                       # (F, NFFT)


BANK = _bank()


def cwt_power(xw):
    """xw (n, 4, 640) -> |W|^2 (n, 4, F, 640)."""
    x = xw - xw.mean(-1, keepdims=True)
    X = np.fft.fft(x, NFFT, axis=-1)[:, :, None, :]                           # zero padded
    W = np.fft.ifft(X * BANK[None, None], axis=-1)[..., :WIN]
    return np.abs(W) ** 2


def features(xw, chunk=500):
    out = []
    mids = slice(WIN // 4, 3 * WIN // 4)
    for i in range(0, len(xw), chunk):
        P = np.log10(cwt_power(xw[i:i + chunk].astype(np.float64)) + 1e-6)     # (n, 4, F, T)
        mean = P.mean(-1)                                                       # (n, 4, F)
        cols = [mean[:, :, k] for k in range(len(FREQS))]
        for lo, hi in BANDS.values():
            m = (FREQS >= lo) & (FREQS < hi)
            cols.append(P[:, :, m][..., mids].mean(2).std(-1))
        out.append(np.stack(cols, 1).reshape(len(P), -1))                       # (n, cols, 4) flattened: column-major, as NAMES
    return np.concatenate(out).astype(np.float32)
