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

import asyncio
import logging

import litellm

litellm.drop_params = True


async def llm_acompletion_retry(model: str, prompt: str, max_retries: int = 10,
                                temperature: float = 0) -> str:
    """Asynchronous 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.
        max_retries: Max retry attempts on failure.
        temperature: Sampling temperature.

    Returns:
        str: Response content. Empty string if all retries fail.
    """
    if model:
        model = model.removeprefix("litellm/")

    messages = [{"role": "user", "content": prompt}]

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