# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-delegates-work-it-cannot-later-prove-it-authorized-a2a-receipt-chain-breaks-under-key-rotation-and-re-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-delegates-work-it-cannot-later-prove-it-authorized-a2a-receipt-chain-breaks-under-key-rotation-and-re-delegation.warrant.json
# Markdown SHA-256:   1243413f8715c7f38665599066ea2bf8ae4cf69e0554602746227a57402e002e
# Code AST SHA-256:   4ab703adfbb07999658ee2eb656684c3bec23ee4aa4fbf82be9a596fa58d5698
# Verified Classes:   ReceiptChainBroken, Warrant, KeyHistoryEntry, Receipt
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ReceiptChainBroken(RuntimeError):
    """Raised when a delegation receipt cannot be bound to its authorizing principal."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer: str
    subject: str
    parent_hash: Optional[str]   # H(signed bytes of parent warrant), NOT parent id
    signed_bytes: bytes
    signature: bytes


@dataclass(frozen=True)
class KeyHistoryEntry:
    principal: str
    key_id: str
    valid_from: int
    valid_until: Optional[int]   # None == still active


@dataclass(frozen=True)
class Receipt:
    warrant_hash: str
    result_hash: str
    signer: str
    key_history_digest: str
    signature: bytes


def _hash(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def verify_chain(
    receipts: list[Receipt],
    warrants: dict[str, Warrant],          # keyed by warrant_id, but binding via hash
    key_history: list[KeyHistoryEntry],
    issued_at: dict[str, int],             # warrant_id -> issuance timestamp
    root_principal: str,
) -> str:
    """
    Walk receipts back to the root principal. Every hop must bind by content hash,
    and every signing key must resolve against the append-only history at issuance time.
    """
    if not receipts:
        raise ReceiptChainBroken("empty receipt chain: nothing to bind")

    # Index warrants by the hash of their signed bytes, so identifier collisions
    # cannot silently swap one warrant for another.
    by_hash = {_hash(w.signed_bytes): w for w in warrants.values()}

    # Detect identifier collisions that would make the chain ambiguous.
    id_counts: dict[str, int] = {}
    for w in warrants.values():
        id_counts[w.warrant_id] = id_counts.get(w.warrant_id, 0) + 1
    for wid, n in id_counts.items():
        if n > 1:
            raise ReceiptChainBroken(
                f"warrant id {wid!r} collides across {n} distinct signed warrants; "
                "identifier binding is unresolvable"
            )

    # Verify each receipt points at a warrant whose parent_hash is a real content hash.
    for r in receipts:
        w = by_hash.get(r.warrant_hash)
        if w is None:
            raise ReceiptChainBroken(
                f"receipt references warrant hash {r.warrant_hash!r} which is not present; "
                "chain dead-ends (likely identifier-only binding)"
            )
        if w.parent_hash is not None and w.parent_hash not in by_hash:
            raise ReceiptChainBroken(
                f"warrant {w.warrant_id!r} parent_hash {w.parent_hash!r} does not resolve; "
                "parent was bound by identifier, not content"
            )
        # Resolve the signer's key against history at issuance time.
        ts = issued_at.get(w.warrant_id)
        if ts is None:
            raise ReceiptChainBroken(
                f"no issuance timestamp for {w.warrant_id!r}; cannot resolve key history"
            )
        ok = any(
            e.principal == w.issuer
            and e.valid_from <= ts
            and (e.valid_until is None or ts < e.valid_until)
            for e in key_history
        )
        if not ok:
            raise ReceiptChainBroken(
                f"issuer {w.issuer!r} key not resolvable at issuance ts={ts}; "
                "rotation without key-history retroactively invalidates the warrant"
            )

    # Walk to the root: follow parent_hash from the terminal receipt.
    terminal = by_hash[receipts[-1].warrant_hash]
    node = terminal
    seen = set()
    while node.parent_hash is not None:
        if node.warrant_id in seen:
            raise ReceiptChainBroken("cycle detected in delegation chain")
        seen.add(node.warrant_id)
        node = by_hash[node.parent_hash]

    if node.issuer != root_principal:
        raise ReceiptChainBroken(
            f"chain root issuer {node.issuer!r} != expected principal {root_principal!r}"
        )
    return receipts[-1].result_hash
