# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-an-aaif-attestation-chain-when-the-issuer-s-credential-is-valid-but-the-subject-s-key-binding-proof-was-minted-against-a.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-an-aaif-attestation-chain-when-the-issuer-s-credential-is-valid-but-the-subject-s-key-binding-proof-was-minted-against-a.warrant.json
# Markdown SHA-256:   ebb11f2fa02ccd2d25139356d6f15d4b5a08fdf5aed9e2827dbbb94a56bfb00f
# Code AST SHA-256:   701ead3183cf9e5080ce6c809f9a7cbdf01c49117651c2a6d7be698f612cb90a
# Verified Classes:   BindingHashMismatch, AgentCard, BindingProof
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class BindingHashMismatch(RuntimeError):
    """Raised when a binding proof was minted against a card revision
    that differs from the card_hash recorded in the VC claim block."""
    pass


@dataclass
class AgentCard:
    revision: int
    tools: tuple[str, ...]

    def card_hash(self) -> str:
        body = f"r{self.revision}|{','.join(sorted(self.tools))}"
        return hashlib.sha256(body.encode()).hexdigest()


@dataclass
class BindingProof:
    nonce: str
    card_hash: str
    signature_valid: bool


def issue_credential(
    claim_card_hash: str,
    proof: BindingProof,
    issuer_signs,
) -> dict:
    # Gate 1: the binding proof must attest the same card revision
    # the issuer recorded in the claim block. Signature validity is
    # necessary but NOT sufficient.
    if not proof.signature_valid:
        raise BindingHashMismatch("binding proof signature did not verify")
    if proof.card_hash != claim_card_hash:
        raise BindingHashMismatch(
            f"binding proof anchored to {proof.card_hash[:12]} but claim "
            f"records {claim_card_hash[:12]}; re-fetch card and re-issue"
        )
    return issuer_signs(claim_card_hash, proof.nonce)


def verify_credential(
    vc: dict,
    live_card: AgentCard,
    freshness_ok: bool,
) -> bool:
    # Gate 2: verifier must re-resolve the card and confirm the claim
    # hash still matches the live manifest within the freshness window.
    if not freshness_ok:
        raise BindingHashMismatch("agent-card outside freshness window")
    if vc["claim"]["card_hash"] != live_card.card_hash():
        raise BindingHashMismatch(
            f"claim card_hash {vc['claim']['card_hash'][:12]} != live "
            f"card {live_card.card_hash()[:12]} (rev {live_card.revision})"
        )
    return True
