# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-severed-delegation-chain-when-cross-org-attestation-caching-diverges.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-severed-delegation-chain-when-cross-org-attestation-caching-diverges.warrant.json
# Markdown SHA-256:   9fbef3dbf246785ab6cb4b4595440c48c26ef3d5e57c8b250823a7a243e0a729
# Code AST SHA-256:   6065e3a7f02a96ddf8105b4ac039989cf6356419e367e7a47c7914fb4a9015e4
# Verified Classes:   SeveredDelegationChainError, AttestationRoot, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta


class SeveredDelegationChainError(RuntimeError):
    """Raised when a warrant's issuance epoch cannot be bound to a cached attestation root,
    or when hops in a chain resolve the same warrant to different roots."""
    pass


@dataclass(frozen=True)
class AttestationRoot:
    key_id: str
    not_before: datetime
    not_after: datetime


@dataclass(frozen=True)
class Warrant:
    issuer_key_id: str
    issued_at: datetime
    signature_valid: bool


def verify_cross_org_warrant(
    warrant: Warrant,
    cached_roots: list[AttestationRoot],
    downstream_root_key_ids: set[str] | None = None,
    max_anchor_staleness: timedelta = timedelta(hours=6),
    now: datetime | None = None,
) -> AttestationRoot:
    """Resolve a warrant to a root, or raise on severance / split-brain.

    The decision boundary: a signature mismatch is ambiguous until the warrant's
    issuance epoch is compared against each cached root's validity interval.
    """
    now = now or datetime.utcnow()

    # Find the root whose validity interval covers the warrant's issuance epoch.
    covering = [r for r in cached_roots if r.not_before <= warrant.issued_at <= r.not_after]

    # Anchor freshness floor: if every cached root is older than the max staleness
    # relative to the warrant epoch, we cannot rule out a rotation we missed.
    if not covering:
        raise SeveredDelegationChainError(
            f"No cached root covers warrant issued_at={warrant.issued_at.isoformat()}; "
            f"cached roots: {[(r.key_id, r.not_before, r.not_after) for r in cached_roots]}. "
            f"Refresh the issuer root set before retrying the warrant."
        )

    # If multiple roots cover the epoch (grace overlap), pick the one matching the issuer key.
    matching = [r for r in covering if r.key_id == warrant.issuer_key_id]
    if not matching:
        # Epoch is covered but by a different key -> genuine severance or forgery.
        raise SeveredDelegationChainError(
            f"Warrant issuer_key_id={warrant.issuer_key_id} not among roots covering "
            f"issued_at={warrant.issued_at.isoformat()}; possible forgery or severed chain."
        )

    resolved = matching[0]

    # Staleness floor: the resolved root must have been fetched recently enough that
    # we would have observed any rotation before the warrant epoch.
    if now - resolved.not_before > max_anchor_staleness + (now - warrant.issued_at):
        raise SeveredDelegationChainError(
            f"Resolved root {resolved.key_id} is stale relative to warrant epoch; "
            f"anchor freshness floor violated."
        )

    if not warrant.signature_valid:
        # Signature invalid but epoch binds cleanly -> the warrant itself is bad,
        # not the anchor. Still a hard stop; do not retry the warrant.
        raise SeveredDelegationChainError(
            f"Warrant signature invalid under resolved root {resolved.key_id}; "
            f"epoch binds, so this is not a stale-anchor condition."
        )

    # Split-brain guard: every hop that will re-verify must resolve to the same root.
    if downstream_root_key_ids is not None and resolved.key_id not in downstream_root_key_ids:
        raise SeveredDelegationChainError(
            f"Split-brain: this hop resolved {resolved.key_id} but downstream hops hold "
            f"{sorted(downstream_root_key_ids)}. Propagate the resolved root set in the handoff."
        )

    return resolved
