"""RATE-001: Missing Rate Limiting detection rule."""

from __future__ import annotations

import ast

from . import Rule
from ..models import Finding, Severity


class MissingRateLimitingRule(Rule):
    """Detects servers without rate limiting."""

    @property
    def rule_id(self) -> str:
        return "RATE-001"

    @property
    def name(self) -> str:
        return "Missing Rate Limiting"

    @property
    def severity(self) -> Severity:
        return Severity.LOW

    @property
    def description(self) -> str:
        return "Server without rate limiting may be vulnerable to DoS."

    def check(self, tree: ast.Module, source: str) -> list[Finding]:
        """Check if a server file lacks rate limiting."""
        findings: list[Finding] = []
        source_lower = source.lower()

        has_server = "Server(" in source or "app = " in source
        has_rl = any(
            kw in source_lower
            for kw in ("rate_limit", "ratelimit", "throttle", "max_requests")
        )

        if has_server and not has_rl:
            findings.append(Finding(
                rule_id=self.rule_id,
                severity=self.severity,
                title="Sin rate limiting",
                description="No se detecta rate limiting.",
                file="",
                line=1,
                recommendation="Nota: en MCP stdio puede ser aceptable.",
                cwe="CWE-770",
                confidence="LOW",
            ))
        return findings
