"""Feature blocks F6, F7, F8 and the spectrogram of F9 (FEATURE_EXPERIMENTS.md). numpy only (the Codabench image has no numba).

All of them are computed from the filtered window (E4 pipeline) with the same 7 Welch frames as the 217 features (2 s Hann frames,
hop 0.5 s, mean removed per window), so they are causal and need nothing but the window.

  F6  within-window dynamics, per channel (52 columns)
        fr{min,med,max}_{band}_{ch}   min / median / max over the 7 frames of the log10 band power, band in theta, alpha, sigma, beta
        adrop_{ch}                    share of the 7 frames whose alpha power is below 0.5 x the largest alpha frame ("alpha dropout")
  F7  inter-channel (16 columns)
        coh_{theta,alpha,sigma}_{TT,FF,L,R}   magnitude-squared coherence (mean over the band) of TP9-TP10, AF7-AF8, TP9-AF7, AF8-TP10
        pli_alpha_{TT,FF}                     cross-spectral phase-lag index in alpha, temporal pair and frontal pair
        asym_alpha_{AF,TP}                    log10 alpha power AF8 - AF7 and TP10 - TP9
  F8  aperiodic fit, per channel (20 columns)
        fit of log10 P = b - log10(fk^chi + f^chi) on 1-40 Hz by a grid over chi (0-4, step 0.2) and the knee frequency fk
        (0 = none, 2, 4, 8, 16 Hz), b in closed form; a second pass refits on the points under the first fit (FOOOF's robust fit)
        aper_exp, aper_off, aper_knee (= log10(1 + fk)), peak_alpha (largest residual in 8-12 Hz), peak_theta (4-8 Hz)
  F9  sg_{ch}_{frame}_{bin}: log10 PSD of every frame, 90 bins of 0.5 Hz (0.5-45 Hz), 4 x 7 x 90 = 2520 columns
"""
import numpy as np

FS, WIN = 128, 640
NFFT, HOP = 256, 64
CH = ["TP9", "AF7", "AF8", "TP10"]
HANN = np.hanning(NFFT)
U = (HANN ** 2).sum()
FREQS = np.fft.rfftfreq(NFFT, 1 / FS)
DF = float(FREQS[1])
FRAME_IDX = np.arange((WIN - NFFT) // HOP + 1)[:, None] * HOP + np.arange(NFFT)
BANDS = {"theta": (4, 8), "alpha": (8, 11), "sigma": (11, 15), "beta": (15, 30)}
PAIRS = {"TT": (0, 3), "FF": (1, 2), "L": (0, 1), "R": (2, 3)}
STATS = ("min", "med", "max")
NAMES_F6 = [f"fr{s}_{b}_{c}" for b in BANDS for s in STATS for c in CH] + [f"adrop_{c}" for c in CH]
NAMES_F7 = [f"coh_{b}_{p}" for b in ("theta", "alpha", "sigma") for p in PAIRS] + ["pli_alpha_TT", "pli_alpha_FF", "asym_alpha_AF", "asym_alpha_TP"]
NAMES_F8 = [f"{f}_{c}" for f in ("aper_exp", "aper_off", "aper_knee", "peak_alpha", "peak_theta") for c in CH]
NAMES_SG = [f"sg_{c}_{t}_{k}" for c in CH for t in range(7) for k in range(90)]
NSG = len(NAMES_SG)


def frame_spectra(wf):
    """wf (n, 4, 640) -> complex frame FFTs (n, 4, 7, 129)."""
    dm = wf - wf.mean(-1, keepdims=True)
    return np.fft.rfft(dm[..., FRAME_IDX] * HANN, axis=-1)


def frame_psd(X):
    p = np.abs(X) ** 2 / (FS * U)
    p[..., 1:-1] *= 2
    return p


def _band(lo, hi):
    return (FREQS >= lo) & (FREQS < hi)


def features_f6(P):
    """P (n, 4, 7, 129) -> (n, 52)."""
    cols = []
    for b, (lo, hi) in BANDS.items():
        lin = P[..., _band(lo, hi)].sum(-1) * DF + 1e-6
        bp = np.log10(lin)
        cols += [bp.min(-1), np.median(bp, -1), bp.max(-1)]
        if b == "alpha":
            alpha = lin
    drop = (alpha < 0.5 * alpha.max(-1, keepdims=True)).mean(-1)
    return np.concatenate(cols + [drop], axis=1).astype(np.float32)


def features_f7(X):
    """X (n, 4, 7, 129) complex -> (n, 16)."""
    saa = (np.abs(X) ** 2).mean(2)
    cols = []
    for b in ("theta", "alpha", "sigma"):
        m = _band(*BANDS[b])
        for a, c in PAIRS.values():
            sac = (X[:, a] * np.conj(X[:, c])).mean(1)
            cols.append((np.abs(sac) ** 2 / (saa[:, a] * saa[:, c] + 1e-12))[:, m].mean(-1))
    m = _band(*BANDS["alpha"])
    for name in ("TT", "FF"):
        a, c = PAIRS[name]
        cols.append(np.abs(np.sign((X[:, a] * np.conj(X[:, c])).imag)[..., m].mean(axis=(1, 2))))
    la = np.log10(frame_psd(X).mean(2)[..., m].sum(-1) * DF + 1e-6)
    cols += [la[:, 2] - la[:, 1], la[:, 3] - la[:, 0]]
    return np.stack(cols, 1).astype(np.float32)


KNEES = (0.0, 2.0, 4.0, 8.0, 16.0)
CHIS = np.arange(0.0, 4.01, 0.2)
SEL = (FREQS >= 1.0) & (FREQS <= 40.0)
FSEL = FREQS[SEL]


def _grid_fit(y, mask):
    """y (N, F) log10 spectra, mask (N, F) bool -> best (chi, knee, b) per row by the sum of squared residuals on the masked points."""
    n = len(y)
    mf = mask.astype(np.float64)
    cnt = mf.sum(-1)
    best = np.full(n, np.inf)
    chi_b, kn_b, b_b = np.zeros(n), np.zeros(n), np.zeros(n)
    for chi in CHIS:
        for fk in KNEES:
            t = np.log10(fk ** chi + FSEL ** chi)
            z = y + t
            b = (z * mf).sum(-1) / cnt
            sse = (mf * (z - b[:, None]) ** 2).sum(-1)
            better = sse < best
            best = np.where(better, sse, best)
            chi_b = np.where(better, chi, chi_b)
            kn_b = np.where(better, fk, kn_b)
            b_b = np.where(better, b, b_b)
    return chi_b, kn_b, b_b


def _curve(chi, fk, b):
    return b[:, None] - np.log10(fk[:, None] ** chi[:, None] + FSEL[None] ** chi[:, None])


def features_f8(Pm):
    """Pm (n, 4, 129) Welch PSD -> (n, 20): aper_exp, aper_off, aper_knee, peak_alpha, peak_theta, each for the 4 channels."""
    n = Pm.shape[0]
    y = np.log10(Pm[..., SEL].reshape(-1, FSEL.size) + 1e-12)
    chi, fk, b = _grid_fit(y, np.ones_like(y, dtype=bool))
    r = y - _curve(chi, fk, b)
    mask = r <= 0                                                   # points under the first fit: the robust refit
    mask[mask.sum(-1) < 15] = True
    chi, fk, b = _grid_fit(y, mask)
    r = y - _curve(chi, fk, b)
    pa = r[:, (FSEL >= 8) & (FSEL <= 12)].max(-1)
    pt = r[:, (FSEL >= 4) & (FSEL < 8)].max(-1)
    cols = [chi, b, np.log10(1 + fk), pa, pt]
    return np.concatenate([c.reshape(n, 4) for c in cols], axis=1).astype(np.float32)


def spectrogram(P):
    """P (n, 4, 7, 129) -> (n, 2520) float32, order (channel, frame, bin)."""
    return np.log10(P[..., 1:91] + 1e-6).reshape(len(P), -1).astype(np.float32)


def all_blocks(wf):
    """wf (n, 4, 640) filtered windows -> F6, F7, F8, SG."""
    X = frame_spectra(wf)
    P = frame_psd(X)
    return features_f6(P), features_f7(X), features_f8(P.mean(2)), spectrogram(P)
