"""Torch (GPU) port of run_stft_tree.window_features: the same 217 features, same order, float64 by default.

Used to recompute the features of augmented windows inside the training loop. Checked against the numpy original by
check() below (run this file directly).
"""
import math
import os
import sys

import numpy as np
import torch

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
sys.path.insert(0, os.path.join(ROOT, "experiments/stft_tree"))
import run_stft_tree as R  # noqa: E402

FS, WIN, NFFT, HOP = 128, 640, 256, 64
CH = R.CH
BANDS = R.BANDS
FREQS = np.fft.rfftfreq(NFFT, 1 / FS)
DF = float(FREQS[1])


class TorchFeatures:
    def __init__(self, device, dtype=torch.float64):
        self.dev, self.dt = device, dtype
        t = lambda a: torch.as_tensor(a, device=device)
        tm = lambda m: torch.as_tensor(np.where(m)[0], device=device)      # index tensors: no host sync, unlike bool masks
        self.hann = t(np.hanning(NFFT)).to(dtype)
        self.U = float((np.hanning(NFFT) ** 2).sum())
        self.freqs = t(FREQS).to(dtype)
        F = FREQS
        self.tot_m = tm((F >= 0.5) & (F < 45))
        self.band_m = {b: tm((F >= lo) & (F < hi)) for b, (lo, hi) in BANDS.items()}
        fm = (F >= 2) & (F <= 40) & ~((F > 7) & (F < 17))
        self.fm = tm(fm)
        lf = np.log10(F[fm]); self.lf_mean = float(lf.mean())
        self.lfc = t(lf - lf.mean()).to(dtype); self.lfc2 = float(((lf - lf.mean()) ** 2).sum())
        self.sm = tm((F >= 11) & (F < 15))
        self.logf_sm = t(np.log10(F[(F >= 11) & (F < 15)])).to(dtype)
        self.am = tm((F >= 7) & (F <= 13))
        self.g = tm((F >= 30) & (F < 45))
        self.spec_m = [tm((F >= j) & (F < j + 1)) for j in range(1, 45)]
        self.n_tot = int(((F >= 0.5) & (F < 45)).sum())
        self.names = self._names()

    def _names(self):
        _, names = R.window_features(np.random.default_rng(0).standard_normal((2, 4, WIN)) * 10)
        return list(names)

    def __call__(self, xw):
        """xw: (N, 4, 640) tensor (microvolts) -> (N, 217) tensor, same order as R.window_features."""
        x = xw.to(self.dt)
        dm = x - x.mean(-1, keepdim=True)
        fr = dm.unfold(-1, NFFT, HOP) * self.hann                       # (N, 4, 7, 256)
        P = torch.fft.rfft(fr, dim=-1).abs() ** 2 / (FS * self.U)
        P[..., 1:-1] *= 2
        Pm = P.mean(2)                                                  # (N, 4, 129)
        cols = []
        add = lambda a: cols.extend([a[:, c] for c in range(4)] if a.dim() == 2 else [a])
        tot = Pm[..., self.tot_m].sum(-1) * DF + 1e-6
        add(torch.log10(tot))
        bp, bp_fr = {}, {}
        for b in BANDS:
            m = self.band_m[b]
            bp[b] = Pm[..., m].sum(-1) * DF + 1e-6
            bp_fr[b] = torch.log10(P[..., m].sum(-1) * DF + 1e-6)
            add(torch.log10(bp[b])); add(torch.log10(bp[b] / tot))
        add(torch.log10(bp["theta"] / bp["alpha"])); add(torch.log10(bp["sigma"] / bp["beta"])); add(torch.log10(bp["delta"] / bp["beta"]))
        Pt = Pm[..., self.tot_m]
        Pn = Pt / (Pt.sum(-1, keepdim=True) + 1e-12)
        add(-(Pn * torch.log(Pn + 1e-12)).sum(-1) / math.log(self.n_tot))
        cum = torch.cumsum(Pn, -1)
        ft = self.freqs[self.tot_m]
        add(ft[(cum >= 0.95).to(torch.int8).argmax(-1)]); add(ft[(cum >= 0.5).to(torch.int8).argmax(-1)])
        ly = torch.log10(Pm[..., self.fm] + 1e-6)
        slope = ((ly - ly.mean(-1, keepdim=True)) * self.lfc).sum(-1) / self.lfc2
        add(slope)
        fit = ly.mean(-1, keepdim=True) + slope[..., None] * (self.logf_sm - self.lf_mean)
        add((torch.log10(Pm[..., self.sm] + 1e-6) - fit).mean(-1))
        add(self.freqs[self.am][Pm[..., self.am].argmax(-1)])
        for b in ("delta", "alpha", "beta", "gamma"):
            add(bp_fr[b].std(-1, unbiased=False))
        add(torch.log10(P[..., self.tot_m].sum(-1) * DF + 1e-6).std(-1, unbiased=False))
        sd = dm.std(-1, unbiased=False)
        add(torch.log10(sd + 1e-3))
        add(torch.log10(dm.diff(dim=-1).abs().mean(-1) + 1e-3))
        mx = x.abs().amax(-1)
        add(torch.log10(mx + 1e-3))
        add((x.abs() >= 780).to(self.dt).mean(-1))
        rms_hf = torch.sqrt(Pm[..., self.g].sum(-1) * DF)
        add(((mx > 200) | (rms_hf > 5)).to(self.dt).sum(-1))
        z = dm / (sd[..., None] + 1e-6)
        for a, b in ((0, 3), (1, 2), (0, 1), (2, 3)):
            add((z[:, a] * z[:, b]).mean(-1))
        lp = torch.log10(Pm + 1e-6)
        for idx in ([0, 3], [1, 2]):
            sub = lp[:, idx]
            for m in self.spec_m:
                add(sub[..., m].mean(dim=(1, 2)))
        return torch.stack(cols, 1)


def check(n=3000):
    """Compare with the numpy original on real filtered windows of the best pipeline."""
    raw = np.load(os.path.join(ROOT, "experiments/e4_start/cache/mask_raw_f16.npy"), mmap_mode="r")
    rng = np.random.default_rng(0)
    rows = np.sort(rng.choice(len(raw), n, replace=False))
    x = np.asarray(raw[rows]).astype(np.float64)
    ref, names = R.window_features(x)
    tf = TorchFeatures(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
    assert tf.names == list(names)
    out = tf(torch.from_numpy(x).to(tf.dev)).cpu().numpy()
    d = np.abs(out - ref)
    rel = d / (np.abs(ref) + 1e-3)
    worst = int(rel.max(0).argmax())
    print(f"{n} real windows: max |diff| {d.max():.2e}, max relative {rel.max():.2e} (column {names[worst]}); "
          f"columns with any relative diff > 1e-4: {[names[j] for j in np.where(rel.max(0) > 1e-4)[0]]}")
    return rel.max()


if __name__ == "__main__":
    check()
