"""Optional allowlisting for LLM kwargs sourced from config before run_raw_agent."""

from __future__ import annotations

import logging
from typing import Any

_ALLOWED_RESPONSE_FORMAT_TYPES = frozenset({"json_object", "text"})
_MAX_STOP_SEQ_LEN = 20


def validated_stop(stop: Any, log: logging.Logger, context: str) -> list[str] | None:
    if stop is None:
        return None
    if not isinstance(stop, list):
        log.warning("%s invalid stop: must be a list of strings (not passing)", context)
        return None
    out: list[str] = []
    for i, item in enumerate(stop):
        if not isinstance(item, str):
            log.warning("%s invalid stop[%d]: not a string (not passing stop)", context, i)
            return None
        if len(item) > _MAX_STOP_SEQ_LEN:
            log.warning(
                "%s invalid stop: each sequence must be <= %d chars (not passing stop)",
                context,
                _MAX_STOP_SEQ_LEN,
            )
            return None
        out.append(item)
    return out if out else None


def validated_response_format(rf: Any, log: logging.Logger, context: str) -> dict[str, Any] | None:
    if rf is None:
        return None
    if not isinstance(rf, dict):
        log.warning("%s invalid response_format: must be a dict (not passing)", context)
        return None
    typ = rf.get("type")
    if typ not in _ALLOWED_RESPONSE_FORMAT_TYPES:
        log.warning(
            "%s invalid response_format: type must be json_object or text (not passing)",
            context,
        )
        return None
    return rf
