"""GDB system tools — status, tag listing, and instance listing (MVP spike)."""

from __future__ import annotations

from typing import Any

from mcp.types import ToolAnnotations

from mcp_eregistrations_gdb.gdb_client import GDBClient, GDBClientError, translate_error
from mcp_eregistrations_gdb.server import mcp


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def gdb_status(instance: str | None = None) -> dict[str, Any]:
    """Get GDB server health and version.

    Args:
        instance: Instance name (default: auto-select).

    Returns:
        dict with version, status.
    """
    try:
        async with GDBClient.for_instance(instance) as client:
            result: dict[str, Any] = await client.get("/api/v1/status")
            return result
    except GDBClientError as e:
        raise translate_error(e, resource_type="status") from e


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def gdb_tag_list(instance: str | None = None) -> dict[str, Any]:
    """List all GDB tags.

    Args:
        instance: Instance name (default: auto-select).

    Returns:
        dict with count, tags.
    """
    try:
        async with GDBClient.for_instance(instance) as client:
            data = await client.get("/api/v1/tags")
            if isinstance(data, list):
                return {"count": len(data), "tags": data}
            return {
                "count": data.get("count", 0),
                "tags": data.get("results", []),
            }
    except GDBClientError as e:
        raise translate_error(e, resource_type="tag") from e


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def gdb_instance_list() -> dict[str, Any]:
    """List eRegistrations instances with GDB URLs configured.

    Returns:
        dict with count, instances (name, display_name, gdb_url).
    """
    from mcp_eregistrations_common.config import load_builtin_instances

    instances = load_builtin_instances()
    gdb_instances = []
    for inst in instances:
        gdb_url = inst.get("gdb_url")
        if gdb_url:
            gdb_instances.append(
                {
                    "name": inst["name"],
                    "display_name": inst.get("display_name", inst["name"]),
                    "gdb_url": gdb_url,
                }
            )
    return {"count": len(gdb_instances), "instances": gdb_instances}
