"""GDB database group tools — list, create, update, delete, move."""

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
from mcp_eregistrations_gdb.tools import _add_optional


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

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

    Returns:
        dict with count, groups (each with id, name, has_logo, color_hex).
    """
    try:
        async with GDBClient.for_instance(instance) as client:
            data = await client.get("/api/v1/database-groups")
            groups = [
                {
                    "id": g.get("id"),
                    "name": g.get("name"),
                    "has_logo": g.get("has_logo"),
                    "color_hex": g.get("color_hex"),
                }
                for g in data
            ]
            return {"count": len(groups), "groups": groups}
    except GDBClientError as e:
        raise translate_error(e, resource_type="group") from e


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=False))
async def gdb_group_create(
    name: str,
    color_hex: str | None = None,
    instance: str | None = None,
) -> dict[str, Any]:
    """Create a database group.

    Args:
        name: Group name (must be unique).
        color_hex: Hex color string (default: None).
        instance: Instance name (default: auto-select).

    Returns:
        dict with id, name, has_logo, color_hex.
    """
    try:
        async with GDBClient.for_instance(instance) as client:
            body: dict[str, Any] = {"name": name}
            _add_optional(body, "color_hex", color_hex)
            data = await client.post("/api/v1/database-group/modify", data=body)
            return {
                "id": data.get("id"),
                "name": data.get("name"),
                "has_logo": data.get("has_logo"),
                "color_hex": data.get("color_hex"),
            }
    except GDBClientError as e:
        raise translate_error(e, resource_type="group") from e


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=False))
async def gdb_group_update(
    group_id: int,
    name: str | None = None,
    color_hex: str | None = None,
    instance: str | None = None,
) -> dict[str, Any]:
    """Update a database group.

    Args:
        group_id: Integer ID of the group to update.
        name: New group name (default: unchanged).
        color_hex: Hex color string (default: None).
        instance: Instance name (default: auto-select).

    Returns:
        dict with id, name, has_logo, color_hex.
    """
    try:
        async with GDBClient.for_instance(instance) as client:
            body: dict[str, Any] = {"id": group_id}
            _add_optional(body, "name", name)
            _add_optional(body, "color_hex", color_hex)
            data = await client.post("/api/v1/database-group/modify", data=body)
            return {
                "id": data.get("id"),
                "name": data.get("name"),
                "has_logo": data.get("has_logo"),
                "color_hex": data.get("color_hex"),
            }
    except GDBClientError as e:
        raise translate_error(e, resource_type="group", resource_id=group_id) from e


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=False))
async def gdb_group_delete(
    group_id: int,
    instance: str | None = None,
) -> dict[str, Any]:
    """Delete a database group by ID.

    Args:
        group_id: Integer ID of the group to delete.
        instance: Instance name (default: auto-select).

    Returns:
        dict with deleted (bool), group_id.
    """
    try:
        async with GDBClient.for_instance(instance) as client:
            await client.delete(f"/api/v1/database-group/{group_id}/delete")
            return {"deleted": True, "group_id": group_id}
    except GDBClientError as e:
        raise translate_error(e, resource_type="group", resource_id=group_id) from e


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=False))
async def gdb_group_move(
    group_id: int,
    index: int,
    instance: str | None = None,
) -> dict[str, Any]:
    """Move a database group to a new position.

    Args:
        group_id: Integer ID of the group to move.
        index: Target position index (0-based).
        instance: Instance name (default: auto-select).

    Returns:
        dict with moved (bool), group_id, index.
    """
    try:
        async with GDBClient.for_instance(instance) as client:
            await client.post(
                f"/api/v1/database-group/{group_id}/move",
                data={"index": index},
            )
            return {"moved": True, "group_id": group_id, "index": index}
    except GDBClientError as e:
        raise translate_error(e, resource_type="group", resource_id=group_id) from e
