"""SmartLink instance profile management tools."""

from __future__ import annotations

from typing import Any

from mcp_eregistrations_common import config as common_cfg
from mcp_eregistrations_smartlink.server import mcp


@mcp.tool()
async def smartlink_instance_list() -> dict[str, Any]:
    """List eRegistrations instances with SmartLink configured.

    Only shows instances that have a smartlink_url and Keycloak auth
    (SmartLink requires JWT authentication).

    Returns:
        dict with total, instances (list of name, smartlink_url, source).
    """
    builtin = common_cfg.load_builtin_instances()
    custom = common_cfg.load_profiles()

    instances: list[dict[str, Any]] = []
    seen: set[str] = set()

    # Custom profiles override built-in
    for name, profile in custom.items():
        if profile.get("smartlink_url"):
            instances.append({"name": name, "source": "custom", **profile})
            seen.add(name)

    for inst in builtin:
        if inst["name"] not in seen and inst.get("smartlink_url"):
            instances.append({"source": "builtin", **inst})

    return {"total": len(instances), "instances": instances}
