# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bootstrap-federated-trust-when-pairwise-did-binding-and-a2a-v1-0-verifiable-credential-exchange-disagree-on-first-contact.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bootstrap-federated-trust-when-pairwise-did-binding-and-a2a-v1-0-verifiable-credential-exchange-disagree-on-first-contact.warrant.json
# Markdown SHA-256:   c0eb494a1ae3f04607386d369965f185da6cfb0c7e22928b708e2162b853fbd2
# Code AST SHA-256:   86f650f16cdf6aa2eabded4855af915e67ab3b0f62fcc77c006ca7115a1fbfcb
# Verified Classes:   PairwiseBindingError, HandshakeAttempt, PairwiseTrustRecord
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class PairwiseBindingError(RuntimeError):
    """Raised when a federated trust record was assembled across non-atomic handshake attempts."""
    pass


@dataclass
class HandshakeAttempt:
    attempt_id: str
    card_key_fingerprint: str
    card_verified: bool
    vc_jti: str
    vc_subject_did: str
    vc_issuer_did: str
    vc_verified: bool
    issuer_metadata_fetched_at: float
    card_fetched_at: float
    verified_at: Optional[float] = None


@dataclass
class PairwiseTrustRecord:
    subject_did: str
    card_key_fingerprint: str
    vc_jti: str
    issuer_did: str
    verified_at: float


def fingerprint_key(key_bytes: bytes) -> str:
    return "sha256:" + hashlib.sha256(key_bytes).hexdigest()


def bind_pairwise(attempts: list[HandshakeAttempt]) -> PairwiseTrustRecord:
    """
    Establish a pairwise DID binding from handshake attempt(s).
    Enforces: exactly one attempt must carry BOTH card_verified and vc_verified,
    and the card key fingerprint used to verify the VC's subject must be the
    same key that signed the card in that attempt.
    """
    if not attempts:
        raise PairwiseBindingError("no handshake attempts supplied")

    # Find attempts that individually satisfy the full binding.
    complete = [
        a for a in attempts
        if a.card_verified and a.vc_verified and a.vc_subject_did
    ]

    if len(complete) == 0:
        # Detect the partial-accumulation pathology explicitly.
        card_ok = any(a.card_verified for a in attempts)
        vc_ok = any(a.vc_verified for a in attempts)
        if card_ok and vc_ok:
            raise PairwiseBindingError(
                "trust halves accumulated across attempts: card_verified and "
                "vc_verified observed in different handshakes; refusing to merge"
            )
        raise PairwiseBindingError("no single attempt completed both card and VC verification")

    if len(complete) > 1:
        # Multiple complete attempts are only acceptable if they agree on the binding.
        fps = {a.card_key_fingerprint for a in complete}
        jtis = {a.vc_jti for a in complete}
        if len(fps) > 1 or len(jtis) > 1:
            raise PairwiseBindingError(
                f"conflicting complete attempts: fingerprints={fps} jtis={jtis}; "
                "card key rotated mid-handshake, must restart"
            )

    chosen = complete[-1]

    # Atomicity guard: issuer metadata and card must be observed within the
    # same transaction window; neither may be stale relative to the other.
    skew = abs(chosen.issuer_metadata_fetched_at - chosen.card_fetched_at)
    if skew > 2.0:
        raise PairwiseBindingError(
            f"issuer metadata and card fetched {skew:.2f}s apart; "
            "not a single atomic handshake transaction"
        )

    # Subject DID must be exactly the card's DID (string equality is necessary
    # but only sufficient given the same-attempt card verification above).
    if chosen.vc_subject_did != chosen.vc_subject_did.strip() or not chosen.vc_subject_did:
        raise PairwiseBindingError("malformed subject DID in VC")

    return PairwiseTrustRecord(
        subject_did=chosen.vc_subject_did,
        card_key_fingerprint=chosen.card_key_fingerprint,
        vc_jti=chosen.vc_jti,
        issuer_did=chosen.vc_issuer_did,
        verified_at=chosen.verified_at or time.time(),
    )
