"""INFO-001: Information Disclosure detection rule."""

from __future__ import annotations

import ast

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


class InformationDisclosureRule(Rule):
    """Detects error handlers that may leak internal information."""

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

    @property
    def name(self) -> str:
        return "Information Disclosure"

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

    @property
    def description(self) -> str:
        return "Error handlers returning detailed exceptions may expose internals."

    def check(self, tree: ast.Module, source: str) -> list[Finding]:
        """Check for exception handlers that return tracebacks to users."""
        findings: list[Finding] = []

        for node in ast.walk(tree):
            if not isinstance(node, ast.ExceptHandler):
                continue
            body_src = ast.get_source_segment(source, node) or ""
            if "traceback" not in body_src and "str(e)" not in body_src:
                continue
            if "return" not in body_src:
                continue

            findings.append(Finding(
                rule_id=self.rule_id,
                severity=self.severity,
                title="Information Disclosure en error handler",
                description="Excepciones detalladas podrian exponer info interna.",
                file="",
                line=node.lineno,
                recommendation="Devolver mensaje generico al usuario.",
                cwe="CWE-200",
            ))
        return findings
