# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-delegated-capability-token-was-minted-against-a-stale-agent-credential-snapshot.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-delegated-capability-token-was-minted-against-a-stale-agent-credential-snapshot.warrant.json
# Markdown SHA-256:   b9c396ad369d14d7e0c5265e9ed43b4c172904b6f572402e669038d76f9dc6f6
# Code AST SHA-256:   42df9d53c0ce00d4c2da1ab9cf65a973beab08e2b9aa76221501f91610466b7c
# Verified Classes:   StaleCredentialSnapshotError, VerifiableCredential, DelegatedCapabilityToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class StaleCredentialSnapshotError(RuntimeError):
    """Raised when a DCT's embedded credential snapshot no longer matches
    the delegate's current verifiable credential head at admission time."""


@dataclass(frozen=True)
class VerifiableCredential:
    subject_did: str
    version: int
    can_invoke: frozenset[str]
    issued_at: float


@dataclass(frozen=True)
class DelegatedCapabilityToken:
    subject_did: str
    scope: frozenset[str]
    mint_time: float
    exp: float
    credential_snapshot_hash: str


def _vc_hash(vc: VerifiableCredential) -> str:
    basis = f"{vc.subject_did}|{vc.version}|{sorted(vc.can_invoke)}|{vc.issued_at}"
    return hashlib.sha256(basis.encode()).hexdigest()


def admit_dct(
    dct: DelegatedCapabilityToken,
    resolve_current_vc,          # callable: did -> VerifiableCredential (live, no cache)
    credential_freshness_budget: float,
    now: float | None = None,
) -> frozenset[str]:
    now = time.time() if now is None else now

    if now >= dct.exp:
        raise StaleCredentialSnapshotError(
            f"DCT for {dct.subject_did} expired at {dct.exp} (now={now})"
        )

    # The load-bearing check: re-anchor the snapshot to the delegate's
    # CURRENT credential head, resolved live. Cache is bypassed deliberately.
    current = resolve_current_vc(dct.subject_did)
    current_hash = _vc_hash(current)

    if current_hash != dct.credential_snapshot_hash:
        raise StaleCredentialSnapshotError(
            f"DCT for {dct.subject_did} minted against stale credential snapshot "
            f"{dct.credential_snapshot_hash[:12]}...; current head is "
            f"{current_hash[:12]}... (vc v{current.version}). "
            f"Refusing admission; re-mint required."
        )

    # Bound the effective authorization horizon by credential freshness,
    # not by token expiry alone.
    if now > dct.mint_time + credential_freshness_budget:
        raise StaleCredentialSnapshotError(
            f"DCT for {dct.subject_did} used at {now} exceeds credential "
            f"freshness budget ({credential_freshness_budget}s from mint "
            f"{dct.mint_time}); snapshot may have drifted since resolution."
        )

    # Scope must be a subset of the *current* credential's asserted capabilities.
    effective = dct.scope & current.can_invoke
    if effective != dct.scope:
        raise StaleCredentialSnapshotError(
            f"DCT scope {sorted(dct.scope)} not fully supported by current "
            f"credential {sorted(current.can_invoke)} for {dct.subject_did}"
        )

    return effective
