"""Text-only compatibility hook for LiteLLM 1.106.0 and Logits Chat Completions."""
from litellm.integrations.custom_logger import CustomLogger

# The current model ID, and the earlier one that existing litellm.yaml files
# still name. The Logits API accepts both.
MODELS = (
    "deepseek/deepseek-v4.1-flash",
    "deepseek-v4.1-flash",
    "logits/deepseek-v4.1-flash-abliterated",
    "deepseek-v4.1-flash-abliterated",
)


def text_messages(messages):
    if not isinstance(messages, list):
        return messages
    result = []
    for message in messages:
        if not isinstance(message, dict) or not isinstance(message.get("content"), list):
            result.append(message)
            continue
        parts = message["content"]
        if not all(isinstance(part, dict) and part.get("type") in
                   ("text", "input_text", "output_text") and
                   isinstance(part.get("text"), str) for part in parts):
            raise ValueError("The Logits coding pilot accepts text content only")
        result.append({**message, "content": "\n".join(part["text"] for part in parts)})
    return result


class LogitsTextMessages(CustomLogger):
    async def async_pre_call_deployment_hook(self, kwargs, call_type):
        if kwargs.get("model", "").removeprefix("openai/") not in MODELS:
            return kwargs
        for field in ("input", "messages"):
            if field in kwargs:
                kwargs[field] = text_messages(kwargs[field])
        return kwargs


handler = LogitsTextMessages()
