"""Pure-function and transport tests for services/transcribe_client.py.

No network: the shape table is a pure function, and the header/retry tests use
httpx.MockTransport. This is the highest-value test file in the feature,
because the upstream 200 schema is undocumented and _normalize_transcription is
the only thing standing between a format change and a broken feature.
"""

import httpx
import pytest

import services.transcribe_client as tc


# ── _normalize_transcription: the shape table ────────────────────────────────

@pytest.mark.parametrize("body,expected_text,expected_shape", [
    ({"segments": [{"text": "hello", "start": 0.1, "end": 1.0}], "language": "en"},
     "hello", "whisperx_segments"),
    ({"text": "plain"}, "plain", "flat_text"),
    ({"transcript": "t2"}, "t2", "flat_transcript"),
    ({"transcription": "t3"}, "t3", "flat_transcription"),
    ({"result": {"text": "nested"}}, "nested", "result>flat_text"),
    ({"data": {"segments": [{"text": "ns"}]}}, "ns", "data>whisperx_segments"),
    ({"output": {"transcript": "o"}}, "o", "output>flat_transcript"),
    ("bare string", "bare string", "bare_string"),
    ([{"text": "a"}, {"text": "b"}], "a b", "bare_list"),
])
def test_normalize_known_shapes(body, expected_text, expected_shape):
    result = tc._normalize_transcription(body)
    assert result.text == expected_text
    assert result.shape == expected_shape


@pytest.mark.parametrize("body", [{}, {"foo": 1}, 123, None])
def test_normalize_rejects_unparseable(body):
    """Must RAISE, never return an empty-string success — an empty transcript is
    indistinguishable from 'the user said nothing' and produces a baffling
    empty chat turn."""
    with pytest.raises(tc.TranscribeError) as exc:
        tc._normalize_transcription(body)
    assert exc.value.error_code == "asr_bad_response"


def test_normalize_does_not_recurse_past_depth_3():
    deep = {"result": {"result": {"result": {"result": {"text": "too deep"}}}}}
    with pytest.raises(tc.TranscribeError):
        tc._normalize_transcription(deep)


def test_normalize_coerces_non_numeric_timestamps():
    body = {"segments": [{"text": "x", "start": "not-a-number", "end": None}]}
    result = tc._normalize_transcription(body)
    assert result.segments[0]["start"] is None
    assert result.segments[0]["end"] is None


def test_normalize_reads_alternate_segment_keys():
    body = {"segments": [
        {"sentence": "one", "start_time": 0.0, "end_time": 1.0, "speaker_id": "S1"},
    ]}
    result = tc._normalize_transcription(body)
    assert result.segments[0]["text"] == "one"
    assert result.segments[0]["start"] == 0.0
    assert result.segments[0]["speaker"] == "S1"


def test_normalize_prefers_top_level_text_over_joined_segments():
    body = {"text": "canonical", "segments": [{"text": "a"}, {"text": "b"}]}
    assert tc._normalize_transcription(body).text == "canonical"


# ── transport ────────────────────────────────────────────────────────────────

@pytest.fixture
def configured(monkeypatch):
    monkeypatch.setattr(tc, "VOICE_ASR_API_KEY", "test-key")


def _client_returning(handler):
    return httpx.AsyncClient(transport=httpx.MockTransport(handler))


async def test_caller_jwt_is_never_forwarded_to_race(monkeypatch, configured):
    """THE security test for this module.

    RACE authenticates the SERVICE via x-api-key. Forwarding the caller's JWT
    would leak an HR credential that erp_client uses to *mutate* leave records
    into a third party's logs and APM spans — and it would be useless, because
    RACE has no per-tenant scoping. If this test fails, do not ship.
    """
    seen = {}

    def handler(request: httpx.Request) -> httpx.Response:
        seen["headers"] = request.headers
        return httpx.Response(200, json={"text": "ok"})

    monkeypatch.setattr(tc, "_http", _client_returning(handler))
    await tc.transcribe(b"RIFFxxxxWAVE", filename="a.wav", content_type="audio/wav")

    assert seen["headers"]["x-api-key"] == "test-key"
    assert "authorization" not in {k.lower() for k in seen["headers"].keys()}


async def test_agent_voiceprint_omitted_entirely_by_default(monkeypatch, configured):
    """Not sent as an empty string: an empty string is a PRESENT field and may
    select a different upstream code path (diarization). Speaker ID is out of
    scope, so the field must be absent."""
    seen = {}

    def handler(request: httpx.Request) -> httpx.Response:
        seen["body"] = request.content
        return httpx.Response(200, json={"text": "ok"})

    monkeypatch.setattr(tc, "_http", _client_returning(handler))
    await tc.transcribe(b"x", filename="a.wav", content_type="audio/wav",
                        agent_voiceprint="someone")

    assert b"agent_voiceprint" not in seen["body"]


async def test_read_timeout_is_never_retried(monkeypatch, configured):
    """A ReadTimeout means the request reached the GPU and may well have been
    processed. Retrying doubles GPU cost and queue pressure on a box that is
    already too slow. Exactly one attempt, then 504."""
    attempts = {"n": 0}

    def handler(request: httpx.Request) -> httpx.Response:
        attempts["n"] += 1
        raise httpx.ReadTimeout("too slow", request=request)

    monkeypatch.setattr(tc, "_http", _client_returning(handler))
    with pytest.raises(tc.TranscribeError) as exc:
        await tc.transcribe(b"x", filename="a.wav", content_type="audio/wav")

    assert attempts["n"] == 1
    assert exc.value.status_code == 504
    assert exc.value.error_code == "asr_timeout"


async def test_connect_error_is_retried_once_then_503(monkeypatch, configured):
    attempts = {"n": 0}

    def handler(request: httpx.Request) -> httpx.Response:
        attempts["n"] += 1
        raise httpx.ConnectError("down", request=request)

    monkeypatch.setattr(tc, "_http", _client_returning(handler))
    monkeypatch.setattr(tc, "_backoff", lambda attempt: 0)
    with pytest.raises(tc.TranscribeError) as exc:
        await tc.transcribe(b"x", filename="a.wav", content_type="audio/wav")

    assert attempts["n"] == tc._MAX_ATTEMPTS
    assert exc.value.error_code == "asr_unavailable"


async def test_upstream_401_reports_misconfiguration_not_auth_failure(monkeypatch, configured):
    """A rejected api key is a SERVER misconfiguration. It must not surface to
    the user as an auth error, and the real cause must not be echoed."""
    def handler(request: httpx.Request) -> httpx.Response:
        return httpx.Response(401, text="invalid api key")

    monkeypatch.setattr(tc, "_http", _client_returning(handler))
    with pytest.raises(tc.TranscribeError) as exc:
        await tc.transcribe(b"x", filename="a.wav", content_type="audio/wav")

    assert exc.value.status_code == 500
    assert exc.value.error_code == "asr_not_configured"
    assert "invalid api key" not in exc.value.detail


async def test_empty_transcript_raises_rather_than_succeeding(monkeypatch, configured):
    def handler(request: httpx.Request) -> httpx.Response:
        return httpx.Response(200, json={"text": "   "})

    monkeypatch.setattr(tc, "_http", _client_returning(handler))
    with pytest.raises(tc.TranscribeError) as exc:
        await tc.transcribe(b"x", filename="a.wav", content_type="audio/wav")

    assert exc.value.error_code == "asr_empty"


@pytest.mark.parametrize("body", [
    {"text": "   "},                                  # whitespace only
    {"transcript": "", "segments": []},               # the real gateway shape
    {"success": True, "detected_language": "en",
     "transcript": "", "diarized_text": "", "segments": []},  # live silence body
])
async def test_no_speech_is_a_422_not_a_bad_gateway(monkeypatch, configured, body):
    """Regression: silence used to come back as 502.

    The reported symptom was a bare "502 Bad Gateway" in the browser for a
    recording that simply had no speech in it. The gateway answered 200 and was
    perfectly healthy, so blaming it was wrong — and because a reverse proxy
    with ProxyErrorOverride substitutes its own HTML for 5xx bodies, the
    error_code never survived the hop and the UI could not say "try again".
    """
    def handler(request: httpx.Request) -> httpx.Response:
        return httpx.Response(200, json=body)

    monkeypatch.setattr(tc, "_http", _client_returning(handler))
    with pytest.raises(tc.TranscribeError) as exc:
        await tc.transcribe(b"x", filename="a.wav", content_type="audio/wav")

    assert exc.value.error_code == "asr_empty"
    assert exc.value.status_code == 422, "no speech is the caller's problem, not the upstream's"
    assert 500 > exc.value.status_code, "must never be classed as a server fault"
    # The user-facing half of the ask: prompt for a repeat.
    assert "again" in exc.value.detail.lower()


async def test_silence_still_counts_as_a_successful_warmup(monkeypatch, configured):
    """warmup() keys off error_code, not status. If it ever keyed off 5xx, the
    422 above would make every warmup look like a failed one and spam the log."""
    def handler(request: httpx.Request) -> httpx.Response:
        return httpx.Response(200, json={"transcript": "", "segments": []})

    monkeypatch.setattr(tc, "_http", _client_returning(handler))
    assert await tc.warmup() is True


async def test_missing_api_key_fails_loudly(monkeypatch):
    """The failure mode we are explicitly avoiding: race_rag_service's missing
    key turned RAG into a permanent silent no-op. Voice must raise."""
    monkeypatch.setattr(tc, "VOICE_ASR_API_KEY", None)
    with pytest.raises(tc.TranscribeError) as exc:
        await tc.transcribe(b"x", filename="a.wav", content_type="audio/wav")
    assert exc.value.error_code == "asr_not_configured"


# ── The live gateway's actual contract ───────────────────────────────────────
# Captured from a real POST to https://raceai.studyineurope.xyz/v1/transcribe.
# Until this was run, the response shape was a hypothesis; three things about
# it differed from what the client assumed.
LIVE_RESPONSE = {
    "success": True,
    "detected_language": "en",
    "transcript": "Thank you.",
    "diarized_text": "AGENT: Thank you.",
    "segments": [
        {"start": 0.59, "end": 0.96, "text": "Thank you.",
         "speaker": "SPEAKER_00", "confidence": 1.0, "embedding": []},
    ],
    "speaker_embeddings": {},
    "diarization_confidence": 1.0,
    "processing_time_seconds": 0.18,
}


def test_the_live_response_shape_is_parsed():
    result = tc._normalize_transcription(LIVE_RESPONSE)
    assert result.text == "Thank you."
    assert result.shape == "whisperx_segments"
    assert len(result.segments) == 1
    assert result.segments[0]["speaker"] == "SPEAKER_00"


def test_detected_language_is_read():
    """The gateway sends `detected_language`, not `language`. Reading only the
    latter reported every transcription as language-unknown."""
    assert tc._normalize_transcription(LIVE_RESPONSE).language == "en"
    # Both spellings, and `language` wins when a gateway sends both.
    assert tc._normalize_transcription({"text": "x", "language": "fr"}).language == "fr"
    assert tc._normalize_transcription({"text": "x", "detected_language": "de"}).language == "de"


def test_the_diarized_text_is_never_used_as_the_transcript():
    """`diarized_text` is "AGENT: Thank you." — speaker labelling is out of
    scope, and this would put "AGENT:" straight into the composer."""
    result = tc._normalize_transcription(LIVE_RESPONSE)
    assert not result.text.startswith("AGENT")
    assert "AGENT:" not in result.text


def test_the_top_level_transcript_is_preferred_over_joining_segments():
    """Both are present live. The gateway's own transcript is canonical —
    joining segments re-punctuates and would drift on multi-segment audio."""
    body = {
        "transcript": "the canonical sentence",
        "segments": [{"text": "the canonical"}, {"text": "sentence"}],
        "detected_language": "en",
    }
    assert tc._normalize_transcription(body).text == "the canonical sentence"


def test_the_default_path_is_the_one_that_answers():
    """Bare /transcribe is a 404 on the live gateway; /v1/transcribe answers.
    The wrong default surfaced to users as "voice temporarily unavailable"."""
    assert tc.VOICE_ASR_TRANSCRIBE_PATH.endswith("/v1/transcribe") or \
        tc.VOICE_ASR_TRANSCRIBE_PATH == "/v1/transcribe"


# ── Keep-warm ────────────────────────────────────────────────────────────────
# Measured live: the first transcription after idle took ~35s (model load) and
# warm calls ~1s. Against a 2s target that is not a slow request, it is one the
# user assumes has hung — and it lands on whoever opens the app first.

async def test_warmup_treats_silence_as_success(monkeypatch, configured):
    """The warmup clip is silence, so the gateway correctly answers "no speech".
    That is a SUCCESSFUL warmup: the model loaded, which is the entire point.
    Counting it as a failure would make the warmup look permanently broken."""
    def handler(request: httpx.Request) -> httpx.Response:
        return httpx.Response(200, json={"text": "", "segments": []})

    monkeypatch.setattr(tc, "_http", _client_returning(handler))
    assert await tc.warmup("test") is True


async def test_warmup_never_raises_into_startup(monkeypatch, configured):
    """A keep-warm task must never take the app down; the worst outcome of a
    failed warmup is the cold start we already have."""
    def handler(request: httpx.Request) -> httpx.Response:
        raise httpx.ConnectError("gateway down", request=request)

    monkeypatch.setattr(tc, "_http", _client_returning(handler))
    monkeypatch.setattr(tc, "_backoff", lambda attempt: 0)
    assert await tc.warmup("test") is False   # no exception


async def test_warmup_is_skipped_when_the_asr_is_not_configured(monkeypatch):
    """No key means every call would fail anyway — don't log a scary error
    once a minute about it."""
    monkeypatch.setattr(tc, "VOICE_ASR_API_KEY", None)
    assert await tc.warmup("test") is False


async def test_warmup_can_be_switched_off(monkeypatch, configured):
    monkeypatch.setattr(tc, "VOICE_WARMUP_ENABLED", False)
    assert await tc.warmup("test") is False


def test_the_warmup_clip_is_a_valid_tiny_wav():
    """Sent to a real gateway on a timer, so it must be well-formed and small."""
    import io
    import wave

    with wave.open(io.BytesIO(tc._WARMUP_WAV)) as w:
        assert w.getnchannels() == 1
        assert w.getframerate() == 16000
        assert w.getsampwidth() == 2
    assert len(tc._WARMUP_WAV) < 8000, "keep-warm payload should stay tiny"


# ── English-only guard ───────────────────────────────────────────────────────
# Whisper auto-detects language and invents fluent text in whatever language it
# settles on when the audio is unclear. A real production capture came back as
# "Feels good. <hangul>? Gracias." — three scripts in one line, while
# detected_language still said "en". So the reported language alone cannot
# catch it; the script of the text is the reliable signal.

def _t(text, language="en"):
    return tc.Transcription(text=text, language=language)


def test_the_reported_mixed_script_hallucination_is_rejected():
    mixed = "Feels good. \uc774\uc2ac\uc774 \uc800\ub798\uc11c \ud55c \uac70\uc57c? Gracias."
    with pytest.raises(tc.TranscribeError) as exc:
        tc._reject_if_not_expected_language(_t(mixed, "en"))
    assert exc.value.error_code == "asr_not_understood"
    # 422, not 502: the upstream worked fine, the RESULT was unusable.
    assert exc.value.status_code == 422


def test_a_non_english_language_is_rejected_even_in_latin_script():
    """Spanish is Latin-script, so only the reported language catches it."""
    with pytest.raises(tc.TranscribeError):
        tc._reject_if_not_expected_language(_t("Cu\u00e1l es mi saldo", "es"))


def test_a_non_latin_script_is_rejected_even_when_language_says_english():
    with pytest.raises(tc.TranscribeError):
        tc._reject_if_not_expected_language(_t("\u3053\u3093\u306b\u3061\u306f", "en"))


@pytest.mark.parametrize("text,language", [
    ("apply casual leave for tomorrow", "en"),
    ("show my leave balance", "en-US"),                 # subtag must not trip it
    ("Caf\u00e9 ros\u00e9 na\u00efve r\u00e9sum\u00e9", "en"),   # accents are Latin
    ("LOP comp off 2026-09-23!!!", "en"),               # digits/punctuation ignored
    ("Priya's leave", None),                            # language unknown -> script decides
])
def test_legitimate_english_is_accepted(text, language):
    tc._reject_if_not_expected_language(_t(text, language))   # must not raise


def test_the_guard_can_be_switched_off(monkeypatch):
    """An English-only product today, but this should not need a code change
    the day it is rolled out somewhere else."""
    monkeypatch.setattr(tc, "VOICE_EXPECTED_LANGUAGE", "")
    tc._reject_if_not_expected_language(_t("\u3053\u3093\u306b\u3061\u306f", "ja"))


def test_a_stray_non_latin_character_does_not_reject_a_good_sentence():
    """Zero tolerance would make the feature feel broken over one odd glyph."""
    tc._reject_if_not_expected_language(
        _t("apply leave for tomorrow \u00bd day", "en"))


async def test_the_language_hint_is_sent_upstream(monkeypatch, configured):
    seen = {}

    def handler(request: httpx.Request) -> httpx.Response:
        seen["body"] = request.content
        return httpx.Response(200, json={"text": "apply casual leave", "detected_language": "en"})

    monkeypatch.setattr(tc, "_http", _client_returning(handler))
    await tc.transcribe(b"x", filename="a.wav", content_type="audio/wav")
    assert b"language" in seen["body"]


async def test_a_hallucinated_transcript_never_reaches_the_caller(monkeypatch, configured):
    """End of the chain: the upstream answers 200 with unusable text, and
    transcribe() still refuses rather than handing it to the composer."""
    def handler(request: httpx.Request) -> httpx.Response:
        return httpx.Response(200, json={
            "transcript": "\uc774\uc2ac\uc774 \uc800\ub798\uc11c \ud55c \uac70\uc57c",
            "detected_language": "ko"})

    monkeypatch.setattr(tc, "_http", _client_returning(handler))
    with pytest.raises(tc.TranscribeError) as exc:
        await tc.transcribe(b"x", filename="a.wav", content_type="audio/wav")
    assert exc.value.error_code == "asr_not_understood"
