"""Tool registry endpoints: list, summary, get."""

from typing import Any

from fastapi import APIRouter, HTTPException, Query

from proxym.dashboard._environments_api import get_environment_registry, get_tool_environment_snapshot
from proxym.tools import ToolCategory, ToolRegistry

router = APIRouter(tags=["tools"])


def _tool_payload(tool, registry) -> dict[str, Any]:
    payload = tool.summary()
    environment = registry.get_tool_environment(tool.name)
    payload["environment_id"] = environment.id if environment else ""
    payload["environment"] = get_tool_environment_snapshot(tool.name)
    return payload


@router.get("/")
async def list_tools(
    category: str | None = Query(None, description="Filter by category: ide, agent_cli, browser"),
    available_only: bool = Query(False, description="Only show tools with an available host or docker-backed instance"),
) -> dict[str, Any]:
    """List all registered tools."""
    reg = ToolRegistry.get()
    env_registry = get_environment_registry()
    cat = ToolCategory(category) if category else None
    tools = reg.list_tools(category=cat, available_only=available_only)
    return {"tools": [_tool_payload(t, env_registry) for t in tools], "count": len(tools)}


@router.get("/summary")
async def tools_summary() -> dict[str, Any]:
    """Summary of tool availability."""
    reg = ToolRegistry.get()
    env_registry = get_environment_registry()
    tools = reg.list_tools()
    return {
        "total": len(tools),
        "available": len([tool for tool in tools if tool.is_available]),
        "tools": [_tool_payload(tool, env_registry) for tool in tools],
        "environments": env_registry.summary(),
    }


@router.put("/{tool_name}")
async def update_tool(tool_name: str, body: dict[str, Any] | None = None) -> dict[str, Any]:
    """Update a tool's mutable fields (default_model, default_instance, description, force_available)."""
    if not body:
        raise HTTPException(400, "Request body required")
    reg = ToolRegistry.get()
    tool = reg.update_tool(tool_name, body)
    if not tool:
        raise HTTPException(404, f"Tool '{tool_name}' not found")
    env_registry = get_environment_registry()
    return _tool_payload(tool, env_registry)


# NOTE: Dynamic route MUST be registered last (after queue_router etc.).
@router.get("/{tool_name}")
async def get_tool(tool_name: str) -> dict[str, Any]:
    """Get details for a specific tool."""
    tool = ToolRegistry.get().get_tool(tool_name)
    if not tool:
        raise HTTPException(404, f"Tool '{tool_name}' not found")
    env_registry = get_environment_registry()
    return _tool_payload(tool, env_registry)
