"""Shell tool for OpenAI Agent"""

import os
from agents import function_tool
from diona.project.shell import ShellCommander, ShellConfig


_home_dir = os.path.expanduser("~")
_diona_dir = os.path.join(_home_dir, ".diona")

_shell_commander = ShellCommander(
    ShellConfig(
        cwd_whitelist=[_diona_dir],
        block_home_directory=True,
        expand_home_directory=False,
        allow_absolute_paths=False,
    )
)


@function_tool
async def shell_tool(command: str, cwd: str = None, timeout: int = 60) -> str:
    """Execute shell commands in a controlled environment.
    
    IMPORTANT: For Python code execution, use python_sandbox_tool instead of this tool.
    Do NOT use shell commands like 'python script.py' - use the python_sandbox_tool instead.
    
    SECURITY RESTRICTIONS (all enforced):
    - Only commands within ~/.diona/ directory are allowed
    - Absolute paths are blocked (e.g., C:\, /etc/)
    - Path traversal is blocked (e.g., ../, ..\\)
    - Home directory (~) is blocked
    - cd/pushd commands are blocked (any directory change)
    - Pipe commands are blocked (|)
    - Command substitution is blocked (`...`, $(...))
    - Environment variables are blocked (%VAR%, $VAR)
    - Script interpreters are blocked (bash, sh, powershell, python, perl, ruby, node, etc.)
    - Dangerous commands are blocked (del, rm, format, diskpart, fdisk, etc.)
    
    AI USAGE GUIDELINES:
    - For Python code: Use python_sandbox_tool instead
    - For shell commands: Use this tool, but prefer python_sandbox_tool for Python code
    - DO NOT attempt to access files outside ~/.diona/
    - DO NOT use absolute paths (C:\, /etc/, /usr/)
    - DO NOT use path traversal (../, ..\\)
    - DO NOT use ~ to access home directory
    - DO NOT use cd, pushd, or any directory change commands
    - DO NOT use pipe (|) to chain commands
    - DO NOT use command substitution (`...`, $(...))
    - DO NOT use environment variables (%VAR%, $VAR)
    - DO NOT use script interpreters (bash, python, perl, ruby, node, powershell, etc.)
    - DO NOT modify or delete files unless explicitly requested
    - DO NOT run dangerous commands (rm, del, format, diskpart, fdisk, etc.)
    - Use ONLY simple read-only commands within ~/.diona/ directory
    - Allowed examples: dir, type filename, echo text, findstr pattern
    
    Args:
        command: The shell command to execute (read-only simple commands only)
        cwd: Working directory (optional, defaults to ~/.diona/)
        timeout: Command timeout in seconds (default: 60)
    
    Returns:
        Command output (stdout and stderr combined) or error message
    """
    effective_cwd = cwd or _diona_dir
    
    if not effective_cwd.startswith(_diona_dir):
        effective_cwd = _diona_dir
    
    try:
        returncode, stdout, stderr = _shell_commander.execute(
            command=command,
            cwd=effective_cwd,
            timeout=timeout
        )
        
        output = stdout
        if stderr:
            if output:
                output += "\n\nStderr:\n" + stderr
            else:
                output = "Stderr:\n" + stderr
        
        if not output:
            output = f"(Command executed successfully, no output. Return code: {returncode})"
        
        return output
        
    except ValueError as e:
        return f"Error: {str(e)}"
    except Exception as e:
        return f"Error executing command: {str(e)}"
