"""Shell command execution tool"""

import subprocess
from typing import Dict, Any


class ShellTool:
    """Shell command execution tool"""
    
    def __init__(self, config: Dict[str, Any]):
        """Initialize shell tool
        
        Args:
            config: Tool configuration
        """
        self.config = config
        self.safe_mode = config.get('safe-mode', True)
        self.description = "Shell command execution tool"
        # Safe mode commands that are allowed
        self.safe_commands = {
            'dir', 'ls', 'pwd', 'echo', 'date', 'time', 'whoami',
            'git', 'python', 'pip', 'node', 'npm', 'yarn'
        }
    
    def execute(self, command: str, **params) -> str:
        """Execute shell command
        
        Args:
            command: Command to execute
            params: Additional parameters
            
        Returns:
            Command output
        """
        # Check if command is allowed in safe mode
        if self.safe_mode:
            cmd_parts = command.split()
            if not cmd_parts:
                return "Empty command"
            
            cmd_name = cmd_parts[0].lower()
            if cmd_name not in self.safe_commands:
                return f"Command not allowed in safe mode: {cmd_name}"
        
        try:
            # Execute command
            result = subprocess.run(
                command,
                shell=True,
                capture_output=True,
                text=True,
                timeout=30  # 30 second timeout
            )
            
            output = ""
            if result.stdout:
                output += result.stdout
            if result.stderr:
                output += f"\nError: {result.stderr}"
            
            return output.strip() or f"Command executed with exit code: {result.returncode}"
        except Exception as e:
            return f"Error executing command: {str(e)}"
    
    def get_schema(self) -> Dict[str, Any]:
        """Get tool schema
        
        Returns:
            JSON Schema for the tool
        """
        return {
            "name": "shell",
            "description": self.description,
            "parameters": {
                "type": "object",
                "properties": {
                    "command": {
                        "type": "string",
                        "description": "Shell command to execute"
                    }
                },
                "required": ["command"]
            }
        }
