"""
Critical Blocklist - Patterns that are auto-rejected.

These patterns represent dangerous operations that should never
be allowed without explicit human intervention.
"""

import re
from typing import List, Pattern

# Critical blocklist patterns - auto-reject these
CRITICAL_BLOCKLIST: List[str] = [
    # Force pushes
    r"git\s+push\s+.*--force",
    r"git\s+push\s+-f",
    r"git\s+push\s+--force-with-lease",

    # Destructive git operations
    r"git\s+reset\s+--hard\s+origin",
    r"git\s+clean\s+-fd",
    r"git\s+checkout\s+--\s+\.",

    # Dangerous shell commands
    r"rm\s+-rf\s+/(?!\S)",  # rm -rf / (root)
    r"rm\s+-rf\s+~",        # rm -rf ~ (home)
    r"rm\s+-rf\s+\*",       # rm -rf *
    r":\(\)\s*\{\s*:\|\:\s*&\s*\}\s*;",  # Fork bomb

    # Exfiltration patterns
    r"curl\s+.*\s+\|\s*sh",
    r"wget\s+.*\s+-O\s*-\s*\|\s*sh",
    r"base64\s+.*\|\s*curl",
    r"nc\s+-e\s+/bin/",

    # Infrastructure destruction
    r"terraform\s+destroy\s+-auto-approve",
    r"kubectl\s+delete\s+namespace\s+prod",
    r"kubectl\s+delete\s+.*--all\s+--all-namespaces",
    r"helm\s+delete\s+.*--purge",

    # Database destruction
    r"DROP\s+DATABASE",
    r"DROP\s+TABLE",
    r"TRUNCATE\s+TABLE",
    r"DELETE\s+FROM\s+\w+\s*;?\s*$",  # DELETE without WHERE

    # Credential exposure
    r"echo\s+.*API_KEY",
    r"echo\s+.*SECRET",
    r"echo\s+.*PASSWORD",
    r"cat\s+.*\.env\s*>\s*/dev/tcp",
    r"printenv\s*\|\s*curl",

    # AWS dangerous operations
    r"aws\s+iam\s+delete-user",
    r"aws\s+s3\s+rb\s+.*--force",
    r"aws\s+ec2\s+terminate-instances",
    r"aws\s+rds\s+delete-db-instance",

    # GCP dangerous operations
    r"gcloud\s+projects\s+delete",
    r"gcloud\s+compute\s+instances\s+delete",
    r"gsutil\s+rm\s+-r\s+gs://",

    # Azure dangerous operations
    r"az\s+group\s+delete",
    r"az\s+vm\s+delete",
    r"az\s+storage\s+account\s+delete",
]

# Compiled patterns for faster matching
_compiled_blocklist: List[Pattern] = [
    re.compile(pattern, re.IGNORECASE) for pattern in CRITICAL_BLOCKLIST
]


def is_blocklisted(command: str) -> bool:
    """
    Check if a command matches any blocklist pattern.

    Args:
        command: Command string to check

    Returns:
        True if command is blocklisted
    """
    for pattern in _compiled_blocklist:
        if pattern.search(command):
            return True
    return False


def get_matching_pattern(command: str) -> str:
    """
    Get the blocklist pattern that matches a command.

    Args:
        command: Command string to check

    Returns:
        Matching pattern string, or empty string if no match
    """
    for i, pattern in enumerate(_compiled_blocklist):
        if pattern.search(command):
            return CRITICAL_BLOCKLIST[i]
    return ""
