"""Phase 1 limits: 60 seconds, 10 MB, approved formats only.

One file for the three numbers so an approval change has a single obvious
place to land, and so "is the limit enforced?" is answerable without reading
three modules.

The gaps these were written against, both found by end-to-end runs rather than
by reading the code:

  * the duration limit was 120s server-side while the browser defaulted to 60 —
    and because the browser reads the limit back from /voice/config, the server
    RAISED it to 120. The stricter-looking client number was decorative;
  * the format list was advisory. Anything the sniffer could not identify was
    handed to ffmpeg to decide, and ffmpeg happily decodes AMR, WMA, AIFF and
    video files.
"""

import math
import wave

import pytest

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

# Applied per-test rather than module-wide: half of these are sync, and a
# blanket asyncio mark warns on every one of them.
asyncio_test = pytest.mark.asyncio

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


def _wav_bytes(path, seconds=1.0, amplitude=0.30):
    with wave.open(str(path), "wb") as w:
        w.setnchannels(1); w.setsampwidth(2); w.setframerate(16000)
        frames = bytearray()
        for i in range(int(16000 * seconds)):
            t = i / 16000
            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))
            frames += int(32767 * amplitude * max(-1.0, min(1.0, v / 1.8))).to_bytes(
                2, "little", signed=True)
        w.writeframes(bytes(frames))
    return open(path, "rb").read()


class _FakeUpload:
    """Minimal UploadFile stand-in: read_capped only calls .read(n)."""

    def __init__(self, data: bytes):
        self._data = data
        self._pos = 0

    async def read(self, n: int = -1) -> bytes:
        chunk = self._data[self._pos:self._pos + n] if n and n > 0 else self._data[self._pos:]
        self._pos += len(chunk)
        return chunk


# ── The approved numbers ──────────────────────────────────────────────────────

def test_the_approved_duration_is_sixty_seconds():
    assert ap.VOICE_MAX_DURATION_SEC == 60


def test_the_approved_size_is_ten_megabytes():
    assert ai.VOICE_MAX_UPLOAD_BYTES == 10 * 1024 * 1024


@asyncio_test
async def test_the_browser_is_told_the_same_numbers_the_server_enforces(client):
    """The browser takes its limits from /voice/config and stops recording at
    max_duration_sec. If this endpoint advertised a number the server did not
    enforce, the client would cheerfully record something guaranteed to be
    refused — or, as happened, the server would silently RAISE the client's
    stricter limit."""
    r = await client.get("/voice/config")

    assert r.status_code == 200
    body = r.json()
    assert body["max_duration_sec"] == ap.VOICE_MAX_DURATION_SEC == 60
    assert body["max_upload_bytes"] == ai.VOICE_MAX_UPLOAD_BYTES == 10 * 1024 * 1024


# ── Size ──────────────────────────────────────────────────────────────────────

@asyncio_test
async def test_an_oversize_upload_is_refused():
    upload = _FakeUpload(b"\x00" * (ai.VOICE_MAX_UPLOAD_BYTES + 1))

    with pytest.raises(ai.AudioRejected) as exc:
        await ai.read_capped(upload)

    assert exc.value.status_code == 413
    assert exc.value.error_code == "audio_too_large"
    assert "10 MB" in exc.value.detail


@asyncio_test
async def test_the_cap_is_applied_while_reading_not_after():
    """The bytes must never all be held at once. An unbounded read on a large
    POST is a one-line OOM: there is no ASGI body-size limit in front of this
    service."""
    oversize = ai.VOICE_MAX_UPLOAD_BYTES + (5 * 1024 * 1024)
    upload = _FakeUpload(b"\x00" * oversize)

    with pytest.raises(ai.AudioRejected):
        await ai.read_capped(upload)

    # Stopped within one chunk of the cap rather than consuming all 15 MB.
    assert upload._pos <= ai.VOICE_MAX_UPLOAD_BYTES + (64 * 1024)


@asyncio_test
async def test_an_upload_exactly_at_the_cap_is_accepted():
    """The limit is inclusive. An off-by-one here rejects a legitimate
    recording that sits precisely on the boundary."""
    data = await ai.read_capped(_FakeUpload(b"\x00" * ai.VOICE_MAX_UPLOAD_BYTES))
    assert len(data) == ai.VOICE_MAX_UPLOAD_BYTES


# ── Duration ──────────────────────────────────────────────────────────────────

@requires_ffmpeg
@asyncio_test
async def test_a_recording_over_sixty_seconds_is_refused(tmp_path):
    payload = _wav_bytes(tmp_path / "long.wav", seconds=61.5)

    with ai.workspace() as ws:
        with pytest.raises(ap.PreprocessError) as exc:
            await ap.preprocess(payload, ws, ".wav")

    assert exc.value.status_code == 413
    assert exc.value.error_code == "audio_too_long"
    assert "60" in exc.value.detail


@requires_ffmpeg
@asyncio_test
async def test_a_recording_inside_the_limit_survives_whole(tmp_path):
    """Refuse, never shave. A limit that truncated would pass the test above
    while quietly losing the end of everyone's sentence."""
    payload = _wav_bytes(tmp_path / "ok.wav", seconds=5.0)

    with ai.workspace() as ws:
        out = await ap.preprocess(payload, ws, ".wav")

    assert out["duration_s"] == pytest.approx(5.0, abs=0.3)


@requires_ffmpeg
@asyncio_test
async def test_the_duration_limit_holds_without_ffprobe(tmp_path, monkeypatch):
    """The production host has ffmpeg but no ffprobe, so the pre-transcode gate
    cannot measure the input there. Measuring the OUTPUT needs no ffprobe: it
    is raw PCM at a known rate, so its length is arithmetic."""
    monkeypatch.setattr(ap, "_FFPROBE_BIN", None)
    payload = _wav_bytes(tmp_path / "long.wav", seconds=61.5)

    with ai.workspace() as ws:
        with pytest.raises(ap.PreprocessError) as exc:
            await ap.preprocess(payload, ws, ".wav")

    assert exc.value.error_code == "audio_too_long"


# ── Format ────────────────────────────────────────────────────────────────────

@pytest.mark.parametrize("label,head", [
    ("wav",  b"RIFF\x00\x00\x00\x00WAVEfmt "),
    ("ogg",  b"OggS\x00\x02\x00\x00\x00\x00\x00\x00"),
    ("webm", b"\x1a\x45\xdf\xa3\x01\x00\x00\x00\x00\x00\x00\x1f"),
    ("mp4",  b"\x00\x00\x00\x20ftypM4A \x00\x00\x00\x00"),
    ("flac", b"fLaC\x00\x00\x00\x22\x12\x00\x12\x00"),
    ("mp3",  b"ID3\x04\x00\x00\x00\x00\x00\x00\x00\x00"),
])
def test_every_approved_container_is_accepted(label, head):
    assert ai.validate("application/octet-stream", head, ffmpeg_available=True) == label


@pytest.mark.parametrize("label,head", [
    # Formats ffmpeg decodes happily, which is exactly why they used to pass.
    ("AMR",        b"#!AMR\n\x00\x00\x00\x00\x00\x00\x00"),
    ("AIFF",       b"FORM\x00\x00\x00\x00AIFFCOMM"),
    ("WMA/ASF",    b"\x30\x26\xb2\x75\x8e\x66\xcf\x11\xa6\xd9\x00\xaa"),
    ("Matroska-ish gibberish", b"NOTAUDIOATALL\x00\x00\x00"),
    ("a Windows exe", b"MZ\x90\x00\x03\x00\x00\x00\x04\x00\x00\x00"),
    ("a zip/office file", b"PK\x03\x04\x14\x00\x00\x00\x08\x00\x00\x00"),
])
def test_unapproved_formats_are_refused_even_though_ffmpeg_could_read_them(label, head):
    with pytest.raises(ai.AudioRejected) as exc:
        ai.validate("audio/wav", head, ffmpeg_available=True)

    assert exc.value.status_code == 415, label
    assert exc.value.error_code == "unsupported_audio_type"


def test_a_declared_content_type_cannot_launder_a_payload():
    """content_type is attacker-controlled. Accepting on it would defeat the
    sniff entirely — any payload declaring audio/wav would reach the ASR."""
    for declared in ("audio/wav", "audio/webm", "audio/mp4", ""):
        with pytest.raises(ai.AudioRejected):
            ai.validate(declared, b"MZ\x90\x00 definitely not audio", ffmpeg_available=True)


def test_a_truncated_header_is_refused_rather_than_guessed():
    with pytest.raises(ai.AudioRejected):
        ai.validate("audio/wav", b"RIF", ffmpeg_available=True)


def test_the_advertised_mimes_and_the_enforced_containers_agree():
    """/voice/config tells the browser which MIME types are accepted, while the
    gate decides on container magic. If those two sets drift, the API advertises
    something it then refuses."""
    advertised = set()
    for mime in ai.ACCEPTED_MIMES:
        subtype = mime.split("/")[1]
        advertised.add({"x-m4a": "mp4", "m4a": "mp4", "mpeg": "mp3",
                        "x-wav": "wav", "wave": "wav", "x-flac": "flac",
                        "ogg": "ogg"}.get(subtype, subtype))

    assert advertised <= ai.ACCEPTED_CONTAINERS, (
        f"advertised but not enforceable: {advertised - ai.ACCEPTED_CONTAINERS}")
