"""Unit tests for _analyze_audio_file function."""
import unittest
from pathlib import Path
import numpy as np
import soundfile as sf

from reaper_mcp.audio.audio_analysis import _analyze_audio_file
from tests.base import TempDirTestCase


class TestAnalyzeAudioFile(TempDirTestCase):
    """Tests for the analyze_audio_file function."""
    
    def setUp(self):
        """Set up test parameters."""
        super().setUp()
        self.sample_rate = 44100
        self.duration = 1.0
        self.test_file = self.temp_dir / "test_audio.wav"
    
    def test_analyze_audio_file_success(self):
        """Test successful audio file analysis."""
        # Generate and save test audio
        t = np.linspace(0, self.duration, int(self.sample_rate * self.duration), endpoint=False)
        audio = 0.5 * np.sin(2 * np.pi * 440.0 * t)
        sf.write(self.test_file, audio, self.sample_rate)
        
        result = _analyze_audio_file(self.test_file)
        
        # Check for success
        self.assertNotIn("error", result)
        self.assertIn("analysis", result)
        self.assertEqual(result["analysis"]["estimated_key"], "A")
    
    def test_analyze_audio_file_nonexistent(self):
        """Test analysis of nonexistent file."""
        result = _analyze_audio_file("/nonexistent/file.wav")
        
        # Should return error
        self.assertIn("error", result)
    
    def test_analyze_audio_file_caching(self):
        """Test that analysis results are cached."""
        # Generate and save test audio
        t = np.linspace(0, self.duration, int(self.sample_rate * self.duration), endpoint=False)
        audio = 0.5 * np.sin(2 * np.pi * 440.0 * t)
        sf.write(self.test_file, audio, self.sample_rate)
        
        # First analysis
        result1 = _analyze_audio_file(self.test_file)
        self.assertNotIn("error", result1)
        
        # Check that cache was stored (cache is internal, not a separate file)
        # The function should return cached=False on first call
        self.assertFalse(result1.get("cached", False))
        
        # Second analysis should use cache
        result2 = _analyze_audio_file(self.test_file)
        self.assertNotIn("error", result2)
        
        # Results should be the same
        self.assertEqual(result1["analysis"], result2["analysis"])
