"""A recording with no speech in it must not be blamed on the upstream.

Reported as a bare "502 Bad Gateway" in the browser. The chain of events:

  1. the person's recording contained no audible speech;
  2. `silenceremove` trimmed the silent head, which WAS the whole file, leaving
     a 78-byte WAV with zero audio frames;
  3. we posted that husk to the ASR gateway, which answered
     502 "WhisperX returned a non-JSON response";
  4. we relayed it as `asr_upstream_error` (502) — blaming a service that was
     working perfectly;
  5. Apache's ProxyErrorOverride replaced our JSON body with its own HTML, so
     even the error_code never reached the browser.

These tests run REAL ffmpeg, because the bug lived entirely in what the filter
chain does to real bytes — a mocked preprocess step would have reproduced
nothing.
"""

import io
import math
import wave

import pytest

import services.audio_intake as audio_intake
import services.audio_preprocess as ap

pytestmark = pytest.mark.asyncio

requires_ffmpeg = pytest.mark.skipif(
    not ap.ffmpeg_available(), reason="ffmpeg not available on this machine")


def _wav(path, seconds=3.0, rate=16000, amplitude=0.0):
    """amplitude=0.0 gives digital silence; >0 gives a formant-ish tone."""
    with wave.open(str(path), "wb") as w:
        w.setnchannels(1); w.setsampwidth(2); w.setframerate(rate)
        frames = bytearray()
        for i in range(int(rate * seconds)):
            if amplitude:
                t = i / rate
                f0 = 150 + 40 * math.sin(2 * math.pi * 1.3 * t)
                v = (math.sin(2 * math.pi * f0 * t)
                     + 0.5 * math.sin(2 * math.pi * f0 * 2.4 * t)
                     + 0.3 * math.sin(2 * math.pi * f0 * 3.9 * t))
                sample = int(32767 * amplitude * max(-1.0, min(1.0, v / 1.8)))
            else:
                sample = 0
            frames += sample.to_bytes(2, "little", signed=True)
        w.writeframes(bytes(frames))
    return open(path, "rb").read()


@requires_ffmpeg
async def test_silent_recording_is_rejected_before_it_reaches_the_asr(tmp_path):
    payload = _wav(tmp_path / "silence.wav", amplitude=0.0)
    with audio_intake.workspace() as ws:
        with pytest.raises(ap.PreprocessError) as exc:
            await ap.preprocess(payload, ws, ".wav")

    assert exc.value.error_code == "audio_no_speech"
    assert exc.value.status_code == 422, "our audio, our problem — not a bad gateway"
    assert "again" in exc.value.detail.lower(), "the user must be asked to repeat"


@requires_ffmpeg
async def test_the_husk_really_is_empty(tmp_path):
    """Pins the mechanism, so a future filter-chain edit that stops producing
    an empty file makes it obvious the guard above is no longer load-bearing."""
    payload = _wav(tmp_path / "silence.wav", amplitude=0.0)
    with audio_intake.workspace() as ws:
        monkey = ap.VOICE_MIN_SPEECH_SEC
        ap.VOICE_MIN_SPEECH_SEC = 0.0          # disable the guard, observe the output
        try:
            out = await ap.preprocess(payload, ws, ".wav")
        finally:
            ap.VOICE_MIN_SPEECH_SEC = monkey

    # Read it as a WAV rather than doing byte arithmetic: ffmpeg emits a
    # header longer than the nominal 44 bytes (it appends a LIST/INFO chunk),
    # so "total size minus 44" reports ~34 bytes of audio for a file that in
    # fact contains zero samples.
    with wave.open(io.BytesIO(out["audio"])) as w:
        assert w.getnframes() == 0, "the filter chain should leave nothing at all"


@requires_ffmpeg
async def test_real_audio_still_passes_through_untouched(tmp_path):
    """The guard must not become a second way to lose a good recording."""
    payload = _wav(tmp_path / "speech.wav", seconds=3.0, amplitude=0.30)
    with audio_intake.workspace() as ws:
        out = await ap.preprocess(payload, ws, ".wav")

    assert out["preprocessed"] is True
    assert out["duration_s"] == pytest.approx(3.0, abs=0.2)
    assert len(out["audio"]) > ap._WAV_HEADER_BYTES


@requires_ffmpeg
async def test_a_short_answer_is_not_mistaken_for_silence(tmp_path):
    """"Yes" is about 0.4s. The threshold sits below the shortest real word on
    purpose; if someone raises it, this fails rather than silently swallowing
    terse answers."""
    payload = _wav(tmp_path / "short.wav", seconds=0.5, amplitude=0.30)
    with audio_intake.workspace() as ws:
        out = await ap.preprocess(payload, ws, ".wav")

    assert out["preprocessed"] is True
    assert ap.VOICE_MIN_SPEECH_SEC < 0.4, "threshold has grown past a spoken 'yes'"


@requires_ffmpeg
async def test_the_guard_only_applies_when_a_filter_actually_ran(tmp_path, monkeypatch):
    """With no filter chain there is no trimming, so a short clip is short, not
    empty — rejecting it here would be rejecting the user's real audio."""
    monkeypatch.setattr(ap, "VOICE_FFMPEG_FILTER", "")
    payload = _wav(tmp_path / "silence.wav", amplitude=0.0)
    with audio_intake.workspace() as ws:
        out = await ap.preprocess(payload, ws, ".wav")

    assert out["filter_chain"] is None
    assert out["duration_s"] == pytest.approx(3.0, abs=0.2)


# ── The duration limit without ffprobe ────────────────────────────────────────
# Found by an end-to-end run against production: a 150s upload returned 200.
# The pre-transcode gate needs ffprobe to know the input length, and the
# production host has ffmpeg but NO ffprobe (imageio-ffmpeg ships ffmpeg
# alone), so probe_duration returned None, the limit was never applied, and
# ffmpeg's -t cap quietly cut the recording down to the maximum instead.


@requires_ffmpeg
async def test_over_long_audio_is_rejected_even_with_no_ffprobe(tmp_path, monkeypatch):
    monkeypatch.setattr(ap, "_FFPROBE_BIN", None)        # the production host
    monkeypatch.setattr(ap, "VOICE_MAX_DURATION_SEC", 2)

    payload = _wav(tmp_path / "long.wav", seconds=5.0, amplitude=0.30)
    with audio_intake.workspace() as ws:
        with pytest.raises(ap.PreprocessError) as exc:
            await ap.preprocess(payload, ws, ".wav")

    assert exc.value.error_code == "audio_too_long"
    assert exc.value.status_code == 413


@requires_ffmpeg
async def test_audio_inside_the_limit_is_untouched(tmp_path, monkeypatch):
    """The limit must reject, not shave. A clip under the cap keeps its full
    length — a check that truncated instead would pass the test above while
    still losing the end of everyone's sentence."""
    monkeypatch.setattr(ap, "_FFPROBE_BIN", None)
    monkeypatch.setattr(ap, "VOICE_MAX_DURATION_SEC", 10)

    payload = _wav(tmp_path / "ok.wav", seconds=3.0, amplitude=0.30)
    with audio_intake.workspace() as ws:
        out = await ap.preprocess(payload, ws, ".wav")

    with io.BytesIO(out["audio"]) as buf, wave.open(buf) as w:
        assert w.getnframes() / w.getframerate() == pytest.approx(3.0, abs=0.2)


@requires_ffmpeg
async def test_the_cheaper_ffprobe_gate_still_fires_when_it_is_available(tmp_path, monkeypatch):
    """Where ffprobe exists it rejects BEFORE the transcode, which is the whole
    point of keeping it — no CPU spent on audio that is going to be refused."""
    if not ap._FFPROBE_BIN:
        pytest.skip("no ffprobe on this machine")
    monkeypatch.setattr(ap, "VOICE_MAX_DURATION_SEC", 2)

    transcoded = []
    original_run = ap._run

    async def spy(argv, timeout):
        transcoded.append(argv)
        return await original_run(argv, timeout)

    monkeypatch.setattr(ap, "_run", spy)

    payload = _wav(tmp_path / "long.wav", seconds=5.0, amplitude=0.30)
    with audio_intake.workspace() as ws:
        with pytest.raises(ap.PreprocessError) as exc:
            await ap.preprocess(payload, ws, ".wav")

    assert exc.value.error_code == "audio_too_long"
    assert not transcoded, "rejected before spending CPU on a transcode"
