"""CascadeDetector - 独立的级联故障检测工具"""

from __future__ import annotations

from dataclasses import dataclass


@dataclass
class CascadeAlert:
    """级联故障告警"""

    session_id: str
    alert_type: str  # "interaction_limit" or "loop_depth"
    current_value: int
    threshold: int
    message: str


class CascadeDetector:
    """检测多 agent 交互中的级联故障"""

    def __init__(self, max_interactions: int = 10, max_depth: int = 3):
        self._max_interactions = max_interactions
        self._max_depth = max_depth
        self._interaction_counts: dict[str, int] = {}
        self._loop_depths: dict[str, int] = {}

    def check_interaction(self, session_id: str) -> CascadeAlert | None:
        """递增并检查交互计数"""
        self._interaction_counts[session_id] = (
            self._interaction_counts.get(session_id, 0) + 1
        )
        count = self._interaction_counts[session_id]
        if count > self._max_interactions:
            return CascadeAlert(
                session_id=session_id,
                alert_type="interaction_limit",
                current_value=count,
                threshold=self._max_interactions,
                message=(
                    f"Session {session_id} exceeded max interactions: "
                    f"{count} > {self._max_interactions}"
                ),
            )
        return None

    def check_depth(self, session_id: str, depth: int) -> CascadeAlert | None:
        """检查循环深度"""
        self._loop_depths[session_id] = depth
        if depth > self._max_depth:
            return CascadeAlert(
                session_id=session_id,
                alert_type="loop_depth",
                current_value=depth,
                threshold=self._max_depth,
                message=(
                    f"Session {session_id} exceeded max loop depth: "
                    f"{depth} > {self._max_depth}"
                ),
            )
        return None

    def reset(self, session_id: str) -> None:
        """重置某个 session 的计数器"""
        self._interaction_counts.pop(session_id, None)
        self._loop_depths.pop(session_id, None)

    def get_stats(self, session_id: str) -> dict[str, int]:
        """获取某个 session 的当前统计"""
        return {
            "interactions": self._interaction_counts.get(session_id, 0),
            "depth": self._loop_depths.get(session_id, 0),
        }
