"""API rate limiting — sliding window counter per user."""

from __future__ import annotations

import time
import threading
from collections import defaultdict

from radix_edge.config import get_config


class RateLimiter:
    """In-memory sliding window rate limiter."""

    def __init__(self):
        config = get_config()
        self.max_requests = config.rate_limit_requests_per_min
        self.window_seconds = 60
        self._requests: dict[str, list[float]] = defaultdict(list)
        self._lock = threading.Lock()

    def check(self, user_id: str) -> tuple[bool, int]:
        """Check if a request is allowed. Returns (allowed, remaining)."""
        now = time.monotonic()
        cutoff = now - self.window_seconds

        with self._lock:
            # Prune old entries
            timestamps = self._requests[user_id]
            self._requests[user_id] = [t for t in timestamps if t > cutoff]

            remaining = self.max_requests - len(self._requests[user_id])

            if remaining <= 0:
                return False, 0

            self._requests[user_id].append(now)
            return True, remaining - 1

    def reset(self, user_id: str = None):
        """Reset rate limits (for testing)."""
        with self._lock:
            if user_id:
                self._requests.pop(user_id, None)
            else:
                self._requests.clear()
