"""
core/retry_handler.py

Generic retry engine
Exponential backoff + jitter
"""

import asyncio
import random

from remottxrea.core.logger import get_action_logger


class RetryHandler:

    MAX_RETRIES = 3
    BASE_DELAY = 5

    @staticmethod
    async def retry(
        coro,
        session_name: str,
        action: str
    ):

        logger = get_action_logger(
            action="retry_handler",
            session=session_name
        )

        for attempt in range(
            1,
            RetryHandler.MAX_RETRIES + 1
        ):

            try:

                result = await coro
                return result

            except Exception as e:

                if attempt == RetryHandler.MAX_RETRIES:

                    logger.error(
                        f"Retry failed | "
                        f"Action={action} | "
                        f"Attempts={attempt}"
                    )

                    raise

                delay = (
                    RetryHandler.BASE_DELAY
                    * attempt
                )

                # jitter
                delay += random.uniform(1, 3)

                logger.warning(
                    f"Retry {attempt} | "
                    f"Delay={delay:.1f}s"
                )

                await asyncio.sleep(delay)
