# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-cross-issuer-attestation-forgery-when-a-delegated-warrant-s-trust-chain-re-roots-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-cross-issuer-attestation-forgery-when-a-delegated-warrant-s-trust-chain-re-roots-mid-handoff.warrant.json
# Markdown SHA-256:   d5646c9ac23a8c87160f30fdda9f2c26152cd1e54925df1d6adaf6d252b6e48b
# Code AST SHA-256:   7c16b52eca850eac319887ed7fb7437e82095d6d6b4fa36d6a5dd76f3c449c13
# Verified Classes:   AttestationContinuityError, Warrant, Pin
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AttestationContinuityError(RuntimeError):
    """Raised when a delegated warrant's trust chain is signature-valid but
    discontinuous with the verifier's pinned root for the subject."""
    pass


@dataclass(frozen=True)
class Warrant:
    subject: str
    issuer: str
    delegation_parent_hash: str
    issuer_chain: tuple          # ((child, parent), ...) ordered holder -> root
    root_hint: str
    chain_epoch: int
    signatures_valid: bool        # assumed checked upstream


@dataclass(frozen=True)
class Pin:
    subject: str
    root: str
    epoch: int


def _terminal_root(w: Warrant) -> str:
    if not w.issuer_chain:
        raise AttestationContinuityError(f"empty issuer_chain for {w.subject}")
    return w.issuer_chain[-1][1]


def verify_continuity(
    w: Warrant,
    pins: dict,                   # subject -> Pin
    anchors: set,                 # roots the verifier trusts at all
    transition_warrants: dict,    # (old_root, new_root) -> epoch
) -> Pin:
    if not w.signatures_valid:
        raise AttestationContinuityError(f"signature invalid for {w.subject}")

    terminal = _terminal_root(w)
    if terminal not in anchors:
        raise AttestationContinuityError(
            f"terminal root {terminal} not anchored for {w.subject}"
        )

    pin = pins.get(w.subject)
    if pin is None:
        # First observation: establish the pin. This is the only moment
        # a new root may be adopted without a transition warrant.
        return Pin(subject=w.subject, root=terminal, epoch=w.chain_epoch)

    if terminal == pin.root:
        if w.chain_epoch < pin.epoch:
            raise AttestationContinuityError(
                f"epoch regression for {w.subject}: {w.chain_epoch} < {pin.epoch}"
            )
        return pin

    # Terminal root differs from pinned root: this is the substitution window.
    # Accept only with a root-to-root transition warrant at a strictly
    # greater epoch. Anything else is a re-rooting attempt.
    key = (pin.root, terminal)
    if key not in transition_warrants:
        raise AttestationContinuityError(
            f"root substitution for {w.subject}: pinned {pin.root} "
            f"but chain terminates at {terminal} with no transition warrant"
        )
    if w.chain_epoch <= transition_warrants[key]:
        raise AttestationContinuityError(
            f"stale transition warrant for {w.subject}: "
            f"epoch {w.chain_epoch} <= {transition_warrants[key]}"
        )
    return Pin(subject=w.subject, root=terminal, epoch=w.chain_epoch)


def parent_hash_matches_pinned(w: Warrant, expected_parent_hash: str) -> None:
    """The decisive check: bind the first hop to an independently pinned
    parent, not to whatever predecessor the presented chain happens to carry."""
    first_hop_parent = w.issuer_chain[0][1] if w.issuer_chain else None
    recomputed = hashlib.sha256(
        f"{w.subject}|{first_hop_parent}|{w.chain_epoch}".encode()
    ).hexdigest()
    if recomputed != expected_parent_hash:
        raise AttestationContinuityError(
            f"parent hash mismatch for {w.subject}: chain spliced at hop 0"
        )
