# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-a-delegated-warrant-after-its-parent-warrant-was-revoked-mid-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-a-delegated-warrant-after-its-parent-warrant-was-revoked-mid-chain.warrant.json
# Markdown SHA-256:   c941e3d773c5d5ae2bf7ac37f92981b5dee635e9c5a8d1b1015243f8cb27a7d5
# Code AST SHA-256:   4dc78cbe8abe112323d431d3a2cf138fcf1a5ce89430d36f6384ae89adb34f3f
# Verified Classes:   OrphanedWarrantError, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class OrphanedWarrantError(RuntimeError):
    """Raised when a warrant's lineage cannot be validated against the issuer's
    authoritative revocation set within the propagation SLA."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    chain_id: str
    issued_at: float          # seconds since epoch, IMMUTABLE across refresh
    ttl: float
    scope: frozenset[str]
    provenance: Sequence["Warrant"]   # ancestors, oldest first


def verify_lineage(
    leaf: Warrant,
    now: float,
    revocation_sla: float,
    is_revoked,               # callable: warrant_id -> bool, hits issuer
    max_depth: int = 8,
) -> None:
    """Full-chain validation. Fails closed on any ancestor that is revoked or
    whose age exceeds the revocation-propagation SLA.

    The key invariant: a refresh may extend the leaf's ttl, but the oldest
    ancestor's issued_at is immutable, so the lineage's trust horizon is
    bounded by the SLA regardless of how many times the leaf was re-signed.
    """
    chain = list(leaf.provenance) + [leaf]
    if len(chain) > max_depth:
        raise OrphanedWarrantError(
            f"chain depth {len(chain)} exceeds max_depth {max_depth}"
        )

    # Immutability check: every ancestor must predate or equal its child.
    for parent, child in zip(chain, chain[1:]):
        if parent.issued_at > child.issued_at:
            raise OrphanedWarrantError(
                f"provenance timestamp inversion: {parent.warrant_id} "
                f"({parent.issued_at}) > {child.warrant_id} ({child.issued_at})"
            )

    root = chain[0]
    lineage_age = now - root.issued_at
    if lineage_age > revocation_sla:
        # The root predates the issuer's revocation-propagation horizon.
        # We cannot prove it is unrevoked; fail closed.
        raise OrphanedWarrantError(
            f"lineage root {root.warrant_id} age {lineage_age:.1f}s "
            f"exceeds revocation SLA {revocation_sla:.1f}s; "
            f"cannot validate {leaf.warrant_id}"
        )

    for w in chain:
        if is_revoked(w.warrant_id):
            raise OrphanedWarrantError(
                f"warrant {w.warrant_id} in lineage of {leaf.warrant_id} is revoked"
            )

    if leaf.issued_at + leaf.ttl <= now:
        raise OrphanedWarrantError(
            f"leaf {leaf.warrant_id} expired at {leaf.issued_at + leaf.ttl}"
        )


def refresh_warrant(
    leaf: Warrant,
    now: float,
    new_ttl: float,
    revocation_sla: float,
    is_revoked,
) -> Warrant:
    """Re-sign the leaf with a fresh ttl WITHOUT extending the lineage horizon.

    provenance and root issued_at are copied verbatim; the verifier's SLA check
    on the root's immutable issued_at is what bounds authority after revocation.
    """
    verify_lineage(leaf, now, revocation_sla, is_revoked)  # mint-time gate
    return Warrant(
        warrant_id=leaf.warrant_id + f":r{int(now)}",
        chain_id=leaf.chain_id,
        issued_at=leaf.issued_at,      # immutable across refresh
        ttl=new_ttl,
        scope=leaf.scope,
        provenance=leaf.provenance,    # verbatim; root age is the bound
    )
