"""Run command tool - Execute shell commands."""

from __future__ import annotations

import subprocess
from typing import Any

from agenai.agent.tools.base import Tool, ToolResult


class RunCommandTool(Tool):
    """Tool for executing shell commands."""

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

    @property
    def description(self) -> str:
        return "Execute a shell command and return its output."

    @property
    def parameters(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "The shell command to execute",
                },
                "cwd": {
                    "type": "string",
                    "description": "Working directory for the command (optional)",
                },
                "timeout": {
                    "type": "integer",
                    "description": "Timeout in seconds (default: 60)",
                    "default": 60,
                },
            },
            "required": ["command"],
        }

    def execute(
        self,
        command: str,
        cwd: str | None = None,
        timeout: int = 60,
    ) -> ToolResult:
        """Execute a shell command."""
        try:
            result = subprocess.run(
                command,
                shell=True,
                capture_output=True,
                text=True,
                cwd=cwd,
                timeout=timeout,
            )

            output_parts = []

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

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

            if result.returncode != 0:
                output_parts.append(f"exit code: {result.returncode}")

            output = "\n".join(output_parts) if output_parts else "(no output)"

            if result.returncode == 0:
                return ToolResult.ok(output)
            else:
                return ToolResult.fail(output)

        except subprocess.TimeoutExpired:
            return ToolResult.fail(f"Command timed out after {timeout} seconds")
        except Exception as e:
            return ToolResult.fail(f"Error executing command: {e}")
