"""
Basic tests for audio direction estimator.
"""

import pytest
import numpy as np
from saltybot_audio_direction.audio_direction_node import GCCPHATBeamformer, VADDetector


class TestGCCPHATBeamformer:
    """Tests for GCC-PHAT beamforming."""

    def test_beamformer_init(self):
        """Test beamformer initialization."""
        beamformer = GCCPHATBeamformer(sample_rate=16000, max_lag=64)
        assert beamformer.sample_rate == 16000
        assert beamformer.max_lag == 64

    def test_gcc_phat_stereo(self):
        """Test GCC-PHAT with stereo signals."""
        beamformer = GCCPHATBeamformer(sample_rate=16000, max_lag=64)

        # Create synthetic stereo: left-delayed signal
        t = np.arange(512) / 16000.0
        sig1 = np.sin(2 * np.pi * 1000 * t)  # Left mic
        sig2 = np.sin(2 * np.pi * 1000 * (t - 0.004))  # Right mic (delayed)

        lag = beamformer.gcc_phat(sig1, sig2)
        # Negative lag indicates left channel leads, expect lag < 0
        assert isinstance(lag, float)

    def test_estimate_bearing_stereo(self):
        """Test bearing estimation for stereo input."""
        beamformer = GCCPHATBeamformer(sample_rate=16000, max_lag=64)

        t = np.arange(512) / 16000.0
        sig1 = np.sin(2 * np.pi * 1000 * t)
        sig2 = np.sin(2 * np.pi * 1000 * t)

        bearing = beamformer.estimate_bearing([sig1, sig2])
        assert 0 <= bearing <= 360

    def test_estimate_bearing_mono(self):
        """Test bearing with mono input defaults to 0°."""
        beamformer = GCCPHATBeamformer(sample_rate=16000)
        sig = np.sin(2 * np.pi * 1000 * np.arange(512) / 16000.0)
        bearing = beamformer.estimate_bearing([sig])
        assert bearing == 0.0


class TestVADDetector:
    """Tests for voice activity detection."""

    def test_vad_init(self):
        """Test VAD detector initialization."""
        vad = VADDetector(threshold=0.02, smoothing=5)
        assert vad.threshold == 0.02
        assert vad.smoothing == 5

    def test_vad_silence(self):
        """Test VAD detects silence."""
        vad = VADDetector(threshold=0.02)
        silence = np.zeros(2048) * 0.001  # Very quiet
        is_speech = vad.detect(silence)
        assert not is_speech

    def test_vad_speech(self):
        """Test VAD detects speech-like signal."""
        vad = VADDetector(threshold=0.02)
        t = np.arange(2048) / 16000.0
        speech = np.sin(2 * np.pi * 1000 * t) * 0.1  # ~0.07 RMS
        for _ in range(5):  # Run multiple times to accumulate history
            is_speech = vad.detect(speech)
        assert is_speech


if __name__ == '__main__':
    pytest.main([__file__])
