"""Validate and normalize interview audio to mono 16 kHz WAV via FFmpeg."""

from __future__ import annotations

import logging
import os
import shutil
import subprocess
import tempfile
import wave
from dataclasses import dataclass
from pathlib import Path

from app.config import get_settings

logger = logging.getLogger(__name__)

# Magic-byte / extension hints (not authoritative — FFmpeg is the decoder of record)
_MAGIC: list[tuple[bytes, str]] = [
    (b"RIFF", "wav"),
    (b"fLaC", "flac"),
    (b"OggS", "ogg"),
    (b"\xff\xfb", "mp3"),
    (b"\xff\xf3", "mp3"),
    (b"\xff\xf2", "mp3"),
    (b"ID3", "mp3"),
    (b"ftyp", "m4a"),  # appears after 4-byte size
]


class AudioPreprocessError(Exception):
    def __init__(self, message: str, *, code: str = "audio_preprocess_error") -> None:
        self.code = code
        super().__init__(message)


@dataclass
class PreprocessedAudio:
    """Normalized mono PCM ready for Librosa analysis."""

    wav_path: Path
    sample_rate: int
    duration_seconds: float
    channels: int
    source_format_hint: str | None
    warnings: list[str]
    work_dir: Path  # cleaned up by caller via cleanup()

    def cleanup(self) -> None:
        try:
            shutil.rmtree(self.work_dir, ignore_errors=True)
        except Exception:  # noqa: BLE001
            logger.warning("Failed to remove audio work dir", exc_info=True)


def _sniff_format(data: bytes) -> str | None:
    if len(data) < 12:
        return None
    for magic, label in _MAGIC:
        if data.startswith(magic):
            return label
    if data[4:8] == b"ftyp":
        return "m4a"
    return None


def _wav_duration(path: Path) -> tuple[float, int, int]:
    with wave.open(str(path), "rb") as wf:
        rate = wf.getframerate()
        frames = wf.getnframes()
        channels = wf.getnchannels()
        duration = frames / float(rate) if rate else 0.0
        return duration, rate, channels


def preprocess_audio_bytes(
    audio_bytes: bytes,
    *,
    mime_type: str | None = None,
    filename_hint: str | None = None,
) -> PreprocessedAudio:
    """Validate bytes, convert to mono target-rate WAV, return path + metadata.

    Caller MUST call ``result.cleanup()`` (ideally in ``finally``).
    """
    settings = get_settings()
    max_bytes = int(settings.audio_max_upload_bytes)
    min_bytes = int(settings.audio_min_upload_bytes)
    target_sr = int(settings.audio_analysis_sample_rate)
    max_duration = float(settings.audio_max_duration_seconds)
    min_duration = float(settings.audio_min_duration_seconds)
    ffmpeg_bin = settings.ffmpeg_path or "ffmpeg"
    timeout = float(settings.audio_ffmpeg_timeout_seconds)

    warnings: list[str] = []

    if not audio_bytes or len(audio_bytes) < min_bytes:
        raise AudioPreprocessError(
            "Empty or too-small audio payload",
            code="invalid_audio",
        )
    if len(audio_bytes) > max_bytes:
        raise AudioPreprocessError(
            f"Audio exceeds max upload size ({max_bytes} bytes)",
            code="audio_too_large",
        )

    fmt_hint = _sniff_format(audio_bytes)
    if not fmt_hint and mime_type:
        mt = mime_type.lower()
        if "wav" in mt:
            fmt_hint = "wav"
        elif "mpeg" in mt or "mp3" in mt:
            fmt_hint = "mp3"
        elif "mp4" in mt or "m4a" in mt:
            fmt_hint = "m4a"
        elif "ogg" in mt:
            fmt_hint = "ogg"
        elif "flac" in mt:
            fmt_hint = "flac"
        elif "webm" in mt:
            fmt_hint = "webm"

    allowed = {s.strip().lower() for s in settings.audio_allowed_formats.split(",") if s.strip()}
    if fmt_hint and allowed and fmt_hint not in allowed and "webm" not in (fmt_hint or ""):
        # Still attempt FFmpeg decode for webm/opus and unknown-but-plausible payloads
        if fmt_hint not in allowed:
            warnings.append(f"Format hint '{fmt_hint}' outside preferred list; attempting decode")

    work_dir = Path(tempfile.mkdtemp(prefix="tj_audio_"))
    ext = fmt_hint or (Path(filename_hint).suffix.lstrip(".") if filename_hint else "bin")
    if not ext or len(ext) > 8:
        ext = "bin"
    src_path = work_dir / f"input.{ext}"
    out_path = work_dir / "normalized.wav"

    try:
        src_path.write_bytes(audio_bytes)

        cmd = [
            ffmpeg_bin,
            "-y",
            "-hide_banner",
            "-loglevel",
            "error",
            "-i",
            str(src_path),
            "-ac",
            "1",
            "-ar",
            str(target_sr),
            "-c:a",
            "pcm_s16le",
            str(out_path),
        ]
        try:
            proc = subprocess.run(
                cmd,
                capture_output=True,
                timeout=timeout,
                check=False,
            )
        except FileNotFoundError as exc:
            raise AudioPreprocessError(
                "FFmpeg not found — install ffmpeg or set FFMPEG_PATH",
                code="ffmpeg_missing",
            ) from exc
        except subprocess.TimeoutExpired as exc:
            raise AudioPreprocessError(
                "FFmpeg conversion timed out",
                code="ffmpeg_timeout",
            ) from exc

        if proc.returncode != 0 or not out_path.exists() or out_path.stat().st_size < 44:
            err = (proc.stderr or b"").decode("utf-8", errors="replace")[:300]
            logger.info("FFmpeg failed to decode audio (code=%s)", proc.returncode)
            raise AudioPreprocessError(
                f"Unsupported or corrupted audio (ffmpeg: {err or 'decode failed'})",
                code="corrupt_or_unsupported",
            )

        duration, rate, channels = _wav_duration(out_path)
        if duration < min_duration:
            raise AudioPreprocessError(
                f"Audio too short ({duration:.3f}s < {min_duration}s)",
                code="audio_too_short",
            )
        if duration > max_duration:
            raise AudioPreprocessError(
                f"Audio exceeds max duration ({max_duration}s)",
                code="audio_too_long",
            )
        if rate != target_sr:
            warnings.append(f"Unexpected sample rate after convert: {rate}")

        # Near-silence integrity check (all-zero PCM after header)
        pcm = out_path.read_bytes()[44:]
        if pcm and pcm == b"\x00" * len(pcm):
            warnings.append("Decoded audio is complete silence")

        return PreprocessedAudio(
            wav_path=out_path,
            sample_rate=rate,
            duration_seconds=round(duration, 4),
            channels=channels,
            source_format_hint=fmt_hint,
            warnings=warnings,
            work_dir=work_dir,
        )
    except AudioPreprocessError:
        shutil.rmtree(work_dir, ignore_errors=True)
        raise
    except Exception as exc:  # noqa: BLE001
        shutil.rmtree(work_dir, ignore_errors=True)
        raise AudioPreprocessError(
            f"Audio preprocessing failed: {exc}",
            code="audio_preprocess_error",
        ) from exc


def ensure_ffmpeg_available() -> bool:
    settings = get_settings()
    bin_path = settings.ffmpeg_path or "ffmpeg"
    return shutil.which(bin_path) is not None or os.path.isfile(bin_path)
