# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-verifiable-credential-chain-has-silently-forked-its-trust-anchor-during-cross-org-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-verifiable-credential-chain-has-silently-forked-its-trust-anchor-during-cross-org-agent-federation.warrant.json
# Markdown SHA-256:   42ef4e2daa0ba425afece2bcef9eb79247753a645b10f181b8526b8e2e1df544
# Code AST SHA-256:   119d0258f0488a3350e4d8941ce492b12533479fb594cefd0b2b128a018f6328
# Verified Classes:   ForkedTrustAnchorError, PinnedAnchor, VerifiableCredential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ForkedTrustAnchorError(RuntimeError):
    """Raised when a VC's chain terminates at an anchor whose epoch does not
    match the credential's issuance epoch. This is a terminal policy denial,
    NOT a transient resolution miss — do not fall back to a prior anchor."""


@dataclass(frozen=True)
class PinnedAnchor:
    key_id: str
    epoch: int          # monotonic federation epoch, bumped on every rotation
    public_key: bytes
    authoritative: bool # exactly one anchor per store should be True


@dataclass(frozen=True)
class VerifiableCredential:
    issuer: str
    epoch: int                 # issuance epoch, must equal status-list epoch
    status_list_epoch: int
    signature: bytes


def verify_chain(
    vc: VerifiableCredential,
    anchor_store: list[PinnedAnchor],
    chain_terminates_at: str,
) -> PinnedAnchor:
    # Locate the anchor the chain actually terminates at.
    terminator: Optional[PinnedAnchor] = next(
        (a for a in anchor_store if a.key_id == chain_terminates_at), None
    )
    if terminator is None:
        # Genuine resolution miss: anchor not present at all. Retryable.
        raise ForkedTrustAnchorError(
            f"anchor {chain_terminates_at} absent from store; cannot decide"
        )

    # The status list and the credential must agree on epoch before anything
    # else is trusted — a cross-epoch join is the forking signature.
    if vc.epoch != vc.status_list_epoch:
        raise ForkedTrustAnchorError(
            f"credential epoch {vc.epoch} != status-list epoch "
            f"{vc.status_list_epoch}; cross-epoch status join refused"
        )

    # The core invariant: the terminating anchor's epoch must equal the
    # credential's epoch. A lower anchor epoch means the chain forked onto a
    # retired root. This is stable and non-retryable — never fall back.
    if terminator.epoch != vc.epoch:
        raise ForkedTrustAnchorError(
            f"chain terminated at anchor epoch {terminator.epoch} but VC epoch "
            f"is {vc.epoch}; anchor forked, refusing handoff"
        )

    # Only now is it meaningful to require the anchor be policy-authoritative.
    if not terminator.authoritative:
        raise ForkedTrustAnchorError(
            f"anchor {terminator.key_id} epoch {terminator.epoch} matches VC "
            f"but is not designated authoritative by local policy"
        )

    return terminator
