# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-did-to-capability-token-binding-drift-across-a-multi-hop-agent-call-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-did-to-capability-token-binding-drift-across-a-multi-hop-agent-call-chain.warrant.json
# Markdown SHA-256:   87c1f2c5f83614505bad71b131d9edf56231fa11f162d5a769ef7b2a2a7d1d82
# Code AST SHA-256:   fc48338d5ea8c0b95fe54efef19a3e82d8f55d1aea48d55ba5d49766feda53eb
# Verified Classes:   BindingDriftError, DidDocument, CapabilityToken
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from typing import Optional


class BindingDriftError(RuntimeError):
    """Raised when a capability token's committed key thumbprint does not
    match the key actually presenting at the current hop, and no valid
    rotation proof bridges the gap."""
    pass


@dataclass
class DidDocument:
    did: str
    active_key_thumbprint: str
    version_id: int
    resolved_at: float
    rotations: dict = field(default_factory=dict)  # old_thumb -> (new_thumb, timestamp)


@dataclass
class CapabilityToken:
    issuer_did: str
    presenter_did: str
    committed_key_thumbprint: str  # RFC 7638 thumbprint of the key authorized at mint
    signing_key_thumbprint: str    # thumbprint of the key that actually signed this hop
    minted_at: float
    expires_at: float
    rotation_proof: Optional[dict] = None  # {"from": thumb, "to": thumb, "signed_at": ts}


def jwk_thumbprint(public_key_material: str) -> str:
    return hashlib.sha256(public_key_material.encode()).hexdigest()[:16]


def verify_hop(
    token: CapabilityToken,
    resolved_doc: DidDocument,
    now: Optional[float] = None,
) -> bool:
    now = now if now is not None else time.time()

    # 1. Temporal validity — loud, cheap.
    if now > token.expires_at:
        raise BindingDriftError(f"token expired at {token.expires_at}, now={now}")

    # 2. Signature must verify against the *currently resolved* key.
    if token.signing_key_thumbprint != resolved_doc.active_key_thumbprint:
        raise BindingDriftError(
            f"signing key {token.signing_key_thumbprint} is not the active key "
            f"{resolved_doc.active_key_thumbprint} for {resolved_doc.did}"
        )

    # 3. THE BINDING INVARIANT: committed key must equal presenting key,
    #    OR a rotation proof must bridge them within the authorization window.
    if token.committed_key_thumbprint != token.signing_key_thumbprint:
        proof = token.rotation_proof
        if proof is None:
            # Silent-accept failure mode: naive verifiers stop here and pass.
            raise BindingDriftError(
                f"key gap: token committed to {token.committed_key_thumbprint} "
                f"but hop presents {token.signing_key_thumbprint} with no rotation proof"
            )

        # Rotation proof must (a) match the committed key, (b) match the presenter,
        # (c) have been signed *during* the token's authorization window.
        if proof.get("from") != token.committed_key_thumbprint:
            raise BindingDriftError("rotation proof 'from' does not match committed key")
        if proof.get("to") != token.signing_key_thumbprint:
            raise BindingDriftError("rotation proof 'to' does not match presenting key")
        signed_at = proof.get("signed_at", float("inf"))
        if not (token.minted_at <= signed_at <= token.expires_at):
            raise BindingDriftError(
                f"rotation proof signed_at={signed_at} outside authorization window "
                f"[{token.minted_at}, {token.expires_at}]"
            )
        # Cross-check against the DID document's own rotation record.
        recorded = resolved_doc.rotations.get(token.committed_key_thumbprint)
        if recorded is None or recorded[0] != token.signing_key_thumbprint:
            raise BindingDriftError(
                "rotation proof not corroborated by DID document rotation record"
            )

    return True


def verify_chain(tokens: list[CapabilityToken], docs: dict[str, DidDocument]) -> None:
    for i, tok in enumerate(tokens):
        doc = docs.get(tok.presenter_did)
        if doc is None:
            raise BindingDriftError(f"hop {i}: no DID document for {tok.presenter_did}")
        verify_hop(tok, doc)
