"""
VELOCRIUM Retry - Smart retry with backoff
Author: Juste Elysée MALANDILA
"""

from typing import Literal
import time
import random


class Retry:
    """
    Smart retry configuration with exponential backoff and jitter.
    
    Example:
        >>> retry = Retry(max_attempts=3, backoff="exponential", jitter=True)
    """
    
    def __init__(
        self,
        max_attempts: int = 3,
        backoff: Literal["constant", "linear", "exponential"] = "exponential",
        jitter: bool = True,
        base_delay: float = 1.0,
        max_delay: float = 60.0,
    ):
        """
        Initialize retry configuration.
        
        Args:
            max_attempts: Maximum number of retry attempts
            backoff: Backoff strategy (constant, linear, exponential)
            jitter: Add random jitter to prevent thundering herd
            base_delay: Base delay in seconds
            max_delay: Maximum delay in seconds
        """
        self.max_attempts = max_attempts
        self.backoff = backoff
        self.jitter = jitter
        self.base_delay = base_delay
        self.max_delay = max_delay
    
    def get_delay(self, attempt: int) -> float:
        """
        Calculate delay for given attempt number.
        
        Args:
            attempt: Current attempt number (0-indexed)
            
        Returns:
            Delay in seconds
        """
        if self.backoff == "constant":
            delay = self.base_delay
        elif self.backoff == "linear":
            delay = self.base_delay * (attempt + 1)
        else:  # exponential
            delay = self.base_delay * (2 ** attempt)
        
        # Apply max delay cap
        delay = min(delay, self.max_delay)
        
        # Add jitter if enabled
        if self.jitter:
            delay = delay * (0.5 + random.random() * 0.5)
        
        return delay
