# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-did-anchored-agent-passport-whose-attestation-chain-is-valid-but-whose-issuer-s-did-document-has-rotated-its-verificati.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-did-anchored-agent-passport-whose-attestation-chain-is-valid-but-whose-issuer-s-did-document-has-rotated-its-verificati.warrant.json
# Markdown SHA-256:   79e76bfd6eafb57ef32e79d0521db87953ca808b69757a6cc10d240924d57c22
# Code AST SHA-256:   4cdbf93b1d1d7582419293a1cc7b1773c9558bca3d7d746fcf1021cc09ea0327
# Verified Classes:   VMSkewError, VMSnapshot, PassportVerifier
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class VMSkewError(RuntimeError):
    """Raised when a DID verification-method fragment resolves to key material
    that does not match the content pinned at first successful verification.
    This indicates fragment reuse across DID document versions and must abort
    the handshake; degraded-trust fallback is not permitted for this reason."""


@dataclass(frozen=True)
class VMSnapshot:
    fragment: str
    key_material: bytes
    controller: str
    created: str

    def content_hash(self) -> str:
        h = hashlib.sha256()
        h.update(self.fragment.encode())
        h.update(self.key_material)
        h.update(self.controller.encode())
        h.update(self.created.encode())
        return h.hexdigest()


class PassportVerifier:
    def __init__(self):
        # pinned snapshots keyed by (issuer_did, fragment)
        self._pins: dict[tuple[str, str], VMSnapshot] = {}

    def _resolve_current(self, issuer_did: str, fragment: str) -> Optional[VMSnapshot]:
        # In production: fetch did:web document, extract VM by fragment.
        # Returns None if fragment absent from current document version.
        ...

    def verify_attestation(
        self,
        issuer_did: str,
        fragment: str,
        signature: bytes,
        signed_payload: bytes,
    ) -> str:
        """Returns one of: 'valid', 'stale_but_bound'. Raises VMSkewError on skew."""
        key = (issuer_did, fragment)
        current = self._resolve_current(issuer_did, fragment)

        pinned = self._pins.get(key)

        if pinned is None:
            # First contact: pin whatever we resolve, then verify.
            if current is None:
                raise VMSkewError(
                    f"no VM '{fragment}' in {issuer_did} at first contact"
                )
            # verify signature against current.key_material here
            self._pins[key] = current
            return "valid"

        # Subsequent contact: enforce content binding.
        if current is None:
            # Issuer rotated the fragment out entirely. Binding intact,
            # liveness lapsed. Legitimate rotation case.
            return "stale_but_bound"

        if current.content_hash() != pinned.content_hash():
            # Fragment resolves, but to different key material.
            # This is the skew. No fallback.
            raise VMSkewError(
                f"VM '{fragment}' in {issuer_did} resolved to key material "
                f"differing from pinned snapshot "
                f"(pinned={pinned.content_hash()[:12]}, "
                f"current={current.content_hash()[:12]})"
            )

        return "valid"


def admit_peer(verifier: PassportVerifier, issuer_did: str, fragment: str,
               signature: bytes, payload: bytes) -> str:
    try:
        status = verifier.verify_attestation(issuer_did, fragment, signature, payload)
    except VMSkewError:
        # Hard abort: no degraded-trust fallback for skew.
        raise
    if status == "stale_but_bound":
        # Bounded admission: current task only, forced re-attestation deadline.
        return "admitted_bounded"
    return "admitted_full"
