"""Retry throttling for repeated tool calls."""

from __future__ import annotations

import time
from collections import defaultdict


class RetryThrottle:
    """Sliding-window tracker that detects repeated tool invocations.

    If the same tool is called more than ``max_calls`` times within
    ``window_seconds``, :meth:`is_throttled` returns ``True``.
    """

    def __init__(
        self,
        max_calls: int = 5,
        window_seconds: float = 60.0,
    ) -> None:
        self._max_calls = max_calls
        self._window = window_seconds
        self._history: dict[str, list[float]] = defaultdict(list)

    def record(self, tool_name: str) -> None:
        """Record an invocation of *tool_name*."""
        self._history[tool_name].append(time.time())

    def is_throttled(self, tool_name: str) -> bool:
        """Return ``True`` if *tool_name* has exceeded the call limit."""
        now = time.time()
        timestamps = self._history.get(tool_name, [])
        # Keep only timestamps within the window
        recent = [t for t in timestamps if now - t <= self._window]
        self._history[tool_name] = recent
        return len(recent) >= self._max_calls
