"""Unit tests for applyEnvelopeToWaveform function."""
import unittest
from pathlib import Path
import numpy as np
import soundfile as sf
from reaper_mcp.audio.waveform_generation import apply_envelope_to_waveform
from tests.base import TempDirTestCase


class TestApplyEnvelopeToWaveform(TempDirTestCase):
    """Tests for the apply_envelope_to_waveform function."""
    
    def setUp(self):
        """Set up test fixtures."""
        super().setUp()
        self.test_file = self.temp_dir / "test_waveform.wav"
        
        # Create a simple test waveform
        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_apply_envelope_basic(self):
        """Test applying envelope to waveform."""
        result = apply_envelope_to_waveform.fn(
            waveform_file=self.test_file,
            attack=0.1,
            decay=0.1,
            sustain=0.7,
            release=0.2
        )
        
        self.assertNotIn("error", result)
        self.assertIn("file_path", result)
        self.assertTrue(Path(result["file_path"]).exists())
        
        # Verify output audio
        audio, sr = sf.read(result["file_path"])
        self.assertEqual(sr, 44100)
        
        # Envelope should reduce amplitude at start and end
        original_audio, _ = sf.read(self.test_file)
        self.assertLess(np.max(np.abs(audio[:1000])), np.max(np.abs(original_audio[:1000])))
        
        # Clean up
        Path(result["file_path"]).unlink()
    
    def test_apply_envelope_nonexistent_file(self):
        """Test applying envelope to nonexistent file."""
        result = apply_envelope_to_waveform.fn(
            waveform_file="/nonexistent/file.wav"
        )
        
        self.assertIn("error", result)
