"""POST /v1/audio/transcriptions — OpenAI-compatible sync endpoint."""
import io


def _wav_bytes(seconds=1.0, rate=16000):
    """Minimal valid 16-bit PCM mono WAV so PyAV can probe/decode it."""
    import struct
    import wave
    buf = io.BytesIO()
    with wave.open(buf, "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(rate)
        w.writeframes(b"\x00\x00" * int(seconds * rate))
    return buf.getvalue()


def test_requires_auth(client):
    r = client.post("/v1/audio/transcriptions",
                    files={"file": ("a.wav", _wav_bytes(), "audio/wav")},
                    data={"model": "whisper-1"})
    assert r.status_code == 401


def test_json_transcription(client, auth_headers):
    r = client.post("/v1/audio/transcriptions",
                    headers=auth_headers,
                    files={"file": ("a.wav", _wav_bytes(), "audio/wav")},
                    data={"model": "whisper-1", "response_format": "json"})
    assert r.status_code == 200
    assert r.json()["text"] == "hello world"


def test_verbose_json_has_segments(client, auth_headers):
    r = client.post("/v1/audio/transcriptions",
                    headers=auth_headers,
                    files={"file": ("a.wav", _wav_bytes(), "audio/wav")},
                    data={"response_format": "verbose_json"})
    assert r.status_code == 200
    body = r.json()
    assert body["text"] == "hello world"
    assert body["segments"]


def test_bad_response_format_400(client, auth_headers):
    r = client.post("/v1/audio/transcriptions",
                    headers=auth_headers,
                    files={"file": ("a.wav", _wav_bytes(), "audio/wav")},
                    data={"response_format": "nope"})
    assert r.status_code == 400


def test_empty_upload_400(client, auth_headers):
    r = client.post("/v1/audio/transcriptions",
                    headers=auth_headers,
                    files={"file": ("a.wav", b"", "audio/wav")})
    assert r.status_code == 400


def test_language_passthrough(client, auth_headers, fake_engine):
    client.post("/v1/audio/transcriptions",
                headers=auth_headers,
                files={"file": ("a.wav", _wav_bytes(), "audio/wav")},
                data={"language": "de"})
    call = fake_engine.service.file_calls[-1]
    assert call["language"] == "de"
    assert call["multilingual"] is False  # explicit lang disables auto-detect


def test_auto_detect_when_no_language(client, auth_headers, fake_engine):
    client.post("/v1/audio/transcriptions",
                headers=auth_headers,
                files={"file": ("a.wav", _wav_bytes(), "audio/wav")},
                data={"response_format": "verbose_json"})
    call = fake_engine.service.file_calls[-1]
    assert call["language"] is None
    assert call["multilingual"] is True


def test_not_ready_returns_503(client, auth_headers, fake_engine):
    fake_engine.service.is_ready = False
    r = client.post("/v1/audio/transcriptions",
                    headers=auth_headers,
                    files={"file": ("a.wav", _wav_bytes(), "audio/wav")})
    assert r.status_code == 503
    assert r.headers.get("Retry-After") == "5"


def test_model_not_downloaded_400(client, auth_headers):
    r = client.post("/v1/audio/transcriptions",
                    headers=auth_headers,
                    files={"file": ("a.wav", _wav_bytes(), "audio/wav")},
                    data={"model": "large-v3-turbo"})  # not in fake _downloaded
    assert r.status_code == 400


def test_known_downloaded_model_switches(client, auth_headers, fake_engine):
    fake_engine._downloaded.add("medium")
    client.post("/v1/audio/transcriptions",
                headers=auth_headers,
                files={"file": ("a.wav", _wav_bytes(), "audio/wav")},
                data={"model": "medium"})
    assert "medium" in fake_engine.switch_calls
