# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-the-mcp-oauth-2-1-resource-indicator-after-dynamic-client-registration-and-why-the-token-audience-silently-desynchron.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-the-mcp-oauth-2-1-resource-indicator-after-dynamic-client-registration-and-why-the-token-audience-silently-desynchron.warrant.json
# Markdown SHA-256:   e855998ac36f85ae8f07534565c005e7a69ba37023c309b329f9a152e4b37508
# Code AST SHA-256:   07d60ae88c876842a157ca0aa652129c0a3108bb8d237a54c0dea0410e38186a
# Verified Classes:   AudienceBindingError, Token, ResolvedEndpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import urllib.parse
from dataclasses import dataclass


class AudienceBindingError(RuntimeError):
    """Raised when the token audience does not cover the resolved MCP endpoint origin."""


@dataclass(frozen=True)
class Token:
    access_token: str
    audience: str  # the `aud` claim, i.e. the resource indicator the AS bound


@dataclass(frozen=True)
class ResolvedEndpoint:
    url: str

    @property
    def origin(self) -> str:
        p = urllib.parse.urlsplit(self.url)
        return f"{p.scheme}://{p.netloc}"


def _audience_covers(aud: str, origin: str, match_mode: str) -> bool:
    if match_mode == "exact":
        return aud == origin
    if match_mode == "origin":
        return urllib.parse.urlsplit(aud).netloc == urllib.parse.urlsplit(origin).netloc
    if match_mode == "prefix":
        return origin.startswith(aud) or aud.startswith(origin)
    raise ValueError(f"unknown audience match mode: {match_mode}")


def assert_binding(token: Token, endpoint: ResolvedEndpoint, match_mode: str = "origin") -> None:
    """
    Call-path invariant: the token's audience must cover the resolved endpoint origin.
    Run on every token acquisition and on every 401 before any retry.
    """
    if not _audience_covers(token.audience, endpoint.origin, match_mode):
        raise AudienceBindingError(
            f"token aud={token.audience!r} does not cover endpoint origin={endpoint.origin!r} "
            f"(match_mode={match_mode}); refusing to send credential. "
            f"Re-resolve endpoint, recompute resource indicator, and re-run DCR."
        )


def acquire_token_for_endpoint(
    discovery_resource: str,
    endpoint: ResolvedEndpoint,
    mint,
    match_mode: str = "origin",
) -> Token:
    # The resource indicator must be derived from the CURRENT discovery result,
    # never from persisted client config, or DCR re-runs inherit a stale binding.
    if urllib.parse.urlsplit(discovery_resource).netloc != urllib.parse.urlsplit(endpoint.origin).netloc:
        raise AudienceBindingError(
            f"discovery resource {discovery_resource!r} and endpoint {endpoint.origin!r} "
            f"disagree on host; DCR would register an unusable audience."
        )
    token = mint(resource=discovery_resource)
    assert_binding(token, endpoint, match_mode)
    return token
