# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-rotated-agent-card-as-a-new-principal-rather-than-a-continuation-of-the-old-one.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-rotated-agent-card-as-a-new-principal-rather-than-a-continuation-of-the-old-one.warrant.json
# Markdown SHA-256:   afcc9df527ac13ad07d83a748df5e27656161968c3e9ec7df173ad11476a5dfb
# Code AST SHA-256:   2ad4451023ff355a1fca74fb7da9bd731ab88801c4c1123fadf9d12f3a2cbb53
# Verified Classes:   PrincipalRotationError, CardIdentity, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class PrincipalRotationError(RuntimeError):
    """Raised when a presented Agent Card represents a different principal
    than the one the active warrant was issued against."""


@dataclass(frozen=True)
class CardIdentity:
    agent_id: str
    issuer_lineage: tuple  # e.g. ("R", "issuer-A")
    key_thumbprint: str


@dataclass(frozen=True)
class Warrant:
    agent_id: str
    issuer_lineage: tuple
    key_thumbprint: str
    scope: str


def accept_rotated_card(
    cached: CardIdentity,
    presented: CardIdentity,
    warrant: Optional[Warrant],
    root_of,
) -> Warrant:
    """Validate a rotated Agent Card and return the warrant to use.

    Continuation requires identical agent_id, identical issuer lineage, and
    a warrant whose bound thumbprint matches the *issuance-time* thumbprint.
    Any divergence is a principal change and voids the warrant.
    """
    if root_of(presented.issuer_lineage) != root_of(cached.issuer_lineage):
        raise PrincipalRotationError(
            f"root changed: {cached.issuer_lineage} -> {presented.issuer_lineage}"
        )

    if presented.agent_id != cached.agent_id:
        raise PrincipalRotationError(
            f"agent_id changed: {cached.agent_id} -> {presented.agent_id}"
        )

    if presented.issuer_lineage != cached.issuer_lineage:
        # Same root, different intermediate: NEW PRINCIPAL.
        raise PrincipalRotationError(
            "issuer lineage diverged under shared root; "
            f"{cached.issuer_lineage} -> {presented.issuer_lineage}; "
            "warrant voided, re-negotiate capabilities and re-issue"
        )

    if warrant is None:
        raise PrincipalRotationError("no active warrant to continue")

    if warrant.key_thumbprint != presented.key_thumbprint:
        # Key rotated under same issuer: acceptable continuation, but the
        # warrant must have been issued against the current key or be
        # explicitly re-bound by the issuing authority (not by the caller).
        raise PrincipalRotationError(
            "warrant thumbprint does not match presented key; "
            "caller must not re-bind, issuer must re-issue"
        )

    return warrant
