"""Async retry decorator utility."""

import asyncio
from collections.abc import Callable
from functools import wraps
from typing import Any

from loguru import logger


def async_retry(max_retries: int = 3, delay: int = 2) -> Callable:
    """
    Decorator to retry async functions on failure.

    Args:
        max_retries: Maximum number of retry attempts
        delay: Delay in seconds between retries

    Returns:
        Decorated async function with retry logic
    """

    def decorator(func: Callable) -> Callable:
        @wraps(func)
        async def wrapper(*args: Any, **kwargs: Any) -> Any:
            for attempt in range(max_retries):
                try:
                    return await func(*args, **kwargs)
                except Exception as e:
                    logger.error(f"Error in {func.__name__}: {e}\nRetrying...")
                    if attempt == max_retries - 1:
                        logger.error(f"Max retries reached for {func.__name__}. Raising exception.")
                        raise
                    await asyncio.sleep(delay)
            return await func(*args, **kwargs)

        return wrapper

    return decorator
