# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-rotated-aaif-credential-as-a-new-principal-rather-than-a-continued-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-rotated-aaif-credential-as-a-new-principal-rather-than-a-continued-identity.warrant.json
# Markdown SHA-256:   891e9b42e6d007fc827563ce0255513e4e0aa182114afb8fd004dc1f7071dd70
# Code AST SHA-256:   5ffc7bdaf48abf58b533f7225363abde47cf7fe5fcbf5a1ae6669c322ca7caad
# Verified Classes:   IdentityForkError, AAIFCredential, ReputationRow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class IdentityForkError(RuntimeError):
    """Raised when a rotated credential cannot be proven continuous with the prior principal."""
    pass


@dataclass(frozen=True)
class AAIFCredential:
    subject: str
    key_id: str
    issuer_root: str
    rotation_proof: Optional[bytes]  # signature by prior key over new pubkey
    rotation_epoch: int


@dataclass
class ReputationRow:
    subject: str
    key_id: str
    issuer_root: str
    score: float
    epoch: int
    superseded_by: Optional[str] = None


def admit_credential(
    cred: AAIFCredential,
    ledger: dict[str, ReputationRow],
    verify_rotation_proof,
    cold_start_prior: float = 0.5,
) -> ReputationRow:
    """
    Returns the reputation row the peer should trust for this credential.
    Raises IdentityForkError if the credential is a fork that must not inherit trust.
    """
    prior = ledger.get(cred.subject)

    if prior is None:
        # First sighting: cold start, keyed on full triple.
        row = ReputationRow(cred.subject, cred.key_id, cred.issuer_root,
                            cold_start_prior, cred.rotation_epoch)
        ledger[f"{cred.subject}:{cred.key_id}:{cred.issuer_root}"] = row
        return row

    # Same key, same issuer: pure continuity.
    if prior.key_id == cred.key_id and prior.issuer_root == cred.issuer_root:
        return prior

    # Key changed. Continuity requires a verifiable rotation proof.
    if cred.rotation_proof is None:
        # No proof. If issuer changed, this is a hard fork.
        if prior.issuer_root != cred.issuer_root:
            raise IdentityForkError(
                f"credential for {cred.subject} presented under issuer "
                f"{cred.issuer_root} with no rotation proof from {prior.issuer_root}; "
                f"treating as new principal, reputation must not carry forward"
            )
        # Same issuer, no proof: quarantine at cold-start prior, do not inherit.
        row = ReputationRow(cred.subject, cred.key_id, cred.issuer_root,
                            cold_start_prior, cred.rotation_epoch)
        ledger[f"{cred.subject}:{cred.key_id}:{cred.issuer_root}"] = row
        return row

    if not verify_rotation_proof(cred.rotation_proof, prior, cred):
        raise IdentityForkError(
            f"rotation proof for {cred.subject} failed verification against "
            f"prior key {prior.key_id}"
        )

    if cred.rotation_epoch <= prior.epoch:
        raise IdentityForkError(
            f"rotation epoch {cred.rotation_epoch} not monotonic over {prior.epoch} "
            f"for {cred.subject}; possible replay"
        )

    # Verified continuity: carry reputation forward under new key.
    row = ReputationRow(cred.subject, cred.key_id, cred.issuer_root,
                        prior.score, cred.rotation_epoch)
    prior.superseded_by = f"{cred.subject}:{cred.key_id}:{cred.issuer_root}"
    ledger[f"{cred.subject}:{cred.key_id}:{cred.issuer_root}"] = row
    return row
