"""RFC 9727 API catalog (application/linkset+json).

The catalog is a machine-readable index of public APIs this publisher exposes.
Internal Cloud and admin surfaces are omitted on purpose.
"""

from __future__ import annotations

from dataclasses import dataclass

RFC9727_PROFILE = "https://www.rfc-editor.org/info/rfc9727"
LINKSET_MEDIA_TYPE = f'application/linkset+json; profile="{RFC9727_PROFILE}"'


@dataclass(frozen=True)
class PublishedApi:
    """One discoverable API surface (anchor path relative to the API origin)."""

    path: str
    title: str


# Only advertise operations with an equivalent public dashboard proxy.
# Expand this allowlist as the delegated agent API is implemented.
PUBLIC_OPERATION_PATHS = frozenset({"/api/public/register"})
AGENT_OPERATION_PATHS = frozenset(
    {
        "/api/agent-access/clients",
        "/api/agent-access/token",
        "/api/agent-access/revoke",
        "/api/agent-access/capabilities",
        "/api/agent-access/tools",
    }
)
PUBLISHED_APIS: tuple[PublishedApi, ...] = (PublishedApi("/api/public", "Public signup API"),)

OPENAPI_PATH = "/openapi.json"
DOCS_PATH = "/docs"
HEALTH_PATH = "/health"
CATALOG_PATH = "/.well-known/api-catalog"


def _abs(base_url: str, path: str) -> str:
    return f"{base_url.rstrip('/')}{path}"


def build_api_catalog(base_url: str, *, agent_enabled: bool = False) -> dict:
    """Return an RFC 9264 linkset representing this publisher's public APIs."""
    origin = base_url.rstrip("/")
    entries = []
    apis = PUBLISHED_APIS + (
        (PublishedApi("/api/agent-access", "Agent access API"),) if agent_enabled else ()
    )
    for api in apis:
        entries.append(
            {
                "anchor": _abs(origin, api.path),
                "service-desc": [
                    {
                        "href": _abs(origin, OPENAPI_PATH),
                        "type": "application/json",
                        "title": f"{api.title} OpenAPI description",
                    }
                ],
                "service-doc": [
                    {
                        "href": _abs(origin, DOCS_PATH),
                        "type": "text/html",
                        "title": f"{api.title} documentation",
                    }
                ],
                "status": [
                    {
                        "href": _abs(origin, HEALTH_PATH),
                        "type": "application/json",
                        "title": "API health",
                    }
                ],
            }
        )
    return {"linkset": entries}


def catalog_link_header(base_url: str) -> str:
    return f'<{_abs(base_url, CATALOG_PATH)}>; rel="api-catalog"'
