"""Risk classification engine."""

from __future__ import annotations

from interceptor.types import RiskLevel

DEFAULT_DESTRUCTIVE_KEYWORDS: list[str] = [
    "delete",
    "remove",
    "drop",
    "overwrite",
    "truncate",
    "rewrite",
]


class RiskClassifier:
    """Classify tool calls into LOW / MEDIUM / HIGH risk.

    Risk is determined by:
    1. Policy overrides (highest priority)
    2. Destructive keyword matches in tool name or argument values
    3. Default LOW otherwise

    Extend by subclassing and overriding ``classify``.
    """

    def __init__(
        self,
        extra_keywords: list[str] | None = None,
        tool_overrides: dict[str, RiskLevel] | None = None,
    ) -> None:
        self._keywords = DEFAULT_DESTRUCTIVE_KEYWORDS + (extra_keywords or [])
        self._tool_overrides = tool_overrides or {}

    # -- public ---------------------------------------------------------------

    def classify(self, tool_name: str, args: dict) -> RiskLevel:
        """Return the risk level for a tool call."""
        # 1. Explicit policy override
        if tool_name in self._tool_overrides:
            return self._tool_overrides[tool_name]

        # 2. Keyword scan
        if self._has_keyword(tool_name, args):
            return RiskLevel.HIGH

        # 3. Heuristic: filesystem-path arguments bump to MEDIUM
        if self._has_path_arg(args):
            return RiskLevel.MEDIUM

        return RiskLevel.LOW

    # -- internals ------------------------------------------------------------

    def _has_keyword(self, tool_name: str, args: dict) -> bool:
        name_lower = tool_name.lower()
        for kw in self._keywords:
            if kw in name_lower:
                return True
        for value in args.values():
            val_str = str(value).lower()
            for kw in self._keywords:
                if kw in val_str:
                    return True
        return False

    @staticmethod
    def _has_path_arg(args: dict) -> bool:
        for value in args.values():
            if isinstance(value, str) and ("/" in value or "\\" in value):
                return True
        return False
