"""User lookup tools."""

from __future__ import annotations

from typing import Any

from mcp.types import ToolAnnotations

from mcp_eregistrations_ds.ds_client import DSClient, DSClientError, translate_error
from mcp_eregistrations_ds.server import mcp


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def user_search(
    query: str,
    instance: str | None = None,
) -> dict[str, Any]:
    """Search users by name or email (trigram similarity).

    Args:
        query: Search term (name, email, or partial match).
        instance: Instance profile name.

    Returns:
        dict with users (list of id, auth_system_id, full_name, email), count.
    """
    try:
        async with DSClient.for_instance(instance) as client:
            data = await client.get(f"/backend/user-autocomplete/{query}")
    except DSClientError as e:
        raise translate_error(e, resource_type="user") from e

    users = data if isinstance(data, list) else []
    return {
        "users": users,
        "count": len(users),
    }
