"""Shared sliding window rate limiter."""

import logging
import time

logger = logging.getLogger("skop-runner")


class SlidingWindowRateLimiter:
    """Sliding window rate limiter that logs a warning on first rejection per burst."""

    def __init__(
        self,
        max_per_second: int,
        window_seconds: float = 1.0,
        label: str = "",
    ):
        self._max = max_per_second
        self._window = window_seconds
        self._label = label
        self._timestamps: list[float] = []
        self._warned = False

    def allow(self) -> bool:
        """Check if the next message is allowed. Returns False if rate limited."""
        now = time.monotonic()
        cutoff = now - self._window

        # Remove expired timestamps and bound list size
        self._timestamps = [
            ts for ts in self._timestamps if ts > cutoff
        ][-self._max:]

        if len(self._timestamps) >= self._max:
            if not self._warned:
                logger.warning(
                    f"Rate limit exceeded ({self._max}/s)"
                    f"{f' for {self._label}' if self._label else ''}. "
                    f"Some messages may be dropped."
                )
                self._warned = True
            return False

        self._timestamps.append(now)
        self._warned = False
        return True

    def reset(self):
        """Reset all state. Call on reconnect."""
        self._timestamps.clear()
        self._warned = False
