"""Rate limiting for code analyzer endpoints."""
import time
from collections import defaultdict
from typing import Dict, Tuple
import threading


class RateLimiter:
    """Simple in-memory rate limiter using sliding window."""
    
    def __init__(self, max_requests: int = 10, window_seconds: int = 60):
        """Initialize rate limiter.
        
        Args:
            max_requests: Maximum requests allowed per window
            window_seconds: Time window in seconds
        """
        self.max_requests = max_requests
        self.window_seconds = window_seconds
        self._requests: Dict[str, list] = defaultdict(list)
        self._lock = threading.Lock()
    
    def is_allowed(self, key: str) -> Tuple[bool, int]:
        """Check if request is allowed for given key.
        
        Args:
            key: Identifier for rate limiting (e.g., user_id)
            
        Returns:
            Tuple of (is_allowed, retry_after_seconds)
        """
        with self._lock:
            now = time.time()
            cutoff = now - self.window_seconds
            
            # Remove old requests
            self._requests[key] = [ts for ts in self._requests[key] if ts > cutoff]
            
            # Check if allowed
            if len(self._requests[key]) < self.max_requests:
                self._requests[key].append(now)
                return True, 0
            
            # Calculate retry after
            oldest = min(self._requests[key])
            retry_after = int(oldest + self.window_seconds - now) + 1
            return False, retry_after
    
    def reset(self, key: str):
        """Reset rate limit for a key."""
        with self._lock:
            if key in self._requests:
                del self._requests[key]


# Global rate limiters
scan_rate_limiter = RateLimiter(max_requests=10, window_seconds=60)
patch_rate_limiter = RateLimiter(max_requests=20, window_seconds=60)
