"""DS instance profile management tools."""

from __future__ import annotations

from typing import Any

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


@mcp.tool()
async def ds_instance_list() -> dict[str, Any]:
    """List available DS instances (built-in + custom).

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

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

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

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

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


@mcp.tool()
async def ds_instance_add(
    name: str,
    ds_url: str,
    keycloak_url: str,
    keycloak_realm: str,
    keycloak_client_id: str = "mcp-eregistrations-bpa",
) -> dict[str, Any]:
    """Register a custom DS instance profile.

    Args:
        name: Instance name (e.g., "staging").
        ds_url: DS base URL (e.g., https://staging.eregistrations.org).
        keycloak_url: Keycloak URL.
        keycloak_realm: Keycloak realm code.
        keycloak_client_id: OIDC client ID (default: mcp-eregistrations-bpa).

    Returns:
        dict with added (bool), name.
    """
    profiles = common_cfg.load_profiles("ds")
    profiles[name] = {
        "ds_url": ds_url.rstrip("/"),
        "keycloak_url": keycloak_url.rstrip("/"),
        "keycloak_realm": keycloak_realm,
        "keycloak_client_id": keycloak_client_id,
    }
    common_cfg.save_profiles("ds", profiles)

    return {"added": True, "name": name}
