# /// script
# requires-python = ">=3.11"
# dependencies = ["mcp>=1.26,<2", "httpx>=0.27,<1"]
# ///
"""Read-only discovery of a specified opensource-server Manager and its MCP tools."""
import argparse
import asyncio
from datetime import timedelta
import json
import os
from pathlib import Path
from urllib.parse import urlsplit

import httpx
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client


def credentials(args, origin):
    if args.token_env:
        token = os.environ.get(args.token_env)
        if not token:
            raise ValueError(f"Environment variable {args.token_env} is unset")
        return token
    if args.cli_login:
        path = Path.home() / ".mieweb/os.json"
        if path.is_file():
            entry = json.loads(path.read_text()).get("instances", {}).get(origin, {})
            if entry.get("token"):
                return entry["token"]
        raise ValueError("No saved CLI login for this exact Manager origin")
    return None


async def check(args):
    url = urlsplit(args.manager)
    if (url.scheme != "https" or not url.hostname or url.username is not None
            or url.password is not None or url.path not in ("", "/") or url.query or url.fragment):
        raise ValueError("Supply a verified HTTPS Manager origin without a path or credentials")
    origin = f"https://{url.netloc}"
    async with httpx.AsyncClient(timeout=15, follow_redirects=False) as client:
        health = await client.get(origin + "/api/v1/health")
        health.raise_for_status()
        if "application/json" not in health.headers.get("Content-Type", "") or not health.json().get("data", {}).get("status"):
            raise ValueError("Expected Manager health JSON. Check the Manager link on the cluster homepage.")
        print(f"Manager {origin} | health {health.json()['data']['status']}", flush=True)

        schema_response = await client.get(origin + "/api/openapi.json")
        schema_response.raise_for_status()
        if "application/json" not in schema_response.headers.get("Content-Type", ""):
            raise ValueError("Expected a JSON OpenAPI document on the Manager origin")
        schema = schema_response.json()
        operations = schema.get("paths", {})
        if (operations.get("/session", {}).get("get", {}).get("operationId") != "get_session"
                or operations.get("/sites", {}).get("get", {}).get("operationId") != "list_sites"
                or not any(urlsplit(item.get("url", "")).path.rstrip("/") == "/api/v1"
                           for item in schema.get("servers", []))):
            raise ValueError("Unrecognized Manager API schema. Check this instance's API documentation.")
        token = credentials(args, origin)
        if token:
            client.headers["Authorization"] = f"Bearer {token}"
        async with streamable_http_client(origin + "/mcp", http_client=client) as (reader, writer, _):
            async with ClientSession(reader, writer, read_timeout_seconds=timedelta(seconds=20)) as session:
                info = await session.initialize()
                names = set()
                cursor = None
                while True:
                    page = await session.list_tools(cursor=cursor)
                    names.update(tool.name for tool in page.tools)
                    cursor = page.nextCursor
                    if not cursor:
                        break
                relevant = names.intersection({"get_session", "list_sites", "get_new_container_form",
                                                "create_container", "update_container", "get_container", "get_job"})
                print(f"MCP {info.serverInfo.name} | {len(names)} tools | {', '.join(sorted(relevant))}")
                if "get_session" not in names:
                    raise ValueError("The MCP tool catalog does not advertise get_session")
                identity = await session.call_tool("get_session", {})
                if identity.isError:
                    if token:
                        raise ValueError("The supplied credential did not establish an MCP session")
                    print("Anonymous MCP discovery succeeded. No authenticated identity was established.")
                    return
                # Confirm the same identity at the API rather than echo arbitrary tool output.
                response = await client.get(origin + "/api/v1/session")
                response.raise_for_status()
                user = response.json()["data"]["user"]
                if not user:
                    raise ValueError("The Manager did not return an authenticated account")
                print(f"Authenticated account: {user}")
                sites = await client.get(origin + "/api/v1/sites")
                sites.raise_for_status()
                for site in sites.json()["data"]:
                    print(f"Site {site['id']}: {site['name']}")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("manager", help="Exact HTTPS origin of the intended Manager")
    auth = parser.add_mutually_exclusive_group()
    auth.add_argument("--token-env", metavar="NAME", help="Read this Manager's bearer key from NAME")
    auth.add_argument("--cli-login", action="store_true", help="Use the CLI login saved for this exact origin")
    try:
        asyncio.run(check(parser.parse_args()))
    except Exception as exc:
        # Async context managers can wrap the original exception in exception groups.
        while isinstance(exc, BaseExceptionGroup):
            exc = exc.exceptions[0]
        raise SystemExit(f"Manager check failed: {exc}") from None


if __name__ == "__main__":
    main()
