"""Zero-init crackle flux residual and the impulse-versus-tone contrast."""

import math

import torch
import torch.nn.functional as F

from method.crackle_flux import (
    CrackleFluxResidual,
    add_crackle_flux,
    fine_crackle_features,
)
from method.frame_asd import FrameASDHead


def _tone_and_impulses(n=16000):
    t = torch.arange(n, dtype=torch.float32) / 16000.0
    tone = torch.sin(2.0 * math.pi * 400.0 * t)
    tone = tone / tone.std().clamp(min=1e-6)
    impulse = torch.zeros(n)
    impulse[800:803] = 1.0
    impulse[6400:6403] = -1.0
    impulse[12000:12003] = 1.0
    impulse = impulse / impulse.std().clamp(min=1e-6)
    return tone, impulse


def test_impulse_train_has_higher_flux_and_kurtosis_than_a_tone():
    tone, impulse = _tone_and_impulses()
    feat_tone = fine_crackle_features(tone.unsqueeze(0), n_time=10)
    feat_impulse = fine_crackle_features(impulse.unsqueeze(0), n_time=10)
    assert float(feat_impulse[0, :, 0].max()) > float(feat_tone[0, :, 0].max())
    assert float(feat_impulse[0, :, 1].max()) > float(feat_tone[0, :, 1].max())


def test_zero_init_residual_matches_the_base_crackle_logit():
    torch.manual_seed(0)
    head = FrameASDHead(16)
    head.crackle_flux = CrackleFluxResidual(n_freq=8)
    frames = torch.randn(2, 16, 16)
    waves = torch.randn(2, 8000)
    head.eval()
    logit_c, logit_w = head(frames)
    shifted = add_crackle_flux(head, logit_c, waves)
    assert torch.allclose(shifted, logit_c, atol=1e-6)
    assert head.crackle_flux.proj.weight.abs().sum() == 0


def test_time_residual_is_constant_inside_each_frequency_group():
    branch = CrackleFluxResidual(n_freq=4)
    with torch.no_grad():
        branch.proj.weight.fill_(1.0)
        branch.proj.bias.fill_(0.4)
        branch.norm.weight.fill_(1.0)
        branch.norm.bias.zero_()
    waves = torch.randn(1, 8000)
    delta = branch(waves, n_tokens=8)
    assert delta.shape == (1, 8)
    assert torch.allclose(delta[:, 0:4], delta[:, :1].expand_as(delta[:, 0:4]))
    assert torch.allclose(delta[:, 4:8], delta[:, 4:5].expand_as(delta[:, 4:8]))


def test_frozen_head_trains_only_the_flux_projection():
    torch.manual_seed(0)
    head = FrameASDHead(8)
    head.crackle_flux = CrackleFluxResidual(n_freq=4)
    for param in head.parameters():
        param.requires_grad = False
    for param in head.crackle_flux.parameters():
        param.requires_grad = True
    waves = torch.randn(2, 4000)
    base = torch.zeros(2, 8)
    logit_c = add_crackle_flux(head, base, waves)
    target = torch.ones(2)
    loss = F.binary_cross_entropy_with_logits(logit_c.mean(dim=1), target)
    loss.backward()
    assert head.crackle.weight.grad is None
    assert head.crackle_flux.proj.weight.grad is not None
    assert float(head.crackle_flux.proj.weight.grad.abs().sum()) > 0
