"""
Loop detector — fires an alert when too many AI calls happen in a time window.
"""

import time
from typing import Optional


class LoopDetector:
    def __init__(self, threshold: int = 10, window_seconds: float = 60.0):
        self.threshold = threshold
        self.window = window_seconds
        self._calls: list = []
        self._alerted = False

    def record(self) -> Optional[str]:
        """
        Record an AI call. Returns an alert message if loop detected, else None.
        Re-triggers after the window expires and a new burst begins.
        """
        now = time.time()
        self._calls = [t for t in self._calls if now - t < self.window]
        self._calls.append(now)

        if self._alerted and len(self._calls) < self.threshold:
            self._alerted = False

        if len(self._calls) >= self.threshold and not self._alerted:
            self._alerted = True
            return (
                f"Agent looped {len(self._calls)} times in {self.window:.0f}s — "
                "possible infinite loop detected"
            )

        return None
