"""AUTH-001: Missing Authentication detection rule."""

from __future__ import annotations

import ast

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


class MissingAuthRule(Rule):
    """Detects MCP servers without authentication."""

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

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

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

    @property
    def description(self) -> str:
        return "Server without authentication mechanism."

    def suggest_fix(self, source: str, finding: Finding) -> str | None:
        """Suggest adding an auth check stub at the top of the server file."""
        lines = source.splitlines()
        if finding.line < 1 or finding.line > len(lines):
            return None
        # Insert a TODO comment reminding to add auth
        return '# TODO: Add authentication — e.g. verify API key or token before handling requests'

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

        has_auth = any(
            kw in source_lower
            for kw in ("auth", "api_key", "authenticate", "authorize")
        )
        has_server = "Server(" in source or "app = " in source

        if has_server and not has_auth:
            findings.append(Finding(
                rule_id=self.rule_id,
                severity=self.severity,
                title="Sin autenticacion detectada",
                description="El servidor MCP no implementa autenticacion.",
                file="",
                line=1,
                recommendation="Nota: en MCP servers locales (stdio) puede ser aceptable.",
                cwe="CWE-306",
                confidence="LOW",
            ))
        return findings
