# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-trust-root-substitution-during-cross-org-verifiable-credential-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-trust-root-substitution-during-cross-org-verifiable-credential-delegation.warrant.json
# Markdown SHA-256:   bc65640f596719977f268bfdd5365a3d7b117a38075af5ce71260a68ee6ccdae
# Code AST SHA-256:   5663dd1a4ff7ba7f7c295bda2e8b780c5148ad5fa018a4f0c6550331c58efbcb
# Verified Classes:   TrustRootSubstitutionError, DelegationVC
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class TrustRootSubstitutionError(RuntimeError):
    """Raised when the resolved trust root diverges from the pinned anchor."""


@dataclass(frozen=True)
class DelegationVC:
    subject: str
    issuer: str
    pinned_trust_anchor_hash: str   # inside the signed payload
    delegation_chain: tuple[str, ...]
    max_chain_len: int


def verify_delegation(
    vc: DelegationVC,
    resolved_did_document: bytes,
    resolver_cache_hit: bool,
) -> None:
    resolved_hash = hashlib.sha256(resolved_did_document).hexdigest()

    # Invariant 1: root equality is a hard gate, never a warning.
    if resolved_hash != vc.pinned_trust_anchor_hash:
        raise TrustRootSubstitutionError(
            f"resolved root {resolved_hash[:12]} != pinned "
            f"{vc.pinned_trust_anchor_hash[:12]} for subject {vc.subject}"
        )

    # Invariant 2: a cache miss must fail closed, not trigger silent re-resolution.
    if not resolver_cache_hit:
        raise TrustRootSubstitutionError(
            "cache miss under active pin: re-resolution would allow substitution; "
            "escalate to delegator for fresh pin"
        )

    # Invariant 3: chain cannot be extended past the pinned bound.
    if len(vc.delegation_chain) > vc.max_chain_len:
        raise TrustRootSubstitutionError(
            f"delegation chain length {len(vc.delegation_chain)} exceeds "
            f"pinned max {vc.max_chain_len}"
        )
