# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-attestation-chain-stale-root-divergence-during-cross-org-agent-trust-bootstrapping.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-attestation-chain-stale-root-divergence-during-cross-org-agent-trust-bootstrapping.warrant.json
# Markdown SHA-256:   1ce4e900b6fcf5f290351dced3a7af277ad941a9dfd7e80d1a066f2cc408dcf2
# Code AST SHA-256:   20e41aa31fbe00f5a93e42d507a23d72f362496fe7c2a0197501302ea0fab6fb
# Verified Classes:   AnchorResolutionError, Transition, Chain
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional, Set


class AnchorResolutionError(RuntimeError):
    """Raised when a chain's terminal issuer cannot be resolved to a trusted anchor."""


@dataclass(frozen=True)
class Transition:
    old_root: str
    new_root: str
    not_before: float
    not_after: float
    signed_by_old_root: bool


@dataclass(frozen=True)
class Chain:
    terminal_issuer: str
    leaf_issued_at: float
    signatures_valid: bool


def resolve_anchor(
    chain: Chain,
    anchors: Set[str],
    transitions: dict[str, Transition],
    now: float,
) -> str:
    """Return 'Trusted' or 'Stale-root'. Raise on genuine untrusted-ness."""
    if chain.terminal_issuer in anchors:
        return "Trusted"

    # Terminal issuer unknown: is it a declared successor of a trusted anchor?
    for old_root in anchors:
        t = transitions.get(old_root)
        if t is None or t.new_root != chain.terminal_issuer:
            continue
        if not t.signed_by_old_root:
            # A transition not bound by the old root proves nothing.
            raise AnchorResolutionError(
                f"transition {t.old_root}->{t.new_root} lacks old-root signature"
            )
        if not (t.not_before <= now <= t.not_after):
            raise AnchorResolutionError(
                f"transition window closed at {t.not_after}, now={now}"
            )
        if not (t.not_before <= chain.leaf_issued_at <= t.not_after):
            raise AnchorResolutionError(
                f"leaf issued {chain.leaf_issued_at} outside overlap window"
            )
        return "Stale-root"

    # No trusted anchor and no valid transition: this is untrusted, period.
    raise AnchorResolutionError(
        f"terminal issuer {chain.terminal_issuer} has no path to a trusted anchor"
    )


def verify_chain(
    chain: Chain,
    anchors: Set[str],
    transitions: dict[str, Transition],
    now: float,
) -> str:
    # Anchor resolution MUST precede signature trust decisions.
    state = resolve_anchor(chain, anchors, transitions, now)
    if not chain.signatures_valid:
        # Only now is a signature failure unambiguously impersonation.
        raise AnchorResolutionError(
            f"signature invalid on chain rooted at {chain.terminal_issuer}"
        )
    if state == "Stale-root":
        # Caller is responsible for promoting the new root post-success.
        return "Stale-root"
    return "Trusted"
