"""
Security Hook

Blocks dangerous commands and validates tool inputs for safety.
"""

import re
from typing import Any

from ai_coder.hooks.base import PreToolHook, HookResult


class SecurityHook(PreToolHook):
    """
    Security hook that blocks dangerous operations.
    
    Checks for:
    - Dangerous shell commands (rm -rf, format, etc.)
    - Path traversal attacks
    - Sensitive file access
    - System file modifications
    """
    
    # Dangerous command patterns
    DANGEROUS_COMMANDS = [
        r'\brm\s+(-rf?|--force)\s+[/~]',           # rm -rf /
        r'\brm\s+(-rf?|--force)\s+\*',             # rm -rf *
        r'\bformat\b.*\b[A-Za-z]:',                # format C:
        r'\bdel\s+/[sS]',                          # del /S (Windows recursive delete)
        r'\brd\s+/[sS]',                           # rd /S (Windows recursive delete)
        r'\b(chmod|chown)\s+.*\s+/',               # chmod on root
        r'\bmkfs\b',                               # Format filesystem
        r'\bdd\s+if=.*of=/dev/',                   # dd to device
        r':(){.*};:',                              # Fork bomb
        r'\b>\s*/dev/sd[a-z]',                     # Write to disk device
        r'\bcurl.*\|\s*(bash|sh|python)',          # Pipe to shell
        r'\bwget.*\|\s*(bash|sh|python)',          # Pipe to shell
    ]
    
    # Sensitive paths to protect
    SENSITIVE_PATHS = [
        r'^/etc/',                                 # System config
        r'^/boot/',                                # Boot files
        r'^/sys/',                                 # Kernel interface
        r'^/proc/',                                # Process info
        r'^C:\\Windows\\System32',                 # Windows system
        r'^C:\\Windows\\SysWOW64',                 # Windows 64-bit system
        r'\.env$',                                 # Environment files
        r'\.ssh/',                                 # SSH keys
        r'id_rsa',                                 # SSH private keys
        r'\.aws/',                                 # AWS credentials
        r'\.kube/config',                          # Kubernetes config
    ]
    
    # Tools that execute commands
    COMMAND_TOOLS = ['run_command', 'execute', 'shell', 'bash', 'terminal']
    
    # Tools that write files
    WRITE_TOOLS = ['write_file', 'create_file', 'edit_file', 'patch_file']

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

    @property
    def description(self) -> str:
        return "Blocks dangerous commands and protects sensitive files"

    def applies_to(self, tool_name: str) -> bool:
        """Apply to command and file writing tools."""
        return tool_name.lower() in self.COMMAND_TOOLS + self.WRITE_TOOLS

    def before_execute(
        self,
        tool_name: str,
        args: dict[str, Any],
    ) -> HookResult:
        """Validate tool call for security issues."""
        
        # Check commands
        if tool_name.lower() in self.COMMAND_TOOLS:
            command = args.get('command', '') or args.get('cmd', '')
            result = self._check_command(command)
            if result:
                return result
        
        # Check file paths
        if tool_name.lower() in self.WRITE_TOOLS:
            path = args.get('path', '') or args.get('file_path', '') or args.get('file', '')
            result = self._check_path(path)
            if result:
                return result
        
        return HookResult.allow()

    def _check_command(self, command: str) -> HookResult | None:
        """Check if command is dangerous."""
        for pattern in self.DANGEROUS_COMMANDS:
            if re.search(pattern, command, re.IGNORECASE):
                return HookResult.block(
                    f"🚫 BLOCKED: Dangerous command detected\n"
                    f"Command: {command}\n"
                    f"Pattern: {pattern}"
                )
        return None

    def _check_path(self, path: str) -> HookResult | None:
        """Check if path is sensitive."""
        for pattern in self.SENSITIVE_PATHS:
            if re.search(pattern, path, re.IGNORECASE):
                return HookResult.block(
                    f"🚫 BLOCKED: Sensitive path detected\n"
                    f"Path: {path}\n"
                    f"Pattern: {pattern}"
                )
        return None


class CommandSanitizer(PreToolHook):
    """
    Sanitizes and normalizes commands before execution.
    
    - Converts grep to rg (ripgrep)
    - Converts find to fd
    - Adds safety flags
    """
    
    @property
    def name(self) -> str:
        return "command-sanitizer"

    @property
    def description(self) -> str:
        return "Sanitizes and improves commands"

    def applies_to(self, tool_name: str) -> bool:
        return tool_name.lower() in ['run_command', 'execute', 'shell', 'bash', 'terminal']

    def before_execute(
        self,
        tool_name: str,
        args: dict[str, Any],
    ) -> HookResult:
        """Sanitize command."""
        command = args.get('command', '') or args.get('cmd', '')
        
        if not command:
            return HookResult.allow()
        
        modified = command
        messages = []
        
        # Suggest ripgrep instead of grep
        if re.match(r'^grep\b', command) and not '|' in command:
            messages.append("💡 Consider using 'rg' (ripgrep) for better performance")
        
        # Suggest fd instead of find
        if re.match(r'^find\s+\S+\s+-name\b', command):
            messages.append("💡 Consider using 'fd' for better performance")
        
        if messages:
            return HookResult.warn('\n'.join(messages))
        
        return HookResult.allow()
