"""Small explicit service protections."""

from __future__ import annotations

import threading
import time

from .errors import RequestLimitError


class TokenBucket:
    def __init__(self, rate_per_minute: int = 30, burst: int = 10):
        self.rate_per_second = rate_per_minute / 60
        self.burst = float(burst)
        self._buckets: dict[str, tuple[float, float]] = {}
        self._lock = threading.Lock()

    def consume(self, key: str) -> None:
        now = time.monotonic()
        with self._lock:
            tokens, updated = self._buckets.get(key, (self.burst, now))
            tokens = min(self.burst, tokens + (now - updated) * self.rate_per_second)
            if tokens < 1:
                raise RequestLimitError("rate limit exceeded")
            self._buckets[key] = (tokens - 1, now)

