"""Shared helper for LLM calls that must return one structured JSON object.

Used by every recruitment feature that asks the model for JSON (resume
parsing, JD generation, and future features from the same module) so the
"parse, and repair once on failure" behaviour lives in exactly one place.
"""
import json
import logging
from typing import TypeVar

from pydantic import BaseModel, ValidationError

from recruitment import race_client
from recruitment.errors import RecruitmentError

logger = logging.getLogger(__name__)

ModelT = TypeVar("ModelT", bound=BaseModel)


def parse_json_object(raw: str, model: type[ModelT]) -> ModelT:
    """Parses a model reply into `model`. Tolerates markdown fences and stray
    prose around the object by slicing from the first '{' to the last '}'."""
    start, end = raw.find("{"), raw.rfind("}")
    if start == -1 or end <= start:
        raise ValueError("no JSON object in model reply")
    data = json.loads(raw[start : end + 1])
    return model.model_validate(data)


async def chat_for_json(messages: list[dict], model: type[ModelT], *, retry_prompt: str, log_label: str) -> ModelT:
    """Calls race_client.chat and parses the reply as `model`. On a parse or
    validation failure, retries once by showing the model its own bad output
    and asking it to correct it; raises RecruitmentError(502) if that also
    fails."""
    raw = await race_client.chat(messages)
    try:
        return parse_json_object(raw, model)
    except (ValueError, ValidationError):
        logger.warning("%s: first LLM reply was not valid JSON, retrying once", log_label)
        messages = messages + [
            {"role": "assistant", "content": raw},
            {"role": "user", "content": retry_prompt},
        ]
        raw = await race_client.chat(messages)
        try:
            return parse_json_object(raw, model)
        except (ValueError, ValidationError) as exc:
            logger.error("%s: LLM returned invalid JSON twice (%s)", log_label, type(exc).__name__)
            raise RecruitmentError(502, "AI service returned an unparseable response") from exc
