#!/usr/bin/env python3
"""Testes unitários da refinagem orange (sem mídia real)."""
import numpy as np
import refine_orange as ro


def test_rms_normalize_levels_match():
    a = np.random.randn(8000) * 0.01
    b = np.random.randn(8000) * 2.0
    na = ro.rms_normalize(a, target=0.1)
    nb = ro.rms_normalize(b, target=0.1)
    ra = np.sqrt(np.mean(na ** 2))
    rb = np.sqrt(np.mean(nb ** 2))
    assert abs(ra - 0.1) < 0.02
    assert abs(rb - 0.1) < 0.02
    # volumes brutos muito diferentes, RMS após norm ~igual
    assert abs(ra - rb) < 0.02


def test_local_xcorr_recovers_known_lag():
    # PCM: spine com evento; clip = evento; atraso conhecido 0.3s @ 2kHz
    rate = 2000.0
    left_pad = 1.5
    delay_s = 0.3
    delay_bins = int(delay_s * rate)
    pad = int(left_pad * rate)
    rng = np.random.default_rng(1)
    clip = rng.standard_normal(int(0.8 * rate))
    clip[200:600] += 4.0
    spine_seg = np.zeros(pad + delay_bins + len(clip) + pad)
    start = pad + delay_bins
    spine_seg[start:start + len(clip)] = clip
    # volumes diferentes — RMS norm dentro do xcorr
    lag_s, ratio = ro.local_xcorr_lag(spine_seg * 0.05, clip * 3.0, rate, left_pad)
    assert lag_s is not None
    delta = lag_s - left_pad
    assert abs(delta - delay_s) < 0.02, (delta, delay_s, ratio)
    assert ratio > 2.5


def test_basename_from_placement_name():
    assert ro.basename_from_placement_name("cam1_marcelo_C8196", "cam1_marcelo") == "C8196"
    assert ro.basename_from_placement_name("cam2_rafa_C0056", "cam2_rafa") == "C0056"


def test_clip_use_s_short_vs_long():
    # Pass2 full_clip: clip de 1.5s usa ~1.5s (não força 3s)
    assert abs(ro.clip_use_s(1.5, full_clip=True) - 1.5) < 1e-9
    assert ro.clip_use_s(0.3, full_clip=True) >= 0.6
    # Pass1: mínimo 3s
    assert ro.clip_use_s(1.5, full_clip=False) == 3.0
    assert ro.clip_use_s(40.0, full_clip=False) == ro.CLIP_USE_S


if __name__ == "__main__":
    test_rms_normalize_levels_match()
    test_local_xcorr_recovers_known_lag()
    test_basename_from_placement_name()
    test_clip_use_s_short_vs_long()
    print("test_refine_orange: OK")
