"""RACE AI gateway ASR client (HA-499).

SECURITY — the caller's JWT must NEVER reach RACE. Read this before "fixing"
anything here:
  1. It would leak an HR credential that erp_client uses to *mutate* leave
     records into a third party's logs and APM spans.
  2. It is useless — RACE authenticates the *service* via `x-api-key`, not the
     end user.
  3. It muddles the audit story.
The contrast with `erp_client` is deliberate, not an inconsistency: /ping and
leave_action_node forward the caller's token *because erp-api enforces
per-employee scope with it*. Different upstream, different rule. RACE has no
per-tenant scoping at all.

Audio bytes are never written to disk by this module and never logged.
"""

import asyncio
import time
import logging
import os
import random
from dataclasses import dataclass, field
from typing import Any, Optional

import httpx

logger = logging.getLogger(__name__)

# Falls back to the shared RACE base URL so one gateway serving both chat and
# ASR is configured once. Voice must not couple to ACTIVE_LLM_PROVIDER.
_RACE_BASE = os.getenv("RACE_API_BASE_URL", "http://127.0.0.1:8080")
VOICE_ASR_BASE_URL = os.getenv("VOICE_ASR_BASE_URL") or _RACE_BASE
VOICE_ASR_API_KEY = os.getenv("VOICE_ASR_API_KEY") or os.getenv("RACE_API_KEY")
# Confirmed against the live gateway: /v1/transcribe answers, bare /transcribe
# is a 404. (The curl this was first specified from showed the root-level path;
# it is wrong, and the resulting 404 surfaced to users as "voice temporarily
# unavailable" with nothing in the UI to suggest a misconfigured path.)
VOICE_ASR_TRANSCRIBE_PATH = os.getenv("VOICE_ASR_TRANSCRIBE_PATH", "/v1/transcribe")

TRANSCRIBE_URL = f"{VOICE_ASR_BASE_URL.rstrip('/')}{VOICE_ASR_TRANSCRIBE_PATH}"

# `agent_voiceprint` is almost certainly a reference speaker ID/embedding fed to
# the diarization stage — the contact-centre pattern of tagging AGENT/CUSTOMER
# instead of SPEAKER_00/01. Speaker identification is explicitly out of scope,
# so the field is OMITTED ENTIRELY rather than sent empty: an empty string is a
# *present* field and may select a different upstream code path.
VOICE_ALLOW_AGENT_VOICEPRINT = os.getenv("VOICE_ALLOW_AGENT_VOICEPRINT", "false").lower() == "true"

# A dedicated client, NOT ai_service._http. That one caps at 20 connections
# shared by every chat completion, intent classification and moderation call,
# with write=10.0. Transcription pushes megabytes and holds a connection for
# tens of seconds, so sharing the pool would turn a burst of voice traffic into
# a *chat outage*. write=60 for the upload; read=180 because the upstream is
# synchronous, may queue, and a cold model load is 30s+.
_http = httpx.AsyncClient(
    timeout=httpx.Timeout(connect=10.0, read=180.0, write=60.0, pool=5.0),
    limits=httpx.Limits(max_connections=8, max_keepalive_connections=4),
)

_RETRY_STATUSES = {502, 503, 504}
_MAX_ATTEMPTS = 2


class TranscribeError(Exception):
    """A failure the caller must surface to the user.

    Unlike race_rag_service.query_collection (which fails open to [] because a
    broken retrieval should not break an otherwise-good HR answer), a failed
    transcription MUST be visible: the user spoke and is waiting.
    """

    def __init__(self, status_code: int, error_code: str, detail: str = "",
                 upstream_status: Optional[int] = None):
        self.status_code = status_code
        self.error_code = error_code
        self.detail = detail
        self.upstream_status = upstream_status
        super().__init__(f"{error_code}: {detail}" if detail else error_code)


@dataclass
class Transcription:
    text: str
    language: Optional[str] = None
    segments: list = field(default_factory=list)
    # Which branch of _normalize_transcription matched. Logged on every request:
    # the day RACE changes their response format, this one field says so
    # immediately instead of leaving you guessing.
    shape: str = "unknown"
    raw_keys: list = field(default_factory=list)


def is_configured() -> bool:
    return bool(VOICE_ASR_API_KEY)


def _require_config() -> None:
    if not VOICE_ASR_API_KEY:
        # Logged loudly at ERROR because the alternative — failing quietly — is
        # exactly how race_rag_service's missing key turned RAG into a
        # permanent silent no-op that nobody noticed.
        logger.error(
            "VOICE_ASR_API_KEY/RACE_API_KEY is not configured — voice transcription "
            "cannot work in this environment. Set it in .env (see .env.example)."
        )
        raise TranscribeError(500, "asr_not_configured",
                              "Voice transcription is not configured on this server.")


def _as_float(value: Any) -> Optional[float]:
    try:
        return float(value)
    except (TypeError, ValueError):
        return None


def _segment(raw: Any) -> Optional[dict]:
    if not isinstance(raw, dict):
        return None
    text = None
    for key in ("text", "transcript", "sentence", "value"):
        candidate = raw.get(key)
        if isinstance(candidate, str):
            text = candidate
            break
    if text is None:
        return None

    start = end = None
    for a, b in (("start", "end"), ("start_time", "end_time"), ("from", "to")):
        if a in raw or b in raw:
            start, end = _as_float(raw.get(a)), _as_float(raw.get(b))
            break

    speaker = None
    for key in ("speaker", "speaker_id", "label"):
        if isinstance(raw.get(key), str):
            speaker = raw[key]
            break

    return {"text": text, "start": start, "end": end, "speaker": speaker}


def _first_string(body: dict, *keys: str) -> Optional[str]:
    """The first of `keys` holding a non-blank string."""
    for key in keys:
        value = body.get(key)
        if isinstance(value, str) and value.strip():
            return value
    return None


def _language_of(body: dict) -> Optional[str]:
    """The detected language, whatever the gateway calls it.

    The live gateway sends `detected_language`, not `language` — reading only
    the latter reported every transcription as language-unknown, which is the
    field the client would use to pick a voice if TTS is added.
    """
    return _first_string(body, "language", "detected_language", "lang")


def _normalize_transcription(body: Any, _depth: int = 0) -> Transcription:
    """Map whatever RACE returns onto one stable shape.

    The upstream 200 schema is undocumented (its OpenAPI types the response as
    a bare `{}`), so this is where the real risk lives. Pure function over an
    already-parsed body: no HTTP, no I/O, unit-tested against a shape table.

    Both transports (one-shot HTTP and streaming) feed this, so the client sees
    one contract regardless of how the audio got there.
    """
    raw_keys = sorted(body.keys()) if isinstance(body, dict) else []

    # A bare string response (some gateways return text/plain).
    if isinstance(body, str):
        return Transcription(text=body.strip(), shape="bare_string")

    # A bare list of segments.
    if isinstance(body, list):
        segs = [s for s in (_segment(x) for x in body) if s]
        return Transcription(
            text=" ".join(s["text"] for s in segs).strip(),
            segments=segs,
            shape="bare_list",
        )

    if not isinstance(body, dict):
        raise TranscribeError(502, "asr_bad_response",
                              f"Unexpected response type {type(body).__name__}")

    # WhisperX canonical: {segments, language, word_segments}
    #
    # The live gateway answers with BOTH `segments` and a top-level
    # `transcript`, so this branch is the one that actually runs. Confirmed
    # live shape:
    #   {success, detected_language, transcript, diarized_text, segments:[
    #     {start, end, text, speaker, confidence, embedding}],
    #    speaker_embeddings, diarization_confidence, processing_time_seconds}
    #
    # `diarized_text` ("AGENT: Thank you.") is deliberately NOT used: speaker
    # labelling is out of scope, and prefixing a dictated sentence with a
    # speaker tag would put "AGENT:" straight into the composer.
    if isinstance(body.get("segments"), list):
        segs = [s for s in (_segment(x) for x in body["segments"]) if s]
        text = _first_string(body, "text", "transcript", "transcription")
        if not text:
            text = " ".join(s["text"] for s in segs)
        return Transcription(
            text=text.strip(),
            language=_language_of(body),
            segments=segs,
            shape="whisperx_segments",
            raw_keys=raw_keys,
        )

    # Flat string payloads.
    for key, shape in (("text", "flat_text"),
                       ("transcript", "flat_transcript"),
                       ("transcription", "flat_transcription")):
        candidate = body.get(key)
        if isinstance(candidate, str):
            return Transcription(
                text=candidate.strip(),
                language=_language_of(body),
                shape=shape,
                raw_keys=raw_keys,
            )

    # Wrapper envelopes: {result|data|output: {...}} — unwrap ONE level and
    # recurse, guarded so a pathological/cyclic payload cannot spin.
    if _depth < 3:
        for key in ("result", "data", "output"):
            inner = body.get(key)
            if isinstance(inner, (dict, list, str)):
                nested = _normalize_transcription(inner, _depth + 1)
                if nested.text or nested.segments:
                    nested.shape = f"{key}>{nested.shape}"
                    nested.raw_keys = raw_keys
                    return nested

    raise TranscribeError(502, "asr_bad_response",
                          "Could not find a transcript in the ASR response.")


# ── English-only guard ────────────────────────────────────────────────────────
# Whisper auto-detects language and, on unclear or non-speech audio, invents
# fluent-looking text in whatever language it settles on. A real capture from
# production came back as:
#
#     "Feels good. 이슬이 저래서 한 거야? Gracias."
#
# Three scripts in one line. Note that `detected_language` for that is very
# likely "en" — the model reports ONE language for the clip while the text
# wanders — so checking the reported language alone does not catch it. The
# script of the text itself is the reliable signal.
#
# This is an HR assistant used in English; anything else is a misrecognition,
# and the honest response is to ask the person to say it again rather than to
# put invented words in their message box.

VOICE_EXPECTED_LANGUAGE = os.getenv("VOICE_EXPECTED_LANGUAGE", "en").strip().lower()

# Proportion of letters allowed to fall outside the Latin range before the
# transcript is treated as a misrecognition. Not zero: a legitimate answer can
# carry a stray accented or symbol character, and rejecting on a single one
# would make the feature feel broken.
_MAX_NON_LATIN_RATIO = 0.15


def _non_latin_ratio(text: str) -> float:
    """Share of ALPHABETIC characters outside Basic/Latin-1 letters.

    Digits, spaces and punctuation are ignored, so "2026-09-23" and "!!!" do
    not skew it. Hangul, CJK, Cyrillic, Arabic, Devanagari all count as
    non-Latin and push the ratio up.
    """
    letters = [c for c in text if c.isalpha()]
    if not letters:
        return 0.0
    non_latin = sum(1 for c in letters if ord(c) > 0x024F)
    return non_latin / len(letters)


def _reject_if_not_expected_language(result: "Transcription", request_id=None) -> None:
    """Raise `asr_not_understood` when the transcript is not the expected
    language, so the caller can ask the person to repeat themselves.

    Deliberately NOT `asr_empty`: "I heard nothing" and "I heard something and
    it was not English" are different states, and only the second is worth
    suggesting a retry in English for.
    """
    if not VOICE_EXPECTED_LANGUAGE:
        return   # explicitly disabled

    detected = (result.language or "").strip().lower()
    ratio = _non_latin_ratio(result.text)

    # Language codes arrive as "en" or "en-US"; compare on the primary subtag.
    language_mismatch = bool(detected) and detected.split("-")[0] != VOICE_EXPECTED_LANGUAGE
    script_mismatch = ratio > _MAX_NON_LATIN_RATIO

    if language_mismatch or script_mismatch:
        # The transcript itself is NOT logged — it is personal data, and a
        # misrecognition is no less so. Shape only.
        logger.info(
            "VOICE rejected non-%s transcript | req=%s | detected=%s | "
            "non_latin=%.0f%% | chars=%d",
            VOICE_EXPECTED_LANGUAGE, request_id, detected or "-", ratio * 100,
            len(result.text),
        )
        raise TranscribeError(
            422, "asr_not_understood",
            "I didn't catch that. Please try again in English.")


async def transcribe(
    audio: bytes,
    *,
    filename: str,
    content_type: str,
    agent_voiceprint: Optional[str] = None,
    request_id: Optional[str] = None,
) -> Transcription:
    """POST audio to the RACE transcribe endpoint and normalize the result."""
    _require_config()

    headers = {"x-api-key": VOICE_ASR_API_KEY}
    files = {"file": (filename, audio, content_type)}

    data = {}
    # A hint, not a guarantee. The gateway accepts the field without
    # complaint, but its OpenAPI documents only `file` and `agent_voiceprint`,
    # so there is no way to confirm it constrains decoding — which is exactly
    # why _reject_if_not_expected_language still validates the RESULT. Sending
    # it costs nothing and helps if the upstream does honour it.
    if VOICE_EXPECTED_LANGUAGE:
        data["language"] = VOICE_EXPECTED_LANGUAGE
    if agent_voiceprint and VOICE_ALLOW_AGENT_VOICEPRINT:
        data["agent_voiceprint"] = agent_voiceprint

    last_exc: Optional[Exception] = None

    for attempt in range(1, _MAX_ATTEMPTS + 1):
        try:
            resp = await _http.post(TRANSCRIBE_URL, headers=headers, files=files,
                                    data=data or None)
        except httpx.ReadTimeout as e:
            # NEVER retried: the request reached the GPU and may well have been
            # processed. Retrying doubles GPU cost, billed seconds and queue
            # pressure on a box that is already too slow.
            logger.warning("ASR read timeout (not retried) | req=%s", request_id)
            raise TranscribeError(504, "asr_timeout",
                                  "The voice service took too long to respond.") from e
        except (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout) as e:
            last_exc = e
            if attempt < _MAX_ATTEMPTS:
                await asyncio.sleep(_backoff(attempt))
                continue
            logger.warning("ASR unreachable after %d attempts | req=%s: %s",
                           attempt, request_id, e)
            raise TranscribeError(503, "asr_unavailable",
                                  "The voice service is temporarily unavailable.") from e
        except httpx.HTTPError as e:
            logger.warning("ASR transport error | req=%s: %s", request_id, e)
            raise TranscribeError(502, "asr_upstream_error",
                                  "The voice service returned an unexpected error.") from e

        if resp.status_code in _RETRY_STATUSES and attempt < _MAX_ATTEMPTS:
            await asyncio.sleep(_backoff(attempt))
            continue

        if resp.status_code in (401, 403):
            # Never echo "invalid api key" to the caller — that is a server
            # misconfiguration, not something the user can act on.
            logger.error("ASR rejected our api key | status=%d | req=%s",
                         resp.status_code, request_id)
            raise TranscribeError(500, "asr_not_configured",
                                  "Voice transcription is not configured correctly.",
                                  upstream_status=resp.status_code)

        if resp.status_code >= 400:
            logger.warning("ASR failed | status=%d | req=%s | body=%s",
                           resp.status_code, request_id, resp.text[:300])
            raise TranscribeError(502, "asr_upstream_error",
                                  "The voice service could not process that audio.",
                                  upstream_status=resp.status_code)

        try:
            body = resp.json()
        except ValueError:
            body = resp.text

        result = _normalize_transcription(body)

        # An empty transcript is NOT a success. Returning "" here would be
        # indistinguishable from "the user said nothing" and produces a
        # baffling empty chat turn; the caller needs to say "I didn't catch
        # that" instead.
        #
        # 422, NOT 502. The upstream did its job and answered 200 — there was
        # simply no speech in the audio. Calling that a Bad Gateway was wrong
        # twice over: it blamed a healthy service, and behind a reverse proxy
        # with ProxyErrorOverride the 5xx body is replaced by the proxy's own
        # HTML, so the error_code never reached the browser and a silent
        # recording surfaced as "502 Bad Gateway" instead of "say that again".
        if not result.text.strip() and not result.segments:
            logger.warning("ASR returned an empty transcript | req=%s | keys=%s | body=%s",
                           request_id, result.raw_keys, str(body)[:300])
            raise TranscribeError(422, "asr_empty",
                                  "I didn't catch that. Please try again.")

        _reject_if_not_expected_language(result, request_id)

        return result

    raise TranscribeError(503, "asr_unavailable",
                          "The voice service is temporarily unavailable.") from last_exc


def _backoff(attempt: int) -> float:
    """0.5s then 2.0s, +/-25% jitter so retries don't synchronize across workers."""
    base = 0.5 if attempt == 1 else 2.0
    return base * (1 + random.uniform(-0.25, 0.25))


async def healthcheck(timeout: float = 3.0) -> dict:
    """Probe the gateway. INFORMATIONAL ONLY — never gate startup or build a
    circuit breaker on this. A sub-dependency can report unhealthy while
    transcription works fine, and a working feature staying dark is worse than
    a red status line."""
    if not is_configured():
        return {"configured": False, "reachable": False, "detail": "api key not set"}
    try:
        resp = await _http.get(
            f"{VOICE_ASR_BASE_URL.rstrip('/')}/healthz",
            headers={"x-api-key": VOICE_ASR_API_KEY},
            timeout=timeout,
        )
        return {"configured": True, "reachable": True, "upstream_status": resp.status_code}
    except Exception as e:
        return {"configured": True, "reachable": False, "detail": str(e)[:200]}


# ── Keep-warm ─────────────────────────────────────────────────────────────────
# Measured on the live gateway: the first transcription after an idle period
# takes ~35 SECONDS (model load), while every warm call is ~1s. Against a 2s
# target that is not a slow request, it is a request the user assumes has hung
# — and it lands on whoever opens the app first each morning.
#
# The fix is to be that first caller ourselves. A tiny synthetic clip costs one
# short GPU job and takes the cold start off the user's path.

VOICE_WARMUP_ENABLED = os.getenv("VOICE_WARMUP_ENABLED", "true").strip().lower() in (
    "1", "true", "yes", "on")
# Slightly under a typical model-eviction window. 0 disables the repeat and
# leaves only the one at startup.
VOICE_WARMUP_INTERVAL_SEC = int(os.getenv("VOICE_WARMUP_INTERVAL_SEC", 600))

_WARMUP_WAV = (
    b"RIFF" + (36 + 3200).to_bytes(4, "little") + b"WAVE"
    + b"fmt " + (16).to_bytes(4, "little")
    + (1).to_bytes(2, "little") + (1).to_bytes(2, "little")
    + (16000).to_bytes(4, "little") + (32000).to_bytes(4, "little")
    + (2).to_bytes(2, "little") + (16).to_bytes(2, "little")
    + b"data" + (3200).to_bytes(4, "little") + bytes(3200)   # 0.1s of silence
)


async def warmup(reason: str = "startup") -> bool:
    """Push a throwaway clip through the gateway so the model is resident.

    Never raises and never blocks anything: a failed warmup only means the
    next real request pays the cold start, which is exactly what happens today.
    """
    if not (VOICE_WARMUP_ENABLED and is_configured()):
        return False
    started = time.monotonic()
    try:
        await transcribe(_WARMUP_WAV, filename="warmup.wav",
                         content_type="audio/wav", request_id=f"warmup-{reason}")
    except TranscribeError as e:
        # asr_empty is the EXPECTED answer for silence — the model still loaded,
        # which is the entire point.
        if e.error_code == "asr_empty":
            logger.info("VOICE warmup ok (%s) | %.1fs", reason, time.monotonic() - started)
            return True
        logger.warning("VOICE warmup failed (%s): %s", reason, e.error_code)
        return False
    except Exception as e:
        logger.warning("VOICE warmup failed (%s): %s", reason, e)
        return False
    logger.info("VOICE warmup ok (%s) | %.1fs", reason, time.monotonic() - started)
    return True


async def warmup_loop() -> None:
    """Warm at startup, then on an interval so an idle gateway never goes cold
    under a user."""
    await warmup("startup")
    if VOICE_WARMUP_INTERVAL_SEC <= 0:
        return
    while True:
        try:
            await asyncio.sleep(VOICE_WARMUP_INTERVAL_SEC)
            await warmup("interval")
        except asyncio.CancelledError:
            raise
        except Exception as e:  # a keep-warm task must never kill the app
            logger.warning("VOICE warmup loop error: %s", e)
