"""LLM completion with retry logic via litellm. Supports 100+ models."""

import logging
import time

import litellm

litellm.drop_params = True


def llm_completion_retry(model: str, prompt: str, chat_history: list = None,
                         return_finish_reason: bool = False, max_retries: int = 10,
                         temperature: float = 0):
    """Synchronous LLM completion with retry. Multi-model support via litellm.

    Args:
        model: Model name (e.g. 'gpt-4o', 'claude-sonnet-4-20250514'). Strips 'litellm/' prefix.
        prompt: User prompt text.
        chat_history: Optional list of prior messages [{"role": ..., "content": ...}].
        return_finish_reason: If True, returns (content, reason) tuple.
        max_retries: Max retry attempts on failure.
        temperature: Sampling temperature.

    Returns:
        str or (str, str): Response content, optionally with finish reason.
    """
    if model:
        model = model.removeprefix("litellm/")

    messages = list(chat_history or []) + [{"role": "user", "content": prompt}]

    for i in range(max_retries):
        try:
            response = litellm.completion(
                model=model,
                messages=messages,
                temperature=temperature,
            )
            content = response.choices[0].message.content
            if return_finish_reason:
                reason = "max_output_reached" if response.choices[0].finish_reason == "length" else "finished"
                return content, reason
            return content
        except Exception as e:
            logging.error(f"LLM completion error (attempt {i+1}/{max_retries}): {e}")
            if i < max_retries - 1:
                time.sleep(1)
            else:
                logging.error(f"Max retries reached for model={model}")
                if return_finish_reason:
                    return "", "error"
                return ""
