"""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 suggest_fix(self, source: str, finding: Finding) -> str | None:
        """Replace chmod 777 with chmod 755 (dirs) or 644 (files)."""
        lines = source.splitlines()
        idx = finding.line - 1
        if idx < 0 or idx >= len(lines):
            return None
        line = lines[idx]
        import re as _re
        fixed = _re.sub(r'0?o?777', '0o755', line)
        if fixed == line:
            return None
        return fixed

    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
