"""CORS-001: CORS Misconfiguration detection rule."""

from __future__ import annotations

import ast

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


class CorsMisconfigurationRule(Rule):
    """Detects wildcard CORS configurations."""

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

    @property
    def name(self) -> str:
        return "CORS Misconfiguration"

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

    @property
    def description(self) -> str:
        return "Wildcard CORS allows requests from any origin."

    def check(self, tree: ast.Module, source: str) -> list[Finding]:
        """Check for wildcard CORS configuration."""
        findings: list[Finding] = []
        lines = self._get_lines(source)

        for i, line in enumerate(lines, 1):
            if "Access-Control-Allow-Origin" in line and "*" in line:
                findings.append(Finding(
                    rule_id=self.rule_id,
                    severity=self.severity,
                    title="CORS abierto (wildcard)",
                    description="Permite requests desde cualquier origen.",
                    file="",
                    line=i,
                    recommendation="Restringir a dominios especificos.",
                    cwe="CWE-942",
                    confidence="MEDIUM",
                ))
        return findings
