"""Audio extraction utilities using ffmpeg."""

import shutil
import subprocess
import tempfile
from pathlib import Path

VIDEO_EXTENSIONS = {".mp4", ".mkv", ".avi", ".mov", ".webm", ".flv", ".wmv", ".m4v"}
AUDIO_EXTENSIONS = {".mp3", ".wav", ".flac", ".aac", ".ogg", ".m4a", ".wma"}


def is_video_file(path: Path) -> bool:
    """Check if file is a video based on extension."""
    return path.suffix.lower() in VIDEO_EXTENSIONS


def is_audio_file(path: Path) -> bool:
    """Check if file is an audio based on extension."""
    return path.suffix.lower() in AUDIO_EXTENSIONS


def check_ffmpeg() -> bool:
    """Check if ffmpeg is available."""
    return shutil.which("ffmpeg") is not None


def extract_audio(
    input_path: Path,
    output_path: Path | None = None,
    *,
    sample_rate: int = 16000,
    channels: int = 1,
) -> Path:
    """
    Extract audio from video file using ffmpeg.

    Args:
        input_path: Path to video file
        output_path: Output path for audio file (optional, uses temp file if not provided)
        sample_rate: Audio sample rate (default 16000 Hz, optimal for speech)
        channels: Number of audio channels (default 1, mono)

    Returns:
        Path to extracted audio file
    """
    if not check_ffmpeg():
        raise RuntimeError(
            "ffmpeg not found. Install it with:\n"
            "  macOS: brew install ffmpeg\n"
            "  Ubuntu: sudo apt install ffmpeg\n"
            "  Windows: choco install ffmpeg"
        )

    if output_path is None:
        temp_dir = tempfile.gettempdir()
        output_path = Path(temp_dir) / f"{input_path.stem}_audio.wav"

    cmd = [
        "ffmpeg",
        "-i", str(input_path),
        "-vn",  # No video
        "-acodec", "pcm_s16le",  # PCM 16-bit
        "-ar", str(sample_rate),
        "-ac", str(channels),
        "-y",  # Overwrite output
        str(output_path),
    ]

    result = subprocess.run(
        cmd,
        capture_output=True,
        text=True,
    )

    if result.returncode != 0:
        raise RuntimeError(f"ffmpeg failed: {result.stderr}")

    return output_path


def prepare_audio(input_path: Path) -> tuple[Path, bool]:
    """
    Prepare audio for transcription.

    If input is a video file, extracts audio. Otherwise returns the original path.

    Returns:
        Tuple of (audio_path, is_temp_file)
        is_temp_file indicates if the returned path should be deleted after use
    """
    if is_video_file(input_path):
        audio_path = extract_audio(input_path)
        return audio_path, True
    return input_path, False
