"""ffmpeg normalization for voice uploads.

Headline: NORMALIZE AGGRESSIVELY, DENOISE BARELY.

Whisper-family models are trained on ~680k hours of uncurated noisy audio and
are robust to broadband noise by construction. Spectral-subtraction denoising
trades noise energy for musical noise and transient smearing — artifacts
*outside* the training distribution that measurably RAISE word error rate on
lightly-noisy audio. The browser is already running a WebRTC RNNoise-class
suppressor via `noiseSuppression: true`; stacking a second denoiser on top is
the worst case.

So this stage earns its place on format normalization and three wins that have
nothing to do with noise:
  * 16 kHz mono s16 is the models' native input — anything else forces an
    internal resample we don't control and inflates the upload 3-6x.
  * Deterministic payload size: exactly 32 kB/s.
  * **Chrome's MediaRecorder WebM has no duration in its header** (streamed
    container, the Segment Duration is never back-patched), a well-known cause
    of ASR-side "0-second file" failures. Re-muxing writes a correct, seekable
    WAV header. THIS FIX ALONE JUSTIFIES THE STAGE.
"""

import asyncio
import logging
import os
import shutil

logger = logging.getLogger(__name__)

VOICE_FFMPEG_ENABLED = os.getenv("VOICE_FFMPEG_ENABLED", "auto").strip().lower()
VOICE_FFMPEG_FILTER = os.getenv(
    "VOICE_FFMPEG_FILTER",
    "highpass=f=80,"
    "silenceremove=start_periods=1:start_duration=0.1:start_threshold=-50dB:detection=peak,"
    "speechnorm=e=12.5:r=0.0001:l=1",
)
VOICE_FFMPEG_TIMEOUT_SEC = float(os.getenv("VOICE_FFMPEG_TIMEOUT_SEC", 20))
# Phase 1 limit: 60 seconds, 10 MB (VOICE_MAX_UPLOAD_BYTES in audio_intake).
# The browser reads this back from /voice/config and enforces it locally too,
# so a doomed recording auto-stops instead of uploading and being refused.
# Raising it here raises it in the browser as well — which is why the default
# has to BE the approved number rather than merely allow it.
VOICE_MAX_DURATION_SEC = int(os.getenv("VOICE_MAX_DURATION_SEC", 60))
# Below this much surviving audio there is no utterance any ASR can use, and
# the upstream does not fail gracefully on one: a 0-frame WAV comes back as
# 502 "WhisperX returned a non-JSON response", which we would then relay as an
# upstream error and blame a service that was working perfectly. 0.2s is under
# the length of the shortest real word ("yes" is roughly twice that), so this
# rejects empty audio without rejecting terse answers. Tunable because it is a
# judgement call, not a constant of nature.
VOICE_MIN_SPEECH_SEC = float(os.getenv("VOICE_MIN_SPEECH_SEC", 0.2))

# Resolved once at import so tests can monkeypatch a module-level name rather
# than the PATH.
def _resolve_ffmpeg() -> str | None:
    """An explicit path first, then PATH, then the bundled binary.

    VOICE_FFMPEG_PATH exists because PATH resolution proved unreliable in a
    real deployment. On one host `shutil.which("ffmpeg")` returned
    /bin/ffmpeg from the service user's shell while the running service — same
    user, restarted long after ffmpeg was installed — resolved nothing, and
    every recording came back 502. systemd starts a unit with its own
    environment, so "it works in my shell" says very little about what the
    process sees.

    An absolute path settles it: no PATH, no login profile, no sandbox view.
    Set it and the question stops being a question.

    The fallback is not a convenience — it is what makes voice work at all.
    The upstream ASR accepts ONLY WAV/PCM: a live round-trip showed it reject
    webm/opus, ogg/opus and mp4/AAC alike, which is every container a browser
    can actually record in. Without a transcode step, dictation fails in
    Chrome, Edge, Firefox and Safari — i.e. everywhere — and the failure
    surfaces as a generic upstream error that says nothing about format.

    So a deployment without ffmpeg on PATH is not a degraded mode here, it is
    a broken one. imageio-ffmpeg ships a static binary as an ordinary Python
    dependency, which makes the working configuration the default instead of
    something each environment has to remember to install.
    """
    pinned = os.getenv("VOICE_FFMPEG_PATH", "").strip()
    if pinned:
        if os.path.isfile(pinned) and os.access(pinned, os.X_OK):
            logger.info("Using pinned ffmpeg: %s", pinned)
            return pinned
        # Loud, because someone set this deliberately and it is wrong — falling
        # through silently is how a deployment ends up quietly broken again.
        logger.error(
            "VOICE_FFMPEG_PATH=%r is not an executable file. Falling back to "
            "PATH lookup; fix the path or unset it.", pinned)

    found = shutil.which("ffmpeg")
    if found:
        return found
    try:
        import imageio_ffmpeg
        return imageio_ffmpeg.get_ffmpeg_exe()
    except Exception as e:
        logger.warning(
            "No ffmpeg on PATH and imageio-ffmpeg is unavailable (%s). Audio will be "
            "forwarded untranscoded, which the ASR rejects for every browser "
            "container - voice dictation will not work until this is fixed.", e)
        return None


_FFMPEG_BIN = _resolve_ffmpeg()
# ffprobe is optional: it only sharpens the duration gate. ffmpeg's own -t cap
# still bounds the transcode when it is missing, and imageio-ffmpeg ships
# ffmpeg alone.
_FFPROBE_BIN = shutil.which("ffprobe")

_WAV_HEADER_BYTES = 44
_WAV_BYTES_PER_SECOND = 16000 * 2  # 16 kHz * s16 mono


class PreprocessError(Exception):
    def __init__(self, status_code: int, error_code: str, detail: str):
        self.status_code = status_code
        self.error_code = error_code
        self.detail = detail
        super().__init__(detail)


def ffmpeg_available() -> bool:
    if VOICE_FFMPEG_ENABLED == "false":
        return False
    return _FFMPEG_BIN is not None


def status() -> dict:
    return {
        "mode": VOICE_FFMPEG_ENABLED,
        "ffmpeg": _FFMPEG_BIN,
        "ffprobe": _FFPROBE_BIN,
        "available": ffmpeg_available(),
        "filter": VOICE_FFMPEG_FILTER or "(none — format normalization only)",
    }


async def _run(argv: list, timeout: float):
    """Run a subprocess off the event loop WITHOUT consuming a threadpool slot.

    `asyncio.create_subprocess_exec`, not `run_in_threadpool(subprocess.run)`,
    for two codebase-specific reasons:
      1. Starlette's threadpool is capped (anyio default 40) and this service
         routes essentially ALL its I/O through it — save_message, store_hr_log,
         get_context, record_usage. A 2-4s ffmpeg run holding a token directly
         starves DB writes for every other in-flight chat request.
      2. A hung ffmpeg under subprocess.run in a thread CANNOT be killed:
         wait_for cancels the awaitable, not the thread, and the token leaks
         permanently.
    `exec`, never `shell`.
    """
    try:
        proc = await asyncio.create_subprocess_exec(
            *argv,
            stdout=asyncio.subprocess.DEVNULL,
            stderr=asyncio.subprocess.PIPE,
        )
    except NotImplementedError:
        # Raised under a non-Proactor event loop on Windows. Without this
        # fallback the failure mode is a 500 on every single request.
        from fastapi.concurrency import run_in_threadpool
        import subprocess

        def _blocking():
            return subprocess.run(argv, stdout=subprocess.DEVNULL,
                                  stderr=subprocess.PIPE, timeout=timeout)

        completed = await run_in_threadpool(_blocking)
        return completed.returncode, completed.stderr or b""

    try:
        _, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
    except asyncio.TimeoutError:
        proc.kill()
        await proc.wait()  # reap, or the zombie lingers
        raise PreprocessError(504, "audio_preprocess_timeout",
                              "Processing that recording took too long.")
    return proc.returncode, stderr or b""


async def probe_duration(path: str):
    """Seconds, or None if ffprobe is unavailable or the container lies."""
    if not _FFPROBE_BIN:
        return None
    argv = [_FFPROBE_BIN, "-v", "error", "-show_entries", "format=duration",
            "-of", "default=noprint_wrappers=1:nokey=1", path]
    try:
        proc = await asyncio.create_subprocess_exec(
            *argv, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL)
        stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=10)
    except (NotImplementedError, asyncio.TimeoutError, OSError):
        return None
    try:
        return float(stdout.decode().strip())
    except (ValueError, AttributeError):
        return None


async def preprocess(payload: bytes, workspace: str, extension: str) -> dict:
    """Normalize to 16 kHz mono s16 WAV.

    Returns {audio, preprocessed, filter_chain, duration_s, trim_offset_s}.
    Falls back to pass-through (returning the original bytes) whenever ffmpeg
    is unavailable in `auto` mode — the upstream accepts webm/mp4/ogg directly,
    so that is a genuinely acceptable degraded mode, surfaced to the caller as
    preprocessed=false so a quality complaint can be correlated.
    """
    if not ffmpeg_available():
        if VOICE_FFMPEG_ENABLED == "true":
            # Required but missing: fail the REQUEST, not startup. A
            # misconfigured node should be diagnosable, not crash-looping.
            raise PreprocessError(503, "audio_preprocess_unavailable",
                                  "Audio processing is unavailable on this server.")
        return {"audio": payload, "preprocessed": False, "filter_chain": None,
                "duration_s": None, "trim_offset_s": 0.0}

    in_path = os.path.join(workspace, f"in{extension}")
    out_path = os.path.join(workspace, "out.wav")
    with open(in_path, "wb") as fh:
        fh.write(payload)

    in_seconds = await probe_duration(in_path)
    if in_seconds is not None and in_seconds > VOICE_MAX_DURATION_SEC:
        raise PreprocessError(
            413, "audio_too_long",
            f"That recording is longer than the {VOICE_MAX_DURATION_SEC}s limit.")

    argv = [_FFMPEG_BIN, "-hide_banner", "-nostdin", "-loglevel", "error", "-y",
            "-i", in_path, "-vn", "-sn", "-dn", "-map", "0:a:0",
            # Hard cap on the transcode too, so a container lying about its
            # duration still cannot produce a 40-minute WAV.
            #
            # Capped one second ABOVE the limit rather than AT it, so that
            # overrunning is still detectable afterwards. Cutting at exactly
            # the limit makes an over-long recording indistinguishable from
            # one that happens to be exactly the maximum length, and the only
            # thing we could do with it then is truncate in silence.
            "-t", str(VOICE_MAX_DURATION_SEC + 1)]
    if VOICE_FFMPEG_FILTER:
        argv += ["-af", VOICE_FFMPEG_FILTER]
    argv += ["-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", "-f", "wav", out_path]

    code, stderr = await _run(argv, VOICE_FFMPEG_TIMEOUT_SEC)

    if code != 0 and VOICE_FFMPEG_FILTER:
        # Most likely an invalid filter string (a bad env edit). Retry once
        # without it: format normalization alone is still the valuable part,
        # and a typo in VOICE_FFMPEG_FILTER should not take voice down.
        logger.warning("ffmpeg failed with filter chain, retrying without it: %s",
                       stderr.decode("utf-8", "replace")[:300])
        argv_plain = [a for a in argv]
        idx = argv_plain.index("-af")
        del argv_plain[idx:idx + 2]
        code, stderr = await _run(argv_plain, VOICE_FFMPEG_TIMEOUT_SEC)
        used_filter = None
    else:
        used_filter = VOICE_FFMPEG_FILTER or None

    if code != 0:
        # NEVER echo raw stderr to the client — it leaks temp paths.
        logger.warning("ffmpeg decode failed (rc=%s): %s", code,
                       stderr.decode("utf-8", "replace")[:300])
        raise PreprocessError(422, "audio_decode_failed",
                              "We couldn't read that recording.")

    with open(out_path, "rb") as fh:
        out = fh.read()

    # Output is raw pcm_s16le 16 kHz mono, so the trimmed duration is free from
    # the file size. Trimming the head offsets every segment timestamp, so the
    # caller adds trim_offset_s back to each segment start/end and reports the
    # ORIGINAL duration.
    out_seconds = max(0.0, (len(out) - _WAV_HEADER_BYTES) / _WAV_BYTES_PER_SECOND)
    trim_offset = max(0.0, (in_seconds - out_seconds)) if in_seconds else 0.0

    # Too long, caught on the way OUT.
    #
    # The check above this transcode needs ffprobe to know the input duration,
    # and ffprobe is absent on the production host (and on plenty of others —
    # imageio-ffmpeg ships ffmpeg alone). There it returned None, the limit was
    # never enforced, and a 150s recording came back 200 with two and a half
    # minutes quietly cut down to two. Measuring the OUTPUT needs no ffprobe at
    # all: it is raw PCM at a known rate, so its length is arithmetic.
    if out_seconds > VOICE_MAX_DURATION_SEC:
        raise PreprocessError(
            413, "audio_too_long",
            f"That recording is longer than the {VOICE_MAX_DURATION_SEC}s limit.")

    # Nothing survived the filter chain. `silenceremove` trims the silent head,
    # and for a recording that is ALL silence — muted mic, wrong input device,
    # a press that caught nothing — that is the whole file. Sending the 78-byte
    # husk on would earn a 502 from the upstream and tell the user the voice
    # service is broken, when the honest answer is "I heard nothing, say that
    # again". Checked only when a filter ran; without one, out_seconds is just
    # in_seconds and a short clip is a short clip, not an empty one.
    if used_filter and out_seconds < VOICE_MIN_SPEECH_SEC:
        logger.info("preprocess left no audio | in=%.2fs out=%.3fs filter=%s",
                    in_seconds or 0.0, out_seconds, used_filter)
        raise PreprocessError(422, "audio_no_speech",
                              "I didn't catch that. Please try again.")

    return {"audio": out, "preprocessed": True, "filter_chain": used_filter,
            "duration_s": in_seconds if in_seconds is not None else out_seconds,
            "trim_offset_s": trim_offset}
