"""Compatibility helpers for OpenAI-compatible providers."""

from __future__ import annotations

from typing import Any


def normalize_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
    """Trim provider-unsafe empty payloads."""
    normalized: list[dict[str, Any]] = []
    for message in messages:
        clean = dict(message)
        content = clean.get("content")
        if isinstance(content, str) and content == "":
            clean["content"] = None if clean.get("role") == "assistant" else "(empty)"
        normalized.append(clean)
    return normalized


def build_request_payload(
    model: str,
    messages: list[dict[str, Any]],
    tools: list[dict[str, Any]] | None,
) -> dict[str, Any]:
    """Build a chat completions payload with the current compat defaults."""
    payload: dict[str, Any] = {
        "model": model,
        "messages": normalize_messages(messages),
    }
    if tools:
        payload["tools"] = tools
        payload["tool_choice"] = "auto"
    return payload
