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


class TestPitchShiftAudio(TempDirTestCase):
    """Tests for the pitch_shift_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
        sample_rate = 44100
        duration = 1.0
        t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
        audio = 0.5 * np.sin(2 * np.pi * 440.0 * t)
        sf.write(self.test_file, audio, sample_rate)
    
    def test_pitch_shift_up(self):
        """Test shifting pitch up."""
        result = pitch_shift_audio(self.test_file, semitones=3.0)
        
        self.assertNotIn("error", result)
        self.assertIn("file_path", result)
        self.assertTrue(Path(result["file_path"]).exists())
        
        # Verify audio exists
        audio, sr = sf.read(result["file_path"])
        original_audio, _ = sf.read(self.test_file)
        
        # Note: Simple pitch shifting changes duration (documented in function's return "note")
        # Verify that duration changed in expected direction (shorter for upward shift)
        self.assertLess(len(audio), len(original_audio))
        
        # Clean up
        Path(result["file_path"]).unlink()
    
    def test_pitch_shift_down(self):
        """Test shifting pitch down."""
        result = pitch_shift_audio(self.test_file, semitones=-5.0)
        
        self.assertNotIn("error", result)
        self.assertTrue(Path(result["file_path"]).exists())
        
        # Clean up
        Path(result["file_path"]).unlink()
    
    def test_pitch_shift_zero(self):
        """Test pitch shift with 0 semitones (no change)."""
        result = pitch_shift_audio(self.test_file, semitones=0.0)
        
        self.assertNotIn("error", result)
        self.assertTrue(Path(result["file_path"]).exists())
        
        # Clean up
        Path(result["file_path"]).unlink()
    
    def test_pitch_shift_octave(self):
        """Test shifting up one octave (12 semitones)."""
        result = pitch_shift_audio(self.test_file, semitones=12.0)
        
        self.assertNotIn("error", result)
        self.assertTrue(Path(result["file_path"]).exists())
        
        # Clean up
        Path(result["file_path"]).unlink()
    
    def test_pitch_shift_nonexistent_file(self):
        """Test pitch shifting nonexistent file."""
        result = pitch_shift_audio("/nonexistent/file.wav", semitones=3.0)
        
        self.assertIn("error", result)
