"""Route-level tests for /voice/*.

Uses the existing `client` fixture from conftest (ASGITransport + dependency
overrides keyed by function object). Note the overrides only apply because
routers/voice.py depends on the SAME verify_jwt_token / enforce_token_quota
objects conftest imports — wrapping or re-importing either would silently
bypass the override and run the real dependency.
"""

import io
import wave

import pytest

import services.audio_intake as audio_intake
import services.transcribe_client as transcribe_client
import services.voice_log_service as voice_log_service
import services.voice_rate_limit as voice_rate_limit


def make_wav(seconds: float = 0.5, freq: int = 440) -> bytes:
    """A real WAV containing a SINE, not silence.

    Deliberately not silence: a `silenceremove` regression that eats the entire
    file would be invisible against a silent fixture. Built from the stdlib so
    there is no committed binary fixture.
    """
    import math
    rate = 16000
    n = int(rate * seconds)
    buf = io.BytesIO()
    with wave.open(buf, "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(rate)
        frames = bytearray()
        for i in range(n):
            value = int(32767 * 0.3 * math.sin(2 * math.pi * freq * i / rate))
            frames += value.to_bytes(2, "little", signed=True)
        w.writeframes(bytes(frames))
    return buf.getvalue()


@pytest.fixture(autouse=True)
def _isolate(monkeypatch):
    """No network, no DB writes, no Redis in route tests."""
    async def fake_log(**kwargs):
        return None

    async def fake_usage(**kwargs):
        return None

    async def no_rate_limit(*args, **kwargs):
        return None

    monkeypatch.setattr(voice_log_service, "log_attempt", fake_log)
    monkeypatch.setattr(voice_log_service, "record_audio_usage", fake_usage)
    monkeypatch.setattr(voice_rate_limit, "check_rate_limit", no_rate_limit)
    # Redis is not guaranteed in CI; make the lock a no-op unless a test
    # overrides it explicitly.
    monkeypatch.setattr(voice_rate_limit, "_acquire_sync", lambda key: True)
    monkeypatch.setattr(voice_rate_limit, "_release_sync", lambda key: None)


@pytest.fixture
def stub_asr(monkeypatch):
    calls = {"n": 0}

    async def fake_transcribe(audio, *, filename, content_type, **kwargs):
        calls["n"] += 1
        return transcribe_client.Transcription(
            text="apply casual leave tomorrow", language="en",
            segments=[{"text": "apply casual leave tomorrow", "start": 0.0,
                       "end": 1.5, "speaker": None}],
            shape="flat_text")

    monkeypatch.setattr(transcribe_client, "transcribe", fake_transcribe)
    monkeypatch.setattr(transcribe_client, "is_configured", lambda: True)
    return calls


async def test_happy_path_returns_text(client, stub_asr):
    resp = await client.post(
        "/voice/transcribe",
        files={"file": ("clip.wav", make_wav(), "audio/wav")})

    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["success"] is True
    assert body["text"] == "apply casual leave tomorrow"
    assert body["language"] == "en"
    # Never fabricated — WhisperX's avg_logprob is not a probability.
    assert body["confidence"] is None
    assert "asr_ms" in body["timings"]


async def test_oversize_upload_is_rejected_413(client, stub_asr, monkeypatch):
    monkeypatch.setattr(audio_intake, "VOICE_MAX_UPLOAD_BYTES", 1024)
    resp = await client.post(
        "/voice/transcribe",
        files={"file": ("big.wav", make_wav(seconds=2.0), "audio/wav")})

    assert resp.status_code == 413
    assert resp.json()["detail"]["error_code"] == "audio_too_large"
    assert stub_asr["n"] == 0, "must reject before spending GPU time"


async def test_unsupported_format_is_rejected_at_the_gate(client, stub_asr, monkeypatch):
    """Non-audio never reaches the ASR. WHICH refusal depends on whether a
    decoder is available, and both are correct:

      * no ffmpeg -> 415 at the gate, because magic bytes are all we have
      * ffmpeg    -> deferred to the decoder, whose failure becomes a 422

    ffmpeg is pinned absent here so the gate itself is what is under test.
    """
    import services.audio_preprocess as audio_preprocess
    monkeypatch.setattr(audio_preprocess, "_FFMPEG_BIN", None)

    resp = await client.post(
        "/voice/transcribe",
        files={"file": ("evil.exe", b"MZ\x90\x00not audio at all", "audio/wav")})

    assert resp.status_code == 415
    assert resp.json()["detail"]["error_code"] == "unsupported_audio_type"
    assert stub_asr["n"] == 0


async def test_unsupported_format_is_rejected_by_the_decoder(client, stub_asr):
    """The path that actually runs in a real deployment: the sniff is
    inconclusive, ffmpeg is handed the bytes, and its decode failure becomes a
    clean 4xx. Either way the ASR is never called."""
    resp = await client.post(
        "/voice/transcribe",
        files={"file": ("evil.exe", b"MZ\x90\x00not audio at all", "audio/wav")})

    assert 400 <= resp.status_code < 500
    assert resp.json()["detail"]["error_code"] in (
        "unsupported_audio_type", "audio_decode_failed")
    assert stub_asr["n"] == 0


async def test_empty_upload_is_rejected_400(client, stub_asr):
    resp = await client.post(
        "/voice/transcribe", files={"file": ("empty.wav", b"", "audio/wav")})

    assert resp.status_code == 400
    assert resp.json()["detail"]["error_code"] == "empty_audio"


async def test_content_type_is_not_trusted_magic_bytes_win(client, stub_asr):
    """content_type is attacker-controlled, so a declared audio/wav must not be
    enough to get a PDF through. Whether it is stopped by the sniff (415) or by
    the decoder (422) is an implementation detail; being stopped is not."""
    resp = await client.post(
        "/voice/transcribe",
        files={"file": ("lie.wav", b"%PDF-1.7 definitely not audio", "audio/wav")})
    assert 400 <= resp.status_code < 500


async def test_second_concurrent_request_is_rejected_409(client, stub_asr, monkeypatch):
    """One request at a time, enforced server-side — the frontend guard is only
    a client-side promise."""
    monkeypatch.setattr(voice_rate_limit, "_acquire_sync", lambda key: False)

    resp = await client.post(
        "/voice/transcribe",
        files={"file": ("clip.wav", make_wav(), "audio/wav")})

    assert resp.status_code == 409
    assert resp.json()["detail"]["error_code"] == "voice_busy"
    assert stub_asr["n"] == 0


async def test_inflight_lock_is_released_on_error(client, stub_asr, monkeypatch):
    """A lock that only releases on success wedges the user until the TTL
    expires — the classic way this pattern fails in production."""
    released = {"n": 0}
    monkeypatch.setattr(voice_rate_limit, "_release_sync",
                        lambda key: released.__setitem__("n", released["n"] + 1))

    async def boom(*args, **kwargs):
        raise transcribe_client.TranscribeError(503, "asr_unavailable", "down")

    monkeypatch.setattr(transcribe_client, "transcribe", boom)

    resp = await client.post(
        "/voice/transcribe",
        files={"file": ("clip.wav", make_wav(), "audio/wav")})

    assert resp.status_code == 503
    assert released["n"] == 1, "lock must be released on the exception path too"


async def test_upstream_failure_maps_to_actionable_error(client, monkeypatch):
    async def boom(*args, **kwargs):
        raise transcribe_client.TranscribeError(504, "asr_timeout", "too slow")

    monkeypatch.setattr(transcribe_client, "transcribe", boom)
    resp = await client.post(
        "/voice/transcribe",
        files={"file": ("clip.wav", make_wav(), "audio/wav")})

    assert resp.status_code == 504
    assert resp.json()["detail"]["error_code"] == "asr_timeout"


async def test_voice_disabled_returns_503(client, monkeypatch):
    import routers.voice as voice_router_mod
    monkeypatch.setattr(voice_router_mod, "VOICE_ENABLED", False)

    resp = await client.post(
        "/voice/transcribe",
        files={"file": ("clip.wav", make_wav(), "audio/wav")})

    assert resp.status_code == 503
    assert resp.json()["detail"]["error_code"] == "voice_disabled"


async def test_config_exposes_limits(client):
    resp = await client.get("/voice/config")
    assert resp.status_code == 200
    body = resp.json()
    assert body["max_upload_bytes"] > 0
    assert "audio/webm" in body["accepted_mimes"]


async def test_health_is_reachable_and_informational(client):
    resp = await client.get("/voice/health")
    assert resp.status_code == 200
    assert "ffmpeg" in resp.json()


async def test_transcribe_requires_auth(unauth_client):
    resp = await unauth_client.post(
        "/voice/transcribe",
        files={"file": ("clip.wav", make_wav(), "audio/wav")})
    assert resp.status_code in (401, 422)


async def test_temp_workspace_is_always_removed():
    """That single rmtree in `finally` is the whole cleanup guarantee — it must
    run on the exception path, or recorded voice (PII) leaks onto disk."""
    import os
    captured = {}
    with pytest.raises(RuntimeError):
        with audio_intake.workspace() as ws:
            captured["path"] = ws
            assert os.path.isdir(ws)
            raise RuntimeError("boom")
    assert not os.path.exists(captured["path"])


class TestSegmentTimingAndLimits:
    """Trimming leading silence shifts every timestamp, and the duration the
    card reports must stay the ORIGINAL one. Easy to get wrong, invisible when
    wrong — the segments simply point at the erp-api record's wrong moment."""

    async def test_segment_timestamps_are_shifted_back_by_the_trim(
            self, client, monkeypatch, stub_asr):
        import services.audio_preprocess as audio_preprocess

        async def fake_preprocess(payload, workspace, extension):
            # 1.5s of leading silence removed from a 5s recording.
            return {"audio": payload, "preprocessed": True, "filter_chain": "test",
                    "duration_s": 5.0, "trim_offset_s": 1.5}

        monkeypatch.setattr(audio_preprocess, "preprocess", fake_preprocess)

        resp = await client.post(
            "/voice/transcribe",
            files={"file": ("clip.wav", make_wav(), "audio/wav")})

        assert resp.status_code == 200, resp.text
        body = resp.json()
        seg = body["segments"][0]
        # stub_asr returns start=0.0 end=1.5; both move by the trim offset.
        assert seg["start"] == 1.5
        assert seg["end"] == 3.0
        # The ORIGINAL duration, not the trimmed one.
        assert body["duration_ms"] == 5000

    async def test_no_trim_leaves_timestamps_untouched(self, client, monkeypatch, stub_asr):
        import services.audio_preprocess as audio_preprocess

        async def fake_preprocess(payload, workspace, extension):
            return {"audio": payload, "preprocessed": True, "filter_chain": None,
                    "duration_s": 2.0, "trim_offset_s": 0.0}

        monkeypatch.setattr(audio_preprocess, "preprocess", fake_preprocess)

        resp = await client.post(
            "/voice/transcribe",
            files={"file": ("clip.wav", make_wav(), "audio/wav")})

        seg = resp.json()["segments"][0]
        assert seg["start"] == 0.0
        assert seg["end"] == 1.5

    async def test_over_duration_audio_is_rejected_before_the_asr(
            self, client, monkeypatch, stub_asr):
        """Size is a poor proxy for duration — 10MB of 32kbps Opus is ~40
        minutes — so the duration gate has to reject independently."""
        import services.audio_preprocess as audio_preprocess

        async def too_long(payload, workspace, extension):
            raise audio_preprocess.PreprocessError(
                413, "audio_too_long", "That recording is longer than the limit.")

        monkeypatch.setattr(audio_preprocess, "preprocess", too_long)

        resp = await client.post(
            "/voice/transcribe",
            files={"file": ("clip.wav", make_wav(), "audio/wav")})

        assert resp.status_code == 413
        assert resp.json()["detail"]["error_code"] == "audio_too_long"
        assert stub_asr["n"] == 0, "must not spend GPU time on audio it will reject"


class TestConfigEndpoint:
    """/voice/config is what the browser enforces its limits from, so the two
    cannot silently disagree."""

    async def test_config_reports_the_server_limits(self, client):
        body = (await client.get("/voice/config")).json()
        assert body["max_upload_bytes"] > 0
        assert body["max_duration_sec"] > 0
        assert "audio/webm" in body["accepted_mimes"]
        assert "video/webm" in body["accepted_mimes"], \
            "Chrome emits video/webm for an audio-only track — the one everyone forgets"

    async def test_config_reports_disabled_when_the_asr_is_not_configured(
            self, client, monkeypatch):
        import services.transcribe_client as transcribe_client
        monkeypatch.setattr(transcribe_client, "is_configured", lambda: False)
        assert (await client.get("/voice/config")).json()["enabled"] is False


class TestTranscodingIsNotOptional:
    """The ASR gateway accepts ONLY WAV/PCM.

    Verified live: webm/opus, ogg/opus and mp4/AAC were all rejected with an
    upstream error until transcoding was switched on. Those are every container
    a browser can record in, so without ffmpeg the feature is broken in Chrome,
    Edge, Firefox and Safari alike — and the failure arrives as a generic
    upstream error that says nothing about format.

    That makes ffmpeg a hard dependency, not the "nice to have" the tri-state
    flag originally implied.
    """

    def test_ffmpeg_resolves_even_without_one_on_path(self, monkeypatch):
        """imageio-ffmpeg ships a static binary as an ordinary dependency, so
        the working configuration is the default rather than something each
        environment has to remember to install."""
        import shutil
        import services.audio_preprocess as audio_preprocess

        monkeypatch.setattr(shutil, "which", lambda name: None)
        resolved = audio_preprocess._resolve_ffmpeg()

        assert resolved, "no ffmpeg resolved — every browser upload would be rejected"
        assert "ffmpeg" in resolved.lower()

    def test_the_system_binary_wins_when_present(self, monkeypatch):
        import shutil
        import services.audio_preprocess as audio_preprocess

        monkeypatch.setattr(shutil, "which",
                            lambda name: "/usr/bin/ffmpeg" if name == "ffmpeg" else None)
        assert audio_preprocess._resolve_ffmpeg() == "/usr/bin/ffmpeg"

    async def test_a_browser_container_is_accepted_at_the_gate(self, client, stub_asr):
        """webm is what Chrome and Edge produce. It must not be rejected as an
        unsupported type — the transcode step is what makes it usable."""
        webm = b"\x1a\x45\xdf\xa3" + b"\x00" * 512
        resp = await client.post(
            "/voice/transcribe",
            files={"file": ("rec.webm", webm, "audio/webm;codecs=opus")})

        assert resp.status_code != 415, "webm rejected at the gate — voice is dead in Chrome"

    async def test_the_response_reports_whether_it_transcoded(self, client, stub_asr):
        """`preprocessed` is how a "why is the transcript bad" report gets
        correlated with whether ffmpeg actually ran."""
        resp = await client.post(
            "/voice/transcribe",
            files={"file": ("clip.wav", make_wav(), "audio/wav")})

        assert resp.status_code == 200
        assert "preprocessed" in resp.json()


class TestFfmpegPathCanBePinned:
    """VOICE_FFMPEG_PATH exists because PATH resolution proved unreliable in a
    real deployment: the service user's shell resolved /bin/ffmpeg while the
    running service resolved nothing, and every recording came back 502."""

    def test_a_pinned_executable_wins_over_path(self, monkeypatch, tmp_path):
        import shutil
        import services.audio_preprocess as audio_preprocess

        fake = tmp_path / "ffmpeg"
        fake.write_text("#!/bin/sh\n")
        fake.chmod(0o755)

        monkeypatch.setenv("VOICE_FFMPEG_PATH", str(fake))
        monkeypatch.setattr(shutil, "which", lambda name: "/somewhere/else/ffmpeg")

        assert audio_preprocess._resolve_ffmpeg() == str(fake)

    def test_a_bad_pin_falls_back_instead_of_breaking_voice(self, monkeypatch):
        """A wrong path must not take the feature down — it logs loudly and
        keeps looking, so a typo degrades to the previous behaviour."""
        import shutil
        import services.audio_preprocess as audio_preprocess

        monkeypatch.setenv("VOICE_FFMPEG_PATH", "/no/such/ffmpeg")
        monkeypatch.setattr(shutil, "which", lambda name: "/usr/bin/ffmpeg")

        assert audio_preprocess._resolve_ffmpeg() == "/usr/bin/ffmpeg"

    def test_no_pin_keeps_the_existing_behaviour(self, monkeypatch):
        import shutil
        import services.audio_preprocess as audio_preprocess

        monkeypatch.delenv("VOICE_FFMPEG_PATH", raising=False)
        monkeypatch.setattr(shutil, "which", lambda name: "/usr/bin/ffmpeg")

        assert audio_preprocess._resolve_ffmpeg() == "/usr/bin/ffmpeg"
