"""Integration tests for media service interactions."""

import pytest
from pathlib import Path

from src.services.mocks import create_mock_media_service
from src.services.protocols import MediaServiceProtocol


class TestMediaServiceIntegration:
    """Test media service interactions and workflows."""

    @pytest.fixture
    def media_service(self):
        """Create mock media service for testing."""
        return create_mock_media_service()

    @pytest.mark.asyncio
    async def test_media_download_workflow(self, media_service):
        """Test complete media download workflow."""
        url = "https://example.com/test.mp3"
        output_dir = Path("/tmp/test_output")
        
        media_info = await media_service.download_media(url, output_dir)
        
        assert media_info.file_path == output_dir / "mock_download.wav"
        assert media_info.file_size == 1024000
        assert media_info.duration == 120.5
        assert media_info.format == "wav"
        assert media_info.sample_rate == 16000
        assert media_info.channels == 1

    @pytest.mark.asyncio
    async def test_audio_preprocessing_workflow(self, media_service):
        """Test audio preprocessing workflow."""
        input_path = Path("/tmp/input.mp3")
        output_path = Path("/tmp/output.wav")
        
        success = await media_service.preprocess_audio(input_path, output_path)
        assert success is True

    @pytest.mark.asyncio
    async def test_file_validation_operations(self, media_service):
        """Test file validation operations."""
        # Test file size validation
        is_valid = await media_service.validate_file_size(Path("/tmp/test.wav"), max_size_mb=1)
        assert is_valid is True
        
        # Test with larger max size
        is_valid = await media_service.validate_file_size(Path("/tmp/test.wav"), max_size_mb=2)
        assert is_valid is True
        
        # Test with smaller max size (should fail)
        is_valid = await media_service.validate_file_size(Path("/tmp/test.wav"), max_size_mb=0.5)
        assert is_valid is False

    @pytest.mark.asyncio
    async def test_audio_quality_checks(self, media_service):
        """Test audio quality checking operations."""
        quality_ok = await media_service.check_audio_quality(Path("/tmp/test.wav"))
        assert quality_ok is True

    @pytest.mark.asyncio
    async def test_media_info_extraction(self, media_service):
        """Test media information extraction."""
        info = await media_service.get_media_info(Path("/tmp/test.wav"))
        
        assert info["file_path"] == "/tmp/mock_audio.wav"
        assert info["file_size"] == 1024000
        assert info["duration"] == 120.5
        assert info["format"] == "wav"
        assert info["sample_rate"] == 16000
        assert info["channels"] == 1

    @pytest.mark.asyncio
    async def test_media_file_record_operations(self, media_service):
        """Test media file record operations."""
        from src.services.protocols import MediaFileInfo
        
        media_info = MediaFileInfo(
            file_path=Path("/tmp/test.wav"),
            file_size=1024000,
            duration=120.5,
            format="wav",
            sample_rate=16000,
            channels=1
        )
        
        # Test record creation
        media_file = await media_service.create_media_file_record(media_info)
        assert media_file is not None
        assert hasattr(media_file, 'id')
        assert hasattr(media_file, 'file_path')
        assert hasattr(media_file, 'file_size')
        
        # Test record retrieval
        retrieved_file = await media_service.get_media_file_by_id(media_file.id)
        assert retrieved_file is not None
        assert retrieved_file.id == media_file.id

    @pytest.mark.asyncio
    async def test_media_pipeline_workflow(self, media_service):
        """Test complete media processing pipeline."""
        url = "https://youtube.com/watch?v=test123"
        output_dir = Path("/tmp/test_pipeline")
        
        media_file = await media_service.process_media_pipeline(url, output_dir)
        
        assert media_file is not None
        assert hasattr(media_file, 'id')
        assert hasattr(media_file, 'file_path')
        assert hasattr(media_file, 'file_size')

    @pytest.mark.asyncio
    async def test_progress_callback_functionality(self, media_service):
        """Test progress callback functionality in media operations."""
        progress_updates = []
        
        def progress_callback(progress: float, message: str):
            progress_updates.append((progress, message))
        
        # Test download with progress callback
        await media_service.download_media(
            "https://example.com/test.mp3",
            Path("/tmp"),
            progress_callback
        )
        
        # Verify progress updates were called
        assert len(progress_updates) > 0
        assert progress_updates[0][0] == 0.25
        assert progress_updates[-1][0] == 1.0
        
        # Test preprocessing with progress callback
        progress_updates.clear()
        await media_service.preprocess_audio(
            Path("/tmp/input.mp3"),
            Path("/tmp/output.wav"),
            progress_callback
        )
        
        assert len(progress_updates) > 0
        assert progress_updates[0][0] == 0.33
        assert progress_updates[-1][0] == 1.0

    @pytest.mark.asyncio
    async def test_service_protocol_compliance(self, media_service):
        """Test that media service properly implements its protocol."""
        from src.services.protocols import validate_protocol_implementation, MediaServiceProtocol
        
        assert validate_protocol_implementation(media_service, MediaServiceProtocol)


if __name__ == "__main__":
    pytest.main([__file__])
