"""Terminal tool for PentestAgent."""

from typing import TYPE_CHECKING

from ..registry import ToolSchema, register_tool

if TYPE_CHECKING:
    from ...runtime import Runtime


@register_tool(
    name="terminal",
    description="Execute shell commands.",
    schema=ToolSchema(
        properties={
            "command": {
                "type": "string",
                "description": "The shell command to execute",
            },
            "timeout": {
                "type": "integer",
                "description": "Timeout in seconds (default: 300)",
                "default": 300,
            },
            "working_dir": {
                "type": "string",
                "description": "Working directory for the command (optional)",
            },
        },
        required=["command"],
    ),
    category="execution",
)
async def terminal(arguments: dict, runtime: "Runtime") -> str:
    """
    Execute a terminal command in the sandbox.

    Args:
        arguments: Dictionary with 'command', optional 'timeout' and 'working_dir'
        runtime: The runtime environment

    Returns:
        Formatted output string with command results
    """
    command = arguments["command"]
    timeout = arguments.get("timeout", 300)
    working_dir = arguments.get("working_dir")

    # Build the full command with working directory if specified
    if working_dir:
        full_command = f"cd {working_dir} && {command}"
    else:
        full_command = command

    result = await runtime.execute_command(full_command, timeout=timeout)

    # Format the output
    output_parts = [f"Command: {command}"]

    if working_dir:
        output_parts.append(f"Working Directory: {working_dir}")

    output_parts.append(f"Exit Code: {result.exit_code}")

    if result.stdout:
        output_parts.append(f"\n--- stdout ---\n{result.stdout}")

    if result.stderr:
        output_parts.append(f"\n--- stderr ---\n{result.stderr}")

    if not result.stdout and not result.stderr:
        output_parts.append("\n(No output)")

    return "\n".join(output_parts)
