"""Fine-time crackle residual on top of BEATs frame logits.

Crackles are explosive transients of a few milliseconds. A BEATs token spans
about 160 ms (16 mel frames of 10 ms, then 8 frequency patches). The residual
measures 10 ms spectral flux, excess kurtosis, and high-band energy, max-pools
them onto each BEATs time step, and adds a zero-initialized projection to the
crackle logit only. At initialization the official head is unchanged.
"""

import torch
import torch.nn as nn
import torch.nn.functional as F


N_FREQ_PATCHES = 8
HF_CUTOFF_HZ = 1500.0


def _pool_time(values, n_time, mode):
    """values: [B, T] -> [B, n_time]."""
    if values.size(1) == n_time:
        return values
    if values.size(1) < 1:
        return values.new_zeros(values.size(0), n_time)
    pooled = values.unsqueeze(1)
    if mode == 'avg':
        pooled = F.adaptive_avg_pool1d(pooled, n_time)
    else:
        pooled = F.adaptive_max_pool1d(pooled, n_time)
    return pooled.squeeze(1)


def _excess_kurtosis(windows):
    """Excess kurtosis over the last dimension. windows: [B, N, hop]."""
    centered = windows - windows.mean(dim=-1, keepdim=True)
    var = centered.pow(2).mean(dim=-1).clamp(min=1e-8)
    fourth = centered.pow(4).mean(dim=-1)
    return (fourth / var.pow(2) - 3.0).clamp(-5.0, 50.0)


def _hop_excess_kurtosis(waves, hop):
    length = waves.size(1)
    if length < 2:
        return waves.new_zeros(waves.size(0), 1)
    if length < hop:
        return _excess_kurtosis(waves.unsqueeze(1))
    n_hops = length // hop
    windows = waves[:, :n_hops * hop].reshape(waves.size(0), n_hops, hop)
    return _excess_kurtosis(windows)


def fine_crackle_features(waves, n_time, sample_rate=16000):
    """10 ms crackle cues pooled onto ``n_time`` BEATs time steps. [B, n_time, 3].

    Channels are positive spectral flux, excess kurtosis, and the fraction of
    STFT energy above 1.5 kHz. Flux and kurtosis use max pooling because a
    crackle is a peak inside the token. The high-band ratio uses average pooling.
    """
    if waves.dim() != 2:
        raise ValueError('expected waveform [B, samples], got {}'.format(tuple(waves.shape)))
    if n_time < 1:
        raise ValueError('n_time must be positive')
    hop = max(1, int(sample_rate) // 100)
    n_fft = hop * 4
    window = torch.hann_window(n_fft, device=waves.device, dtype=torch.float32)
    spec = torch.stft(
        waves.float(),
        n_fft=n_fft,
        hop_length=hop,
        win_length=n_fft,
        window=window,
        center=True,
        return_complex=True,
    )
    mag = spec.abs()
    flux = F.pad(torch.relu(mag[:, :, 1:] - mag[:, :, :-1]).mean(dim=1), (1, 0))
    cutoff = int(round(HF_CUTOFF_HZ / float(sample_rate) * n_fft))
    cutoff = min(max(cutoff, 1), mag.size(1) - 1)
    high = mag[:, cutoff:, :].sum(dim=1) / mag.sum(dim=1).clamp(min=1e-8)
    kurt = _hop_excess_kurtosis(waves.float(), hop)
    feats = torch.stack([
        _pool_time(flux, n_time, 'max'),
        _pool_time(kurt, n_time, 'max'),
        _pool_time(high, n_time, 'avg'),
    ], dim=-1)
    return feats.to(dtype=waves.dtype)


class CrackleFluxResidual(nn.Module):
    """Zero-initialized map from fine crackle cues onto one logit per BEATs token."""

    def __init__(self, n_freq=N_FREQ_PATCHES, sample_rate=16000):
        super().__init__()
        if n_freq < 1:
            raise ValueError('n_freq must be positive')
        self.n_freq = int(n_freq)
        self.sample_rate = int(sample_rate)
        self.norm = nn.LayerNorm(3)
        self.proj = nn.Linear(3, 1)
        nn.init.zeros_(self.proj.weight)
        nn.init.zeros_(self.proj.bias)

    def forward(self, waves, n_tokens):
        n_tokens = int(n_tokens)
        n_freq = self.n_freq if n_tokens % self.n_freq == 0 else 1
        n_time = n_tokens // n_freq
        with torch.no_grad():
            feats = fine_crackle_features(waves, n_time, self.sample_rate)
        delta = self.proj(self.norm(feats)).squeeze(-1)
        if n_freq == 1:
            return delta
        # Conv2d patch embed flattens (time, freq) in C order, so one time step
        # is n_freq consecutive tokens.
        return delta.repeat_interleave(n_freq, dim=1)


def add_crackle_flux(head, logit_c, waves):
    """Add the residual to the crackle logit only. Wheeze logits stay untouched."""
    branch = getattr(head, 'crackle_flux', None)
    if branch is None or waves is None:
        return logit_c
    return logit_c + branch(waves, logit_c.size(1))
