"""
Module: src.ingestion.normalizer
Workorder: WO01
Purpose: FFmpeg-based audio normalization to 16kHz mono PCM S16 LE.

Dependencies:
    - pathlib: File path handling
    - shutil: Binary availability checks
    - subprocess: FFmpeg invocation

Inputs:
    - source_path: Source audio file

Outputs:
    - Normalized WAV file path

Key Functions/Classes:
    - normalize_audio: Produces normalized audio asset

Tests: tests/unit/test_placeholder.py
"""
from pathlib import Path
import shutil
import subprocess

from src.shared.errors import ProcessingError


def normalize_audio(
    source_path: Path,
    target_dir: Path = Path("data/processed"),
    sample_rate: int = 16000,
) -> Path:
    """Normalize audio using FFmpeg.

    Args:
        source_path: Input audio path.
        target_dir: Target directory for normalized files.
        sample_rate: Target sample rate in Hz.

    Returns:
        Path to normalized WAV file.

    Raises:
        ProcessingError: If FFmpeg is unavailable or normalization fails.
    """
    ffmpeg_bin = shutil.which("ffmpeg")
    if ffmpeg_bin is None:
        raise ProcessingError(
            "FFmpeg not found in PATH. Please install FFmpeg to normalize audio."
        )

    target_dir.mkdir(parents=True, exist_ok=True)
    output_path = target_dir / f"{source_path.stem}_16k_mono.wav"

    command = [
        ffmpeg_bin,
        "-y",
        "-i",
        str(source_path),
        "-ac",
        "1",
        "-ar",
        str(sample_rate),
        "-c:a",
        "pcm_s16le",
        str(output_path),
    ]

    completed = subprocess.run(
        command,
        capture_output=True,
        text=True,
        check=False,
    )
    if completed.returncode != 0:
        raise ProcessingError(
            "FFmpeg normalization failed: "
            f"{completed.stderr.strip() or completed.stdout.strip()}"
        )

    if not output_path.exists():
        raise ProcessingError("FFmpeg completed but output file was not created.")

    return output_path
