"""Python sandbox tool for OpenAI Agent"""

import os
from agents import function_tool
from diona.project.sandbox import Sandbox, SandboxConfig


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

_sandbox = Sandbox(
    SandboxConfig(
        timeout=30.0,
        allow_network=False,
    )
)


@function_tool
async def python_sandbox_tool(code: str, timeout: int = 30) -> str:
    """Execute Python code in a secure sandbox environment.
    
    IMPORTANT: All Python code execution MUST use this tool. Do not use shell commands
    like 'python script.py' - instead, paste the Python code directly into this tool.
    
    SECURITY RESTRICTIONS:
    - No file deletion
    - No network access
    - No subprocess execution
    - No access to dangerous modules (os, subprocess, socket, etc.)
    - Limited os module (read-only: listdir, path, environ, getcwd, etc.)
    
    AI USAGE GUIDELINES:
    - ALL Python code must be executed using this tool, not shell commands
    - For Python scripts, paste the code content directly into the 'code' parameter
    - DO NOT use 'python file.py' in shell - use this tool instead
    - DO NOT attempt to delete files
    - DO NOT try to import dangerous modules (os, subprocess, socket, etc.)
    - DO NOT perform network operations
    - Use this tool for Python code execution and data processing
    - Results are returned as strings (stdout/stderr)
    - This is a READ-ONLY(In Fact You can modify files, But Don't allow delete them) sandbox
    
    Args:
        code: The Python code to execute directly
        timeout: Execution timeout in seconds (default: 30)
    
    Returns:
        Execution result (stdout and stderr combined) or error message
    """
    try:
        result = _sandbox.execute_with_timeout(code)
        
        output = ""
        
        if result.stdout:
            output = result.stdout
        
        if result.stderr:
            if output:
                output += "\n\nStderr:\n" + result.stderr
            else:
                output = "Stderr:\n" + result.stderr
        
        if result.error:
            if output:
                output += "\n\nError:\n" + result.error
            else:
                output = "Error:\n" + result.error
        
        if not output:
            output = "(Code executed successfully, no output)"
        
        if result.timed_out:
            output += "\n\nWarning: Execution timed out"
        
        return output
        
    except Exception as e:
        return f"Error executing code: {str(e)}"
