"""Unit tests for _estimate_key function."""
import unittest
import numpy as np

from reaper_mcp.audio.audio_analysis import _estimate_key


class TestEstimateKey(unittest.TestCase):
    """Tests for the _estimate_key function."""
    
    def setUp(self):
        """Set up test parameters."""
        self.sample_rate = 44100
        self.duration = 2.0  # 2 seconds
        
    def _generate_tone(self, frequency: float) -> np.ndarray:
        """Generate a simple sine wave tone."""
        t = np.linspace(0, self.duration, int(self.sample_rate * self.duration), endpoint=False)
        return 0.5 * np.sin(2 * np.pi * frequency * t)
    
    def test_estimate_key_a4(self):
        """Test key estimation with A4 (440 Hz) - should detect A."""
        audio = self._generate_tone(440.0)
        key = _estimate_key(audio, self.sample_rate)
        self.assertEqual(key, "A", f"Expected 'A' but got '{key}'")
    
    def test_estimate_key_c4(self):
        """Test key estimation with C4 (261.63 Hz) - should detect C."""
        audio = self._generate_tone(261.63)
        key = _estimate_key(audio, self.sample_rate)
        self.assertEqual(key, "C", f"Expected 'C' but got '{key}'")
    
    def test_estimate_key_e4(self):
        """Test key estimation with E4 (329.63 Hz) - should detect E."""
        audio = self._generate_tone(329.63)
        key = _estimate_key(audio, self.sample_rate)
        self.assertEqual(key, "E", f"Expected 'E' but got '{key}'")
    
    def test_estimate_key_g4(self):
        """Test key estimation with G4 (392.00 Hz) - should detect G."""
        audio = self._generate_tone(392.00)
        key = _estimate_key(audio, self.sample_rate)
        self.assertEqual(key, "G", f"Expected 'G' but got '{key}'")
    
    def test_estimate_key_d4(self):
        """Test key estimation with D4 (293.66 Hz) - should detect D."""
        audio = self._generate_tone(293.66)
        key = _estimate_key(audio, self.sample_rate)
        self.assertEqual(key, "D", f"Expected 'D' but got '{key}'")
    
    def test_estimate_key_f4(self):
        """Test key estimation with F4 (349.23 Hz) - should detect F."""
        audio = self._generate_tone(349.23)
        key = _estimate_key(audio, self.sample_rate)
        self.assertEqual(key, "F", f"Expected 'F' but got '{key}'")
    
    def test_estimate_key_silence(self):
        """Test key estimation with silence - should return default 'C'."""
        audio = np.zeros(int(self.sample_rate * self.duration))
        key = _estimate_key(audio, self.sample_rate)
        self.assertEqual(key, "C", f"Expected 'C' for silence but got '{key}'")
    
    def test_estimate_key_empty_array(self):
        """Test key estimation with empty array - should return default 'C'."""
        audio = np.array([])
        key = _estimate_key(audio, self.sample_rate)
        self.assertEqual(key, "C", f"Expected 'C' for empty array but got '{key}'")
