# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-did-anchored-agent-registry-has-silently-re-bound-a-verifiable-credential-to-a-shadow-key-during-cross-org-federati.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-did-anchored-agent-registry-has-silently-re-bound-a-verifiable-credential-to-a-shadow-key-during-cross-org-federati.warrant.json
# Markdown SHA-256:   fa5d12d6de2e5aebaf64c6234b2fa962c6ac89462930faecdd7370d4713d7b24
# Code AST SHA-256:   214085b33fb9a897492f80fd86ba0c8d40f4bf605d7095756aef4b00b1652c26
# Verified Classes:   ShadowKeyRebindError, StaleTrustWindowError, VerificationMethod, DidDocument, Credential
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import base64
from dataclasses import dataclass
from typing import Optional


class ShadowKeyRebindError(RuntimeError):
    """Raised when a VC's named verification method resolves to key material
    that does not thumbprint-match the key that signed the proof, indicating
    a DID document rotation reused a fragment id (shadow-key rebind)."""
    pass


class StaleTrustWindowError(RuntimeError):
    """Raised when a credential's issuanceDate postdates the resolved DID
    document's `updated` field while the named fragment's key material has
    changed since the credential was minted — the verifier's cache is stale
    relative to a rotation that preceded issuance."""
    pass


@dataclass
class VerificationMethod:
    fragment_id: str          # e.g. "#key-2" — UNTRUSTED label
    public_key_multibase: str
    in_assertion_method: bool


@dataclass
class DidDocument:
    did: str
    updated: str              # ISO-8601
    methods: dict             # fragment_id -> VerificationMethod


@dataclass
class Credential:
    issuer_did: str
    issuance_date: str        # ISO-8601
    proof_verification_method: str   # full URI incl. fragment
    proof_key_multibase: str         # key material carried in the proof


def _thumbprint(multibase: str) -> str:
    raw = base64.b64decode(multibase.split("z", 1)[-1] + "==")
    return hashlib.sha256(raw).hexdigest()


def verify_credential(
    cred: Credential,
    resolved_doc: DidDocument,
    cached_doc: Optional[DidDocument] = None,
) -> bool:
    # 1. Extract fragment from the proof's verificationMethod URI.
    fragment = "#" + cred.proof_verification_method.rsplit("#", 1)[-1]

    method = resolved_doc.methods.get(fragment)
    if method is None:
        # Clean failure: fragment removed entirely. Good.
        return False

    # 2. Thumbprint check — the discriminator against shadow-key rebind.
    proof_tp = _thumbprint(cred.proof_key_multibase)
    resolved_tp = _thumbprint(method.public_key_multibase)
    if proof_tp != resolved_tp:
        raise ShadowKeyRebindError(
            f"fragment {fragment} on {resolved_doc.did} resolves to key "
            f"{resolved_tp[:12]}... but proof signed by {proof_tp[:12]}...; "
            f"fragment id was reused across a rotation"
        )

    # 3. Assertion-method membership — key must be currently authorized.
    if not method.in_assertion_method:
        return False

    # 4. Stale-window check against cache generation.
    if cached_doc is not None:
        cached_method = cached_doc.methods.get(fragment)
        if cached_method is not None:
            cached_tp = _thumbprint(cached_method.public_key_multibase)
            if cached_tp != resolved_tp and cred.issuance_date >= resolved_doc.updated:
                raise StaleTrustWindowError(
                    f"credential issued {cred.issuance_date} >= document "
                    f"updated {resolved_doc.updated}, but fragment {fragment} "
                    f"changed key material since cache; issuance may have "
                    f"occurred under a de-authorized holder"
                )

    return True
