# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trust-anchor-expiry-skew-in-cross-org-agent-federation-credential-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trust-anchor-expiry-skew-in-cross-org-agent-federation-credential-chains.warrant.json
# Markdown SHA-256:   37d1de058d95865417658ca9b71d7365a63066ff5e5db508a88ec0c71315ed22
# Code AST SHA-256:   abc3a838d55a0e370de69b284d3ae8167adc3ea44a55e47eb32be2ad2b39fc2c
# Verified Classes:   AnchorTrustError, AnchorPin, PresentedAnchor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AnchorTrustError(RuntimeError):
    """Raised when a presented trust anchor cannot be adjudicated against the pinned policy."""


@dataclass(frozen=True)
class AnchorPin:
    fingerprint: str
    not_after: str          # ISO-8601
    supersedes: Optional[str] = None   # prior fingerprint, or None for genesis


@dataclass(frozen=True)
class PresentedAnchor:
    fingerprint: str
    issuer: str             # DID string -- locator, NOT identity
    not_after: str


def adjudicate_anchor(
    presented: PresentedAnchor,
    pins: dict[str, AnchorPin],
    now_iso: str,
) -> str:
    """
    Returns 'accept' or 'quarantine'. Never returns 'accept' on issuer-string match.
    Raises AnchorTrustError when the presented anchor is unpinned and no live pin
    can justify a quarantine (i.e., it looks like forgery).
    """
    if presented.fingerprint in pins:
        pin = pins[presented.fingerprint]
        # Pinned and live: the normal path.
        return "accept" if now_iso <= pin.not_after else "quarantine"

    # Walk the signed supersession chain from any pinned anchor.
    for fp, pin in pins.items():
        cursor = pin
        seen = {fp}
        while cursor.supersedes is not None:
            if cursor.supersedes in seen:
                raise AnchorTrustError(
                    f"supersession cycle detected at {cursor.supersedes}"
                )
            seen.add(cursor.supersedes)
            nxt = pins.get(cursor.supersedes)
            if nxt is None:
                break
            if nxt.fingerprint == presented.fingerprint:
                # Presented anchor is a signed descendant of a pinned anchor.
                return "accept"
            cursor = nxt

    # Not pinned, not in any supersession chain. Decide by pin liveness.
    any_live = any(now_iso <= p.not_after for p in pins.values())
    if any_live:
        # A live pin exists and does not cover this anchor: treat as forgery.
        raise AnchorTrustError(
            f"presented anchor {presented.fingerprint} "
            f"(issuer={presented.issuer}) is not in any supersession chain "
            f"and a live pin exists; refusing issuer-string fallback"
        )
    # All pins stale: cannot adjudicate, must re-exchange policy.
    return "quarantine"


def verify_federation_chain(
    presented: PresentedAnchor,
    pins: dict[str, AnchorPin],
    now_iso: str,
) -> None:
    verdict = adjudicate_anchor(presented, pins, now_iso)
    if verdict == "quarantine":
        raise AnchorTrustError(
            f"anchor {presented.fingerprint} quarantined: policy re-exchange required"
        )
