# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-cached-agent-card-after-the-remote-signer-rotates-its-jwks.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-cached-agent-card-after-the-remote-signer-rotates-its-jwks.warrant.json
# Markdown SHA-256:   1f0c1f5e8fb7b9193fc851b6e431f52ade2d25a752b2a6e16274257ae1f91d7b
# Code AST SHA-256:   e6ff8653dccad8dbdb46d1ab6a3caf0d2a4fb48a2b71427138ca7a7700d66a25
# Verified Classes:   CardKeyAuthorizationMismatch, CachedCard, SignedAcceptance
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CardKeyAuthorizationMismatch(RuntimeError):
    """Raised when a verifying kid is not authorized by the card version the delegator planned against."""
    pass


@dataclass(frozen=True)
class CachedCard:
    card_version: int
    signing_keys: frozenset  # kids authorized by THIS card version
    jwks_uri: str


@dataclass(frozen=True)
class SignedAcceptance:
    kid: str
    card_version_claimed: int
    signature: bytes


def verify_acceptance(
    card: CachedCard,
    acceptance: SignedAcceptance,
    live_jwks: dict,  # kid -> public key, fetched live (may contain retired/revoked keys)
    signature_valid: bool,
) -> None:
    # Invariant: the verifying kid MUST be authorized by the SAME card version
    # the delegator used to plan the task. JWKS membership alone is NOT authorization.
    if acceptance.card_version_claimed != card.card_version:
        raise CardKeyAuthorizationMismatch(
            f"acceptance claims card_version={acceptance.card_version_claimed}, "
            f"delegator planned against card_version={card.card_version}"
        )

    if acceptance.kid not in card.signing_keys:
        # The key is not authorized by the card we planned against. Even if it is
        # present in the live JWKS (retired-key grace window or rotation), we must
        # NOT fall back to JWKS-as-authorization. Force re-discovery.
        raise CardKeyAuthorizationMismatch(
            f"kid={acceptance.kid} not in authorized signing_keys "
            f"{sorted(card.signing_keys)} for card_version={card.card_version}; "
            f"present_in_live_jwks={acceptance.kid in live_jwks}. "
            f"Re-discover Agent Card before accepting."
        )

    if not signature_valid:
        raise CardKeyAuthorizationMismatch(
            f"signature invalid for kid={acceptance.kid} under card_version={card.card_version}"
        )

    # Lineage record: the (card_version, kid) pair that authorized this delegation.
    lineage = hashlib.sha256(
        f"{card.card_version}:{acceptance.kid}".encode()
    ).hexdigest()
    return lineage
