"""Audio processor for media preprocessing."""

import logging
import shutil
from pathlib import Path
from typing import Any, Dict, Optional

from .processor_types import AsyncProcessor, CircuitBreaker, MediaProcessor

logger = logging.getLogger(__name__)


class AudioProcessor(AsyncProcessor):
    """Audio preprocessing with circuit breaker pattern.

    Handles audio format conversion, normalization, and optimization
    for transcription with built-in resilience patterns.
    """

    def __init__(self, name: str = "AudioProcessor", config: Optional[Dict[str, Any]] = None):
        """Initialize audio processor.

        Args:
            name: Processor name
            config: Processor configuration

        """
        super().__init__(name, config)

        # Audio processing settings
        self.target_sample_rate = config.get("sample_rate", 16000) if config else 16000
        self.target_channels = config.get("channels", 1) if config else 1
        self.target_format = config.get("format", "wav") if config else "wav"

        # Circuit breaker for FFmpeg operations
        self.circuit_breaker = CircuitBreaker(
            failure_threshold=config.get("failure_threshold", 5) if config else 5,
            recovery_timeout=config.get("recovery_timeout", 60) if config else 60,
            expected_exception=Exception,
        )

        # Supported formats
        self.supported_formats = {
            ".mp3",
            ".wav",
            ".flac",
            ".aac",
            ".ogg",
            ".m4a",
            ".mp4",
            ".avi",
            ".mov",
            ".mkv",
            ".webm",
        }

    async def process(self, input_path: Path) -> Path:
        """Process audio file with circuit breaker protection.

        Args:
            input_path: Path to input media file

        Returns:
            Path to processed audio file

        Raises:
            ProcessingError: If processing fails
            CircuitBreakerOpen: If circuit breaker is open

        """
        if not self.can_process(input_path):
            raise ValueError(f"Unsupported format: {input_path.suffix}")

        # Use circuit breaker for protection
        async with self.circuit_breaker:
            return await self._process_audio(input_path)

    async def _process_audio(self, input_path: Path) -> Path:
        """Internal audio processing implementation.

        Args:
            input_path: Path to input file

        Returns:
            Path to processed audio

        """
        output_path = input_path.parent / f"{input_path.stem}_processed.{self.target_format}"

        # Simulate audio processing (replace with actual FFmpeg operations)
        logger.info(f"Processing audio: {input_path} -> {output_path}")

        # In real implementation, would use FFmpeg here
        # For now, just copy the file as a placeholder
        if input_path != output_path:
            shutil.copy2(input_path, output_path)

        return output_path

    def can_process(self, input_path: Path) -> bool:
        """Check if processor can handle the file.

        Args:
            input_path: Path to check

        Returns:
            True if file format is supported

        """
        return input_path.suffix.lower() in self.supported_formats

    async def process_async(self, data: Any) -> Any:
        """Async processing interface from base class.

        Args:
            data: Input data (should be a Path)

        Returns:
            Processed result (Path to processed audio)

        """
        if isinstance(data, (str, Path)):
            return await self.process(Path(data))
        raise TypeError(f"Expected Path or str, got {type(data)}")
