"""Extract audio track from interview video bytes via FFmpeg (reuse system binary)."""

from __future__ import annotations

import io
import logging
import math
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__)


def wav_pcm16_rms(wav_bytes: bytes) -> float | None:
    """Return RMS of mono/stereo 16-bit PCM WAV samples, or None if unreadable."""
    try:
        with wave.open(io.BytesIO(wav_bytes), "rb") as wf:
            n_channels = wf.getnchannels()
            sampwidth = wf.getsampwidth()
            n_frames = wf.getnframes()
            if sampwidth != 2 or n_frames <= 0 or n_channels < 1:
                return None
            raw = wf.readframes(n_frames)
    except Exception:  # noqa: BLE001
        return None
    if len(raw) < 2:
        return None
    # Interpret as little-endian int16
    import array

    samples = array.array("h")
    samples.frombytes(raw[: len(raw) - (len(raw) % 2)])
    if not samples:
        return None
    acc = 0.0
    for s in samples:
        acc += float(s) * float(s)
    return math.sqrt(acc / len(samples))


def wav_duration_ms(wav_bytes: bytes) -> int | None:
    """Duration of a PCM WAV in milliseconds, or None if unreadable."""
    try:
        with wave.open(io.BytesIO(wav_bytes), "rb") as wf:
            rate = wf.getframerate()
            frames = wf.getnframes()
            if rate <= 0 or frames <= 0:
                return None
            return int(round(frames / float(rate) * 1000.0))
    except Exception:  # noqa: BLE001
        return None


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


@dataclass
class DemuxedAudio:
    wav_bytes: bytes
    warnings: list[str]
    work_dir: Path | None = None

    def cleanup(self) -> None:
        if self.work_dir is not None:
            shutil.rmtree(self.work_dir, ignore_errors=True)


def extract_audio_wav_from_video(
    video_bytes: bytes,
    *,
    filename_hint: str = "clip.mp4",
    timeout: float | None = None,
) -> DemuxedAudio:
    """Demux to mono 16 kHz PCM WAV for STT. Raises VideoAudioError on failure."""
    settings = get_settings()
    ffmpeg_bin = settings.ffmpeg_path or "ffmpeg"
    timeout = float(timeout if timeout is not None else settings.video_ffmpeg_timeout_seconds)
    max_bytes = int(settings.video_transcript_max_audio_bytes)

    work = Path(tempfile.mkdtemp(prefix="tj_vid_audio_"))
    suffix = Path(filename_hint).suffix or ".mp4"
    src = work / f"input{suffix}"
    out = work / "audio.wav"
    src.write_bytes(video_bytes)

    cmd = [
        ffmpeg_bin,
        "-y",
        "-hide_banner",
        "-loglevel",
        "error",
        "-i",
        str(src),
        "-vn",
        "-ac",
        "1",
        "-ar",
        "16000",
        "-c:a",
        "pcm_s16le",
        str(out),
    ]
    warnings: list[str] = []
    try:
        proc = subprocess.run(cmd, capture_output=True, timeout=timeout, check=False)
    except FileNotFoundError as exc:
        shutil.rmtree(work, ignore_errors=True)
        raise VideoAudioError(
            "FFmpeg not found — install ffmpeg or set FFMPEG_PATH",
            code="ffmpeg_missing",
        ) from exc
    except subprocess.TimeoutExpired as exc:
        shutil.rmtree(work, ignore_errors=True)
        raise VideoAudioError("FFmpeg audio demux timed out", code="ffmpeg_timeout") from exc

    if proc.returncode != 0 or not out.exists() or out.stat().st_size < 44:
        err = (proc.stderr or b"").decode("utf-8", errors="replace")[:300]
        shutil.rmtree(work, ignore_errors=True)
        # Common: video has no audio stream
        lower = err.lower()
        if "does not contain any stream" in lower or "no audio" in lower or "stream map" in lower:
            raise VideoAudioError(
                "No audio track in video (silent or video-only)",
                code="no_audio_track",
            )
        raise VideoAudioError(
            f"Could not extract audio (ffmpeg: {err or 'decode failed'})",
            code="audio_demux_failed",
        )

    wav = out.read_bytes()
    if len(wav) > max_bytes:
        shutil.rmtree(work, ignore_errors=True)
        raise VideoAudioError(
            f"Extracted audio exceeds max size ({max_bytes} bytes)",
            code="audio_too_large",
        )
    if len(wav) < 1000:
        warnings.append("Extracted audio is very short — transcript may be empty")

    rms = wav_pcm16_rms(wav)
    # Near-silent track is still a valid demux; STT may return empty_transcript.
    if rms is not None and rms < 30.0:
        warnings.append(
            f"Extracted audio appears near-silent (rms={rms:.1f}) — "
            "transcript may be empty"
        )

    return DemuxedAudio(wav_bytes=wav, warnings=warnings, work_dir=work)
