# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-trust-attestation-from-a-peer-whose-policy-exchange-succeeded.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-trust-attestation-from-a-peer-whose-policy-exchange-succeeded.warrant.json
# Markdown SHA-256:   de32c804cdabb1edf741b94bbad0f7cb59dd09a6936336ce56bea1e213709794
# Code AST SHA-256:   db592ad411f442214985ae2757e15a905f3e34203d3d41d71991e1555907a6cf
# Verified Classes:   FederatedAttestationRefused
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class FederatedAttestationRefused(RuntimeError):
    """Raised when a peer's policy exchange succeeded but the delegated
    capability is not applicable at this local instance."""
    pass


RESTRICTED_NAMESPACES = {"dataset/sensitive", "dataset/pii"}
LOCAL_INBOUND_MAX_DEPTH = {"external": 1, "partner": 2}


def assert_applicable(bundle: dict, call: dict, local_schema_hash: str) -> None:
    scope = call["scope"]
    peer_class = bundle["trust_class"]

    # Wildcard into a locally-restricted namespace is unprovable; refuse.
    if scope.endswith("/*"):
        prefix = scope[:-2]
        for ns in RESTRICTED_NAMESPACES:
            if ns.startswith(prefix):
                raise FederatedAttestationRefused(
                    f"wildcard {scope!r} resolves into restricted namespace {ns!r}"
                )

    # Depth must be re-checked locally, not trusted from the peer's self-report.
    declared = bundle["delegation_depth"]
    local_max = LOCAL_INBOUND_MAX_DEPTH.get(peer_class, 0)
    if declared > local_max:
        raise FederatedAttestationRefused(
            f"declared depth {declared} exceeds local inbound max {local_max} "
            f"for trust class {peer_class!r}"
        )

    # Stale schema invalidates the grant rather than mutating its meaning.
    if bundle.get("schema_hash") != local_schema_hash:
        raise FederatedAttestationRefused(
            "grant pinned to schema hash "
            f"{bundle.get('schema_hash')!r}, local is {local_schema_hash!r}"
        )

    # Grant-only bundles cannot prove applicability into restricted space.
    if not bundle.get("reservations") and scope in RESTRICTED_NAMESPACES:
        raise FederatedAttestationRefused(
            f"grant-only bundle cannot authorize restricted scope {scope!r}"
        )
