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


class TestGenerateADSREnvelope(TempDirTestCase):
    """Tests for the generate_adsr_envelope function."""
    
    def test_generate_adsr_envelope_basic(self):
        """Test basic ADSR envelope generation."""
        result = generate_adsr_envelope.fn(
            attack=0.1,
            decay=0.2,
            sustain=0.7,
            release=0.3,
            duration=2.0
        )
        
        self.assertNotIn("error", result)
        self.assertIn("envelope", result)
        self.assertIn("sample_rate", result)
        
        # Verify envelope
        envelope = np.array(result["envelope"])
        sr = result["sample_rate"]
        self.assertEqual(sr, 44100)
        
        # Check envelope shape
        # Should start at 0, rise to 1, decay to sustain level, then release to 0
        self.assertAlmostEqual(envelope[0], 0.0, places=2)
        self.assertLess(envelope[-1], 0.1)  # Should end near 0
    
    def test_generate_adsr_envelope_parameters(self):
        """Test ADSR envelope with specific parameters."""
        result = generate_adsr_envelope.fn(
            attack=0.05,
            decay=0.1,
            sustain=0.5,
            release=0.2,
            duration=1.0
        )
        
        self.assertNotIn("error", result)
        self.assertEqual(result["attack"], 0.05)
        self.assertEqual(result["decay"], 0.1)
        self.assertEqual(result["sustain"], 0.5)
        self.assertEqual(result["release"], 0.2)
    
    def test_generate_adsr_envelope_invalid_sustain(self):
        """Test ADSR envelope with invalid sustain level."""
        result = generate_adsr_envelope.fn(
            attack=0.1,
            decay=0.1,
            sustain=1.5,  # Invalid: > 1.0
            release=0.1,
            duration=1.0
        )
        
        self.assertIn("error", result)
