"""Thin async client for the two race-api endpoints the module needs."""
import logging

import httpx

from recruitment import config
from recruitment.errors import RecruitmentError

logger = logging.getLogger(__name__)

_http = httpx.AsyncClient(
    timeout=httpx.Timeout(
        connect=10.0,
        read=max(config.OCR_TIMEOUT_SECONDS, config.LLM_TIMEOUT_SECONDS),
        write=30.0,
        pool=5.0,
    )
)


def _headers() -> dict:
    if not config.RACE_API_KEY:
        raise RecruitmentError(500, "RACE_API_KEY is not configured")
    return {"x-api-key": config.RACE_API_KEY}


def _upstream_error(service: str, exc: Exception) -> RecruitmentError:
    """Maps a failed race-api call to a client-facing error without leaking the
    upstream body (it can echo resume text). Details go to the server log."""
    if isinstance(exc, httpx.TimeoutException):
        logger.error("race-api %s timed out", service)
        return RecruitmentError(504, f"{service} service timed out")
    if isinstance(exc, httpx.HTTPStatusError):
        logger.error("race-api %s returned status=%s", service, exc.response.status_code)
        if exc.response.status_code in (401, 403):
            return RecruitmentError(502, f"{service} service rejected the API key or its scope")
        return RecruitmentError(502, f"{service} service returned an error")
    logger.error("race-api %s unreachable: %s", service, type(exc).__name__)
    return RecruitmentError(502, f"{service} service unavailable")


async def ocr_pdf(filename: str, content: bytes) -> str:
    """Returns the full text of a PDF. race-api reads the native text layer
    where there is one and only runs the OCR model on scanned pages."""
    try:
        resp = await _http.post(
            config.RACE_OCR_URL,
            files={"file": (filename, content, "application/pdf")},
            headers=_headers(),
            timeout=config.OCR_TIMEOUT_SECONDS,
        )
        resp.raise_for_status()
        return (resp.json().get("text") or "").strip()
    except (httpx.HTTPError, ValueError) as exc:
        raise _upstream_error("OCR", exc) from exc


async def chat(messages: list[dict]) -> str:
    """One non-streaming chat completion at temperature 0 (extraction should be
    deterministic). Returns the assistant message text."""
    payload = {
        "model": config.RACE_API_MODEL,
        "messages": messages,
        "max_tokens": config.LLM_MAX_TOKENS,
        "temperature": 0,
        "stream": False,
    }
    try:
        resp = await _http.post(
            config.RACE_CHAT_URL,
            json=payload,
            headers=_headers(),
            timeout=config.LLM_TIMEOUT_SECONDS,
        )
        resp.raise_for_status()
        choices = resp.json().get("choices") or []
    except (httpx.HTTPError, ValueError) as exc:
        raise _upstream_error("LLM", exc) from exc

    content = choices[0].get("message", {}).get("content") if choices else None
    return (content or "").strip()
