# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-scope-widening-drift-when-a-peer-s-verifiable-credential-attests-a-capability-set-larger-than-the-aaif-scope-it-was-issu.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-scope-widening-drift-when-a-peer-s-verifiable-credential-attests-a-capability-set-larger-than-the-aaif-scope-it-was-issu.warrant.json
# Markdown SHA-256:   b36466236541152649c5d429123666bf34363785310f047a9f6a349ff0407933
# Code AST SHA-256:   04afed1228bb3ff890767c3255efea0d214800ea5f4030ce14517a6ce85aea7a
# Verified Classes:   ScopeWideningDriftError, Credential
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ScopeWideningDriftError(RuntimeError):
    """Raised when a peer's advertised capabilities exceed its AAIF scope."""


@dataclass(frozen=True)
class Credential:
    peer_id: str
    capabilities: frozenset[str]
    scope_uri: str
    scope_hash: str
    credential_hash: str
    valid: bool


def expand_scope(scope_uri: str, expected_hash: str) -> frozenset[str]:
    # Out-of-band, content-addressed policy resolution. Fails closed.
    policy = _fetch_policy(scope_uri)  # raises if unreachable
    actual = hashlib.sha256(policy.encode()).hexdigest()
    if actual != expected_hash:
        raise ScopeWideningDriftError(
            f"scope {scope_uri} hash mismatch: {actual} != {expected_hash}"
        )
    return frozenset(policy.split())


def admit(cred: Credential, requested: str, scope_cache: dict) -> bool:
    if not cred.valid:
        return False

    key = (cred.scope_uri, cred.scope_hash)
    if key not in scope_cache:
        scope_cache[key] = expand_scope(cred.scope_uri, cred.scope_hash)
    authorized = scope_cache[key]

    # Hard invariant: advertised capabilities must not exceed delegated scope.
    if not cred.capabilities <= authorized:
        widened = cred.capabilities - authorized
        raise ScopeWideningDriftError(
            f"peer {cred.peer_id} advertises {sorted(widened)} "
            f"outside scope {cred.scope_uri}; quarantining issuer"
        )

    # Admission is the intersection, never the union.
    return requested in cred.capabilities and requested in authorized


def _fetch_policy(scope_uri: str) -> str:
    raise NotImplementedError
