"""SpecAugment transforms for HFTT/BEATs mel input."""
import json

import torch
import torch.nn as nn
from torchaudio.transforms import FrequencyMasking, TimeMasking

CRACKLE_LABELS = (1, 3)
WHEEZE_LABELS = (2, 3)


class StructuredSpecAug(nn.Module):
    """Per-sample SpecAugment on [B, 1, F, T] with mean fill.

    Masks are drawn independently per sample and filled with that sample's mean, so they never
    create loud horizontal bands (wheeze-like) or vertical stripes (crackle-like).
    protect_all=True: freq masks never overlap the wheeze protect band, for every sample.
    sound_aware=True with labels (label-conditional, leaks labels through the mask pattern):
      - wheeze samples: freq masks are narrower and never overlap the wheeze protect band
      - crackle samples: time masks are capped near the crackle transient width
    """

    expects_freq_time = True

    def __init__(self, freq_mask_param=16, time_mask_param=35, n_freq=2, n_time=2, sound_aware=False,
                 protect_band=(7, 60), wheeze_freq_mask=8, crackle_time_mask=8, protect_all=False):
        super().__init__()
        self.freq_mask_param, self.time_mask_param = int(freq_mask_param), int(time_mask_param)
        self.n_freq, self.n_time = int(n_freq), int(n_time)
        self.sound_aware = bool(sound_aware)
        self.protect_all = bool(protect_all)
        self.protect_band = (int(protect_band[0]), int(protect_band[1]))
        self.wheeze_freq_mask, self.crackle_time_mask = int(wheeze_freq_mask), int(crackle_time_mask)

    @staticmethod
    def _rand_int(high):
        """Uniform integer in [0, high]."""
        return int(torch.randint(0, high + 1, (1,)).item()) if high > 0 else 0

    def _span(self, size, max_width, avoid=None):
        """Sample (start, width); with avoid=(lo, hi) the span stays fully outside [lo, hi]."""
        width = self._rand_int(min(max_width, size))
        if width == 0:
            return 0, 0
        if avoid is None:
            return self._rand_int(size - width), width
        lo, hi = avoid
        n_below = max(lo - width + 1, 0)
        n_above = max(size - width - hi, 0)
        if n_below + n_above == 0:
            return 0, 0
        k = int(torch.randint(0, n_below + n_above, (1,)).item())
        return (k, width) if k < n_below else (hi + 1 + (k - n_below), width)

    def forward(self, x):
        return self.forward_with_labels(x, None)

    def forward_with_labels(self, x, labels=None):
        if x.dim() != 4:
            raise ValueError('StructuredSpecAug expects [B, 1, F, T], got {}'.format(tuple(x.shape)))
        B, _, F, T = x.shape
        use_labels = self.sound_aware and labels is not None
        labels = labels.detach().cpu().tolist() if use_labels else [None] * B
        out = x.clone()
        for b, lab in enumerate(labels):
            wheeze = use_labels and int(lab) in WHEEZE_LABELS
            crackle = use_labels and int(lab) in CRACKLE_LABELS
            fill = x[b].mean()
            f_max = min(self.freq_mask_param, self.wheeze_freq_mask) if wheeze else self.freq_mask_param
            t_max = min(self.time_mask_param, self.crackle_time_mask) if crackle else self.time_mask_param
            for _ in range(self.n_freq):
                s, w = self._span(F, f_max, self.protect_band if (wheeze or self.protect_all) else None)
                if w:
                    out[b, :, s:s + w, :] = fill
            for _ in range(self.n_time):
                s, w = self._span(T, t_max)
                if w:
                    out[b, :, :, s:s + w] = fill
        return out

    def extra_repr(self):
        return ('freq={}x{}, time={}x{}, sound_aware={}, protect_all={}, protect_band={}, wheeze_freq_mask={}, '
                'crackle_time_mask={}').format(self.n_freq, self.freq_mask_param, self.n_time, self.time_mask_param,
                                               self.sound_aware, self.protect_all, self.protect_band,
                                               self.wheeze_freq_mask, self.crackle_time_mask)


def _load_stats(path):
    if not path:
        return {}
    with open(path) as f:
        return json.load(f)


def build_specaug_transform(policy='icbhi_ast_sup', mask='mean', stats_path=None):
    """Build a SpecAugment module.

    icbhi_ast_sup: legacy torchaudio masks (zero fill, one mask per batch).
    structured:    StructuredSpecAug, per-sample masks with mean fill.
    sound_aware:   structured + freq masks kept out of the wheeze protect band for every sample.
    sound_aware_labeled: label-conditional masks (wheeze protect band, short crackle time masks).
        The mask pattern reveals the label, so the model learns "unmasked = abnormal" and
        specificity collapses at test time; kept only to reproduce that failure.
    """
    del mask
    if policy == 'icbhi_ast_sup':
        return nn.Sequential(
            FrequencyMasking(freq_mask_param=16),
            FrequencyMasking(freq_mask_param=16),
            TimeMasking(time_mask_param=35),
            TimeMasking(time_mask_param=35),
        )
    if policy == 'structured':
        return StructuredSpecAug()
    if policy in ('sound_aware', 'sound_aware_labeled'):
        stats = _load_stats(stats_path)
        return StructuredSpecAug(
            sound_aware=policy == 'sound_aware_labeled',
            protect_all=policy == 'sound_aware',
            protect_band=stats.get('wheeze_protect_band', (7, 60)),
            crackle_time_mask=stats.get('crackle_time_mask', 8),
        )
    raise ValueError(f'Unknown specaug policy: {policy}')
