"""Python tools configuration."""

from __future__ import annotations

import subprocess
from typing import TYPE_CHECKING, Any

from mindroom.logging_config import get_logger
from mindroom.tool_system.declarations import (
    ConfigField,
    SetupType,
    ToolCategory,
    ToolExecutionTarget,
    ToolStatus,
)
from mindroom.tool_system.dependencies import install_command_for_current_python
from mindroom.tool_system.registration import register_tool_with_metadata

if TYPE_CHECKING:
    import logging
    from collections.abc import Callable

    from agno.tools.python import PythonTools

logger = get_logger(__name__)


def _install_package_with_current_python(package_name: str) -> None:
    """Install one package into the current interpreter environment."""
    subprocess.check_call([*install_command_for_current_python(), package_name])


def _install_package_with_status(
    package_name: str,
    *,
    warn: Callable[[], None],
    log_debug: Callable[[str], None],
    agno_logger: logging.Logger,
) -> str:
    """Install a package and format the tool response."""
    try:
        warn()
        log_debug("Installing package " + package_name)
        logger.debug("python_package_install_started", package_name=package_name)
        _install_package_with_current_python(package_name)
    except Exception as exc:
        error_message = f"Error installing package {package_name}"
        agno_logger.exception(error_message)
        logger.exception("python_package_install_failed", package_name=package_name)
        return f"Error installing package {package_name}: {exc}"
    return f"successfully installed package {package_name}"


def _python_tools_runtime() -> tuple[Any, Any, Any, Any]:
    """Load Agno's Python tool runtime pieces lazily."""
    from agno.tools.python import PythonTools, log_debug, warn
    from agno.tools.python import logger as agno_logger

    return PythonTools, warn, log_debug, agno_logger


@register_tool_with_metadata(
    name="python",
    display_name="Python Tools",
    description="Execute Python code, manage files, and install packages",
    category=ToolCategory.DEVELOPMENT,
    status=ToolStatus.AVAILABLE,
    setup_type=SetupType.NONE,
    default_execution_target=ToolExecutionTarget.WORKER,
    consumes_workspace_paths=True,
    icon="SiPython",
    icon_color="text-blue-500",
    config_fields=[
        ConfigField(
            name="base_dir",
            label="Base Dir",
            type="text",
            required=False,
            default=None,
            authored_override=False,
        ),
        ConfigField(
            name="safe_globals",
            label="Safe Globals",
            type="text",
            required=False,
            default=None,
        ),
        ConfigField(
            name="safe_locals",
            label="Safe Locals",
            type="text",
            required=False,
            default=None,
        ),
        ConfigField(
            name="restrict_to_base_dir",
            label="Restrict To Base Dir",
            type="boolean",
            required=False,
            default=True,
        ),
    ],
    dependencies=["agno"],
    docs_url="https://docs.agno.com/tools/toolkits/local/python",
    function_names=(
        "list_files",
        "pip_install_package",
        "read_file",
        "run_python_code",
        "run_python_file_return_variable",
        "save_to_file_and_run",
        "uv_pip_install_package",
    ),
)
def python_tools() -> type[PythonTools]:
    """Return Python tools for code execution and file management."""
    python_tools_class, warn, log_debug, agno_logger = _python_tools_runtime()

    class MindRoomPythonTools(python_tools_class):
        """MindRoom wrapper around Agno's Python tool implementation."""

        def pip_install_package(self, package_name: str) -> str:
            """Install a package into the current interpreter environment."""
            return _install_package_with_status(
                package_name,
                warn=warn,
                log_debug=log_debug,
                agno_logger=agno_logger,
            )

        def uv_pip_install_package(self, package_name: str) -> str:
            """Backward-compatible alias for the shared installer path."""
            return _install_package_with_status(
                package_name,
                warn=warn,
                log_debug=log_debug,
                agno_logger=agno_logger,
            )

    return MindRoomPythonTools
