# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-scoped-authority-when-an-mcp-authorization-server-delegates-through-a-resource-indicator-it-never-validated.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-scoped-authority-when-an-mcp-authorization-server-delegates-through-a-resource-indicator-it-never-validated.warrant.json
# Markdown SHA-256:   7d5a284d0bf2d7697837c4c755e5ab817572043c11d97c6899b7727b05983d95
# Code AST SHA-256:   8a34ebea12c029f191430e8c34458d6eff35a059fad768a69c2d1587185f8c58
# Verified Classes:   ResourceBindingViolation, DelegationContextMismatch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import re
from urllib.parse import urlsplit, urlunsplit


class ResourceBindingViolation(RuntimeError):
    """Raised when a token's resource indicator does not exactly bind to the tool endpoint."""


class DelegationContextMismatch(RuntimeError):
    """Raised when a cached token's delegation context differs from the current one."""


def _normalize_uri(uri: str) -> str:
    parts = urlsplit(uri)
    path = re.sub(r"/+", "/", parts.path).rstrip("/") or "/"
    return urlunsplit((parts.scheme.lower(), parts.netloc.lower(), path, "", ""))


def validate_tool_binding(token: dict, tool_endpoint: str, current_ctx: dict) -> None:
    # 1. Resource indicator must be an exact normalized match to the tool endpoint.
    token_res = _normalize_uri(token.get("resource", ""))
    endpoint = _normalize_uri(tool_endpoint)
    if token_res != endpoint:
        raise ResourceBindingViolation(
            f"token resource {token_res!r} is not exactly bound to endpoint {endpoint!r}; "
            f"ancestor/wildcard resources are rejected"
        )

    # 2. Scope must name the specific tool, not a namespace wildcard.
    scopes = set(token.get("scope", "").split())
    tool_scope = f"tools:{endpoint.rsplit('/', 1)[-1]}"
    if tool_scope not in scopes or any(s.endswith(":*") for s in scopes):
        raise ResourceBindingViolation(
            f"scope set {sorted(scopes)!r} does not contain exact tool scope {tool_scope!r} "
            f"or contains a wildcard"
        )

    # 3. Token must have been issued for the current delegation context.
    for claim in ("sub", "client_id", "act"):
        if token.get(claim) != current_ctx.get(claim):
            raise DelegationContextMismatch(
                f"claim {claim!r}: token={token.get(claim)!r} ctx={current_ctx.get(claim)!r}"
            )


def get_or_issue_token(cache: dict, tool_endpoint: str, ctx: dict, as_client) -> dict:
    key = (
        _normalize_uri(tool_endpoint),
        ctx.get("sub"),
        ctx.get("client_id"),
        ctx.get("act"),
    )
    token = cache.get(key)
    if token is None:
        token = as_client.issue(resource=_normalize_uri(tool_endpoint), context=ctx)
        cache[key] = token
    validate_tool_binding(token, tool_endpoint, ctx)
    return token
