"""Unit tests for reverseAudio function."""
import unittest
from pathlib import Path
import numpy as np
import soundfile as sf
from reaper_mcp.audio.audio_processing import reverse_audio
from tests.base import TempDirTestCase


class TestReverseAudio(TempDirTestCase):
    """Tests for the reverse_audio function."""
    
    def setUp(self):
        """Set up test fixtures."""
        super().setUp()
        self.test_file = self.temp_dir / "test_audio.wav"
        
        # Create a simple test audio file with ascending frequency
        sample_rate = 44100
        duration = 1.0
        t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
        # Linear frequency sweep from 200 to 800 Hz
        freq = 200 + 600 * t / duration
        audio = 0.5 * np.sin(2 * np.pi * freq * t)
        sf.write(self.test_file, audio, sample_rate)
    
    def test_reverse_audio_basic(self):
        """Test basic audio reversal."""
        result = reverse_audio(self.test_file)
        
        self.assertNotIn("error", result)
        self.assertIn("file_path", result)
        self.assertTrue(Path(result["file_path"]).exists())
        
        # Verify audio is reversed
        original_audio, sr = sf.read(self.test_file)
        reversed_audio, _ = sf.read(result["file_path"])
        
        # Check that first samples of reversed match last samples of original
        np.testing.assert_array_almost_equal(
            reversed_audio[:100],
            original_audio[-100:][::-1],
            decimal=5
        )
        
        # Clean up
        Path(result["file_path"]).unlink()
    
    def test_reverse_audio_length(self):
        """Test that reversed audio has same length."""
        result = reverse_audio(self.test_file)
        
        original_audio, _ = sf.read(self.test_file)
        reversed_audio, _ = sf.read(result["file_path"])
        
        self.assertEqual(len(reversed_audio), len(original_audio))
        
        # Clean up
        Path(result["file_path"]).unlink()
    
    def test_reverse_audio_nonexistent_file(self):
        """Test reversing nonexistent file."""
        result = reverse_audio("/nonexistent/file.wav")
        
        self.assertIn("error", result)
