# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-resolve-a-federated-peer-anchor-set-divergence-across-aaif-issuers-under-lazy-trust-materialization.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-resolve-a-federated-peer-anchor-set-divergence-across-aaif-issuers-under-lazy-trust-materialization.warrant.json
# Markdown SHA-256:   12f8467289e090faf0b9f3cb197810ef8d9ada41804f06cecb0c49bdb68c32f7
# Code AST SHA-256:   78566932c68e2e21bafc08b784402c1e933b661fb3b23fd4d917ec28e68e99ad
# Verified Classes:   AnchorDivergenceError, UntrustedRootError, KeyLink, AnchorSet
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class AnchorDivergenceError(RuntimeError):
    """Local anchor set cannot reach the warrant's claimed epoch, but a chain exists."""


class UntrustedRootError(RuntimeError):
    """No reachable chain to a bootstrap-pinned root; do not retry."""


@dataclass
class KeyLink:
    epoch: int
    pubkey_fp: str
    next_epoch: Optional[int] = None
    next_sig: Optional[str] = None  # signature by this key over the next key's fp


@dataclass
class AnchorSet:
    issuer: str
    pinned_root_fp: str
    links: dict = field(default_factory=dict)  # epoch -> KeyLink

    def digest(self) -> str:
        h = hashlib.sha256()
        for ep in sorted(self.links):
            h.update(f"{ep}:{self.links[ep].pubkey_fp}".encode())
        return h.hexdigest()[:16]


def _verify_link_sig(link: KeyLink) -> bool:
    # Placeholder: real impl verifies link.next_sig over next key fp with link.pubkey.
    return link.next_sig is not None and link.next_epoch is not None


def resolve_warrant(anchors: AnchorSet, claimed_epoch: int, warrant_body_fp: str) -> str:
    """
    Admit a warrant only if its signing epoch is reachable from the pinned root
    via signed, monotonic key-history links held locally.
    """
    if anchors.pinned_root_fp is None:
        raise UntrustedRootError(
            f"issuer={anchors.issuer}: no bootstrap-pinned root; refusing to resolve"
        )

    if claimed_epoch not in anchors.links:
        # Distinguish divergence (chain may exist) from untrusted (no chain).
        if any(l.next_epoch == claimed_epoch for l in anchors.links.values()):
            raise AnchorDivergenceError(
                f"issuer={anchors.issuer} epoch={claimed_epoch} not materialized; "
                f"local_digest={anchors.digest()} — re-materialize, do not blind-retry"
            )
        raise UntrustedRootError(
            f"issuer={anchors.issuer} epoch={claimed_epoch} unreachable from "
            f"root={anchors.pinned_root_fp}; no chain present"
        )

    # Walk forward from claimed epoch to a link whose fingerprint is the pinned root,
    # verifying each next-pointer signature.
    seen = set()
    cur = claimed_epoch
    while cur is not None:
        if cur in seen:
            raise UntrustedRootError(f"cycle in key-history chain at epoch={cur}")
        seen.add(cur)
        link = anchors.links.get(cur)
        if link is None:
            raise AnchorDivergenceError(
                f"chain broken at epoch={cur}; re-materialize issuer={anchors.issuer}"
            )
        if link.pubkey_fp == anchors.pinned_root_fp:
            return link.pubkey_fp
        if not _verify_link_sig(link):
            raise UntrustedRootError(
                f"unsigned next-pointer at epoch={cur}; chain untrustworthy"
            )
        cur = link.next_epoch

    raise UntrustedRootError(
        f"epoch={claimed_epoch} chain did not terminate at pinned root "
        f"{anchors.pinned_root_fp}"
    )
