# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-re-delegate-a-signed-a2a-capability-token-whose-attenuation-chain-is-intact-but-whose-warrant-identit.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-re-delegate-a-signed-a2a-capability-token-whose-attenuation-chain-is-intact-but-whose-warrant-identit.warrant.json
# Markdown SHA-256:   5432cb23b73e7cbb01c41f6f2d1d6659da200f6552f4f83a37e1f1d82c6900a2
# Code AST SHA-256:   b53db4aacc6188edc78baf92873a5afc90366cceb33a432010d6401330e2d525
# Verified Classes:   WarrantIdentityUnreconstructable, NonMonotoneCaveat, ChainLink, IdentityBinding
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class WarrantIdentityUnreconstructable(RuntimeError):
    """Raised when a token chain is integrity-valid but a link's warrant
    identity cannot be bound to a principal valid at mint time."""
    pass


class NonMonotoneCaveat(RuntimeError):
    """Raised when an appended caveat cannot be proven to attenuate scope."""
    pass


@dataclass
class ChainLink:
    holder_key: str
    minted_at: float
    caveat: str
    monotone_proven: bool


@dataclass
class IdentityBinding:
    holder_key: str
    principal: str
    valid_from: float
    valid_to: float


def reconstruct_warrant(
    link: ChainLink,
    bindings: list[IdentityBinding],
) -> Optional[str]:
    """Return the principal bound to this link's holder key *as of the
    link's minting time*, or None if no time-valid binding exists."""
    for b in bindings:
        if (
            b.holder_key == link.holder_key
            and b.valid_from <= link.minted_at <= b.valid_to
        ):
            return b.principal
    return None


def may_re_delegate(
    chain: list[ChainLink],
    bindings: list[IdentityBinding],
    min_chain_depth: int,
) -> bool:
    if len(chain) < min_chain_depth:
        # Elision and a legitimately short chain are indistinguishable here.
        raise WarrantIdentityUnreconstructable(
            f"chain depth {len(chain)} < required {min_chain_depth}; "
            "cannot distinguish transport elision from skipped delegation"
        )
    for link in chain:
        if not link.monotone_proven:
            raise NonMonotoneCaveat(
                f"caveat {link.caveat!r} from {link.holder_key} "
                "cannot be proven to attenuate"
            )
        principal = reconstruct_warrant(link, bindings)
        if principal is None:
            raise WarrantIdentityUnreconstructable(
                f"link held by {link.holder_key} minted at {link.minted_at} "
                "has no time-valid identity binding; "
                "integrity holds but warrant identity is unreconstructable"
            )
    return True


def delegate(chain, bindings, min_chain_depth, new_caveat):
    try:
        may_re_delegate(chain, bindings, min_chain_depth)
    except (WarrantIdentityUnreconstructable, NonMonotoneCaveat):
        # Execute under the token as received; do not extend it.
        raise
    return chain + [
        ChainLink(
            holder_key="self",
            minted_at=time.time(),
            caveat=new_caveat,
            monotone_proven=True,
        )
    ]
