# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-peer-s-signed-reputation-attestation-whose-subject-binding-was-minted-against-a-rotated-agent-card.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-peer-s-signed-reputation-attestation-whose-subject-binding-was-minted-against-a-rotated-agent-card.warrant.json
# Markdown SHA-256:   75faae2eeccced9464a53175179175b0bd4e9c56542a852f71b4537a5c81b120
# Code AST SHA-256:   81ce8c4caeb1515704a7be2b8cd5134a3c943b3c4e0e357ab3fdbf2a4c0bace4
# Verified Classes:   RotationChainBindingError, RotationLink, AgentCard, Attestation
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class RotationChainBindingError(RuntimeError):
    """Raised when an attestation's subject key cannot be bound to the live card."""


@dataclass
class RotationLink:
    key_id: str
    card_hash: str
    rotated_at: int
    signed_by_prev: bytes  # signature over (key_id, card_hash, rotated_at) by predecessor key


@dataclass
class AgentCard:
    agent_id: str
    verification_key: str
    card_hash: str
    rotation_chain: list[RotationLink]


@dataclass
class Attestation:
    agent_id: str
    subject_key: str
    score: float
    issued_at: int
    expires_at: int


def verify_rotation_chain(card: AgentCard, attestation: Attestation, now: int,
                          sig_ok) -> float:
    """
    Returns the bound reputation score. Raises RotationChainBindingError if the
    attestation's subject_key cannot be proven to be an ancestor of the live key.
    """
    if attestation.agent_id != card.agent_id:
        raise RotationChainBindingError(
            f"agent_id mismatch: {attestation.agent_id!r} vs {card.agent_id!r}")
    if not (attestation.issued_at <= now < attestation.expires_at):
        raise RotationChainBindingError("attestation outside validity window")

    # Walk the chain from the attested subject key to the live key.
    chain = card.rotation_chain
    if not chain:
        # No rotation history: only valid if subject_key IS the live key.
        if attestation.subject_key == card.verification_key:
            return attestation.score
        raise RotationChainBindingError(
            "no rotation chain and subject_key != live key; cannot bind")

    # Locate the subject key in the chain (or as the live key).
    keys = [link.key_id for link in chain] + [card.verification_key]
    if attestation.subject_key not in keys:
        raise RotationChainBindingError(
            f"subject_key {attestation.subject_key!r} not in rotation lineage")

    idx = keys.index(attestation.subject_key)
    # Every link from idx onward must verify against its predecessor.
    for i in range(idx, len(chain)):
        link = chain[i]
        prev_key = keys[i - 1] if i > 0 else attestation.subject_key
        if not sig_ok(prev_key, link):
            raise RotationChainBindingError(
                f"broken rotation link at {link.key_id!r} (signed_by {prev_key!r})")
        # Attestation must have been issued before the subject key was superseded.
        if attestation.issued_at >= link.rotated_at:
            raise RotationChainBindingError(
                f"attestation issued_at {attestation.issued_at} after key "
                f"{link.key_id!r} rotated at {link.rotated_at}")

    # Final link must terminate at the live card hash.
    if chain[-1].card_hash != card.card_hash:
        raise RotationChainBindingError(
            "rotation chain head does not match live card hash")

    return attestation.score


def authorize_handoff(card: AgentCard, attestation: Attestation, now: int,
                      sig_ok, min_score: float = 0.8) -> bool:
    try:
        bound = verify_rotation_chain(card, attestation, now, sig_ok)
    except RotationChainBindingError:
        # Downgrade, do not hard-fail: preserve liveness, refuse to bind.
        bound = 0.0
    if bound < min_score:
        raise RotationChainBindingError(
            f"bound reputation {bound:.2f} < required {min_score:.2f} for "
            f"{card.agent_id!r}; refusing high-value handoff")
    return True
