"""Deterministic waveform conditioning and train-only waveform augmentation for ICBHI cycles."""

import math
import random

import numpy as np
import torch
from scipy.signal import butter, sosfiltfilt


def highpass(wave, cutoff_hz, sample_rate=16000, order=4):
    """Zero-phase Butterworth high-pass (removes DC / heart-sound rumble below wheeze range)."""
    sos = butter(order, cutoff_hz, btype='highpass', fs=sample_rate, output='sos')
    out = sosfiltfilt(sos, wave.double().numpy())
    return torch.from_numpy(np.ascontiguousarray(out)).float()


def rms_normalize(wave, target_dbfs, peak_limit=0.99):
    """Scale to a target RMS level (harmonizes device gain), never exceeding peak_limit."""
    rms = float(wave.pow(2).mean().sqrt())
    if rms < 1e-8:
        return wave
    gain = 10.0 ** (target_dbfs / 20.0) / rms
    peak = float(wave.abs().max())
    if peak * gain > peak_limit:
        gain = peak_limit / peak
    return wave * gain


def condition_wave(wave, args):
    hz = float(getattr(args, 'wave_highpass_hz', 0.0) or 0.0)
    if hz > 0:
        wave = highpass(wave, hz, sample_rate=args.sample_rate)
    target = getattr(args, 'wave_rms_norm', None)
    if target is not None:
        wave = rms_normalize(wave, float(target))
    return wave


def _rms(wave):
    return float(wave.pow(2).mean().sqrt()) + 1e-8


def augment_wave(wave, p, sample_rate, noise_pool, max_gain_db=6.0, max_shift_s=0.5, snr_db=(15.0, 25.0)):
    """Gain jitter, circular shift and a quiet normal-cycle background; each applied with prob p."""
    if random.random() < p:
        wave = wave * 10.0 ** (random.uniform(-max_gain_db, max_gain_db) / 20.0)
    if random.random() < p:
        max_shift = int(max_shift_s * sample_rate)
        wave = torch.roll(wave, random.randint(-max_shift, max_shift))
    if noise_pool is not None and len(noise_pool) and random.random() < p:
        noise = noise_pool[random.randrange(len(noise_pool))]
        n = min(noise.numel(), wave.numel())
        snr = random.uniform(*snr_db)
        scale = _rms(wave) / (_rms(noise[:n]) * 10.0 ** (snr / 20.0))
        wave = wave.clone()
        wave[:n] = wave[:n] + scale * noise[:n]
    return wave


def or_mix(wave_a, wave_b, low=0.4, high=0.6):
    """Equal-level mix of two cycles; caller assigns the OR of their crackle/wheeze labels."""
    n = min(wave_a.numel(), wave_b.numel())
    a = random.uniform(low, high)
    b_scaled = wave_b[:n] * (_rms(wave_a[:n]) / _rms(wave_b[:n]))
    return a * wave_a[:n] + (1.0 - a) * b_scaled


def or_label(label_a, label_b):
    crackle = label_a in (1, 3) or label_b in (1, 3)
    wheeze = label_a in (2, 3) or label_b in (2, 3)
    return int(crackle) + 2 * int(wheeze)


def dbfs(wave):
    return 20.0 * math.log10(_rms(wave))
