# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-bind-an-mcp-oauth-2-1-access-token-after-a-tool-server-s-resource-indicator-rotates-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-bind-an-mcp-oauth-2-1-access-token-after-a-tool-server-s-resource-indicator-rotates-mid-session.warrant.json
# Markdown SHA-256:   bc54f6ec050b6897f97ac3adb8dcee55232a3d6fdbee616ebcab1edf97ea093f
# Code AST SHA-256:   3beda8afc64f63d79bf080df2e89423b7b506740e3850b20ccdb1901f8ab44e9
# Verified Classes:   ResourceBindingMismatch, Token
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class ResourceBindingMismatch(RuntimeError):
    """Raised when a token's resource claim diverges from the server's advertised metadata."""
    pass


@dataclass
class Token:
    access_token: str
    resource: str          # the RFC 8707 resource indicator baked into this token
    expires_at: float


def re_bind_token(
    token: Token,
    protected_resource_metadata: dict,
    mint_fn,               # mint_fn(resource: str) -> Token, calls AS with explicit resource param
    now: float | None = None,
) -> Token:
    now = time.time() if now is None else now
    advertised = protected_resource_metadata.get("resource")
    if not advertised:
        raise ResourceBindingMismatch(
            "protected-resource metadata carries no 'resource'; cannot re-derive binding"
        )

    if token.resource == advertised and token.expires_at > now:
        # Token is already correctly bound and live: a 401 here is NOT a binding fault.
        raise ResourceBindingMismatch(
            f"token resource {token.resource!r} already matches metadata {advertised!r} "
            "and token is unexpired; 401 is not a binding failure — do not refresh"
        )

    # Re-derive resource from metadata, NOT from the stale token or cached DCR response.
    fresh = mint_fn(advertised)
    if fresh.resource != advertised:
        # Guard against AS honoring a stale default: a 200 from the token endpoint
        # is not resolution unless the minted claim matches the advertised indicator.
        raise ResourceBindingMismatch(
            f"re-minted token bound to {fresh.resource!r}, expected {advertised!r}; "
            "authorization server ignored explicit resource parameter"
        )
    return fresh
