# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-reject-a-peer-s-agent-card-after-a-key-rotation-when-the-signature-verifies-cleanly.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-reject-a-peer-s-agent-card-after-a-key-rotation-when-the-signature-verifies-cleanly.warrant.json
# Markdown SHA-256:   d1d5edc354d60420696d36eabc775cbf7f0cfac3b53811c044d5ac4b71275414
# Code AST SHA-256:   fee70a5004e8836d3d9291bdf83246a8b5d40571a4138baec751d0c55a9879ca
# Verified Classes:   IssuerContinuityError, PinnedIssuer
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class IssuerContinuityError(RuntimeError):
    """Raised when a card's signing key cannot be chained to a pinned issuer record."""


@dataclass
class PinnedIssuer:
    organization: str
    agent_name: str
    # RFC 7638 thumbprint -> first_seen epoch
    trusted_thumbprints: dict[str, int] = field(default_factory=dict)


def jwk_thumbprint(jwk: dict) -> str:
    # RFC 7638: canonical members only, lexicographic, no whitespace.
    required = {k: jwk[k] for k in ("crv", "kty", "x", "y") if k in jwk}
    canonical = json.dumps(required, separators=(",", ":"), sort_keys=True)
    return hashlib.sha256(canonical.encode()).hexdigest()


def admit_card(
    card: dict,
    jws_protected: dict,
    resolved_jwk: dict,
    pinned: PinnedIssuer,
    rotation_proof_thumbprint: str | None,
    now: int,
) -> PinnedIssuer:
    """Admit a card only if its signing key chains to a pinned predecessor.

    Signature validity is assumed already checked by the caller. This function
    enforces issuer *continuity*, which the A2A v1.0 card check does not.
    """
    signer_tp = jwk_thumbprint(resolved_jwk)

    # Case 1: signer already pinned -> continuity holds.
    if signer_tp in pinned.trusted_thumbprints:
        return pinned

    # Case 2: new signer, but a rotation proof signed by a pinned key vouches for it.
    if rotation_proof_thumbprint and rotation_proof_thumbprint in pinned.trusted_thumbprints:
        pinned.trusted_thumbprints[signer_tp] = now
        return pinned

    # Case 3: first sight of this issuer with no predecessor -> bootstrap only.
    if not pinned.trusted_thumbprints:
        pinned.trusted_thumbprints[signer_tp] = now
        return pinned

    # Case 4: unknown signer, pinned issuer exists, no valid rotation proof.
    raise IssuerContinuityError(
        f"card for {card.get('provider', {}).get('organization')!r}/"
        f"{card.get('name')!r} signed by unpinned key {signer_tp[:12]}…; "
        f"kid={jws_protected.get('kid')!r} verifies but does not chain to any "
        f"of {len(pinned.trusted_thumbprints)} pinned predecessor(s). "
        f"Refusing delegation (possible jwks_uri substitution or unproven rotation)."
    )


def check_rotation_ordering(jwks_ttl_s: int, min_rotation_interval_s: int) -> None:
    if jwks_ttl_s >= min_rotation_interval_s:
        raise IssuerContinuityError(
            f"JWKS TTL ({jwks_ttl_s}s) >= min rotation interval "
            f"({min_rotation_interval_s}s): caller can hold a card whose signing "
            f"key it can no longer resolve. Reduce TTL or fail closed to per-dispatch fetch."
        )
