"""PERM-001: Excessive Permissions detection rule."""

from __future__ import annotations

import ast
import re

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


class ExcessivePermissionsRule(Rule):
    """Detects world-writable file permissions (chmod 777)."""

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

    @property
    def name(self) -> str:
        return "Excessive Permissions"

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

    @property
    def description(self) -> str:
        return "World-writable file permissions (777) detected."

    def check(self, tree: ast.Module, source: str) -> list[Finding]:
        """Check for chmod 777 or similar excessive permissions."""
        findings: list[Finding] = []
        lines = self._get_lines(source)

        for i, line in enumerate(lines, 1):
            if re.search(r'chmod.*0?777|chmod.*0o777', line):
                findings.append(Finding(
                    rule_id=self.rule_id,
                    severity=self.severity,
                    title="Excessive permissions (777)",
                    description="World-writable file permissions detected.",
                    file="",
                    line=i,
                    recommendation="Use 0o644 for files, 0o755 for directories.",
                    cwe="CWE-250",
                    confidence="MEDIUM",
                ))
        return findings
