# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-inherit-a-delegated-identity-the-depth-bounded-warrant-chain-and-its-silent-collapse-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-inherit-a-delegated-identity-the-depth-bounded-warrant-chain-and-its-silent-collapse-invariant.warrant.json
# Markdown SHA-256:   7a85aadb092a6288c96551800d5ec9e27322f57544a53d8df03e2a4af7253d24
# Code AST SHA-256:   449b483eee0aa7d2834d6e9cd434110c156e4d59670ab0b400d52ae44e6c0485
# Verified Classes:   IdentityChainError, ParentWarrantAbsent, UnverifiableChain, DepthExceeded, Warrant
# Defensive Guards:   11 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class IdentityChainError(RuntimeError):
    """Base for identity lifecycle failures."""


class ParentWarrantAbsent(IdentityChainError):
    """Raised when an instance tries to mint a delegated warrant without
    holding the signed parent warrant in active context."""


class UnverifiableChain(IdentityChainError):
    """Raised when a leaf warrant's parent_hash cannot be resolved to a
    verified ancestor. Distinct from impersonation; fails closed."""


class DepthExceeded(IdentityChainError):
    """Raised when a fully resolved chain exceeds the root's depth budget."""


@dataclass(frozen=True)
class Warrant:
    issuer_id: str
    issuer_version: int      # identity version at mint time
    iat: int                 # issued-at
    exp: int                 # expiry
    depth: int               # signed, monotonic, parent.depth + 1
    parent_hash: Optional[str]
    max_delegation_depth: int  # only meaningful on the root (depth 0)
    signature_valid: bool = True


def mint_child(parent: Optional[Warrant], now: int) -> Warrant:
    """Mint a delegated warrant. Refuses if parent is absent from context."""
    if parent is None:
        # The instance did not hold the signed parent artifact. It may
        # 'remember' the parameters, but memory is not a warrant.
        raise ParentWarrantAbsent(
            "cannot mint delegated warrant: parent warrant not in active context; "
            "refuse rather than re-derive depth from local reasoning"
        )
    if not parent.signature_valid:
        raise IdentityChainError("parent warrant signature invalid")
    if now > parent.exp:
        raise IdentityChainError("parent warrant expired at mint time")
    child_depth = parent.depth + 1
    # Depth is computed from the parent artifact, never re-derived.
    return Warrant(
        issuer_id=parent.issuer_id,
        issuer_version=parent.issuer_version,
        iat=now,
        exp=parent.exp,
        depth=child_depth,
        parent_hash=hash(parent),
        max_delegation_depth=parent.max_delegation_depth,
    )


def verify_chain(chain: list[Warrant], now: int) -> None:
    """Chain-complete verification. Leaf-only verification is insufficient."""
    if not chain:
        raise UnverifiableChain("empty chain")
    root = chain[0]
    if root.depth != 0 or root.parent_hash is not None:
        raise UnverifiableChain("chain root is not a depth-0 anchored warrant")
    for i, w in enumerate(chain):
        if not w.signature_valid:
            raise IdentityChainError(f"warrant {i} signature invalid")
        if not (w.iat <= now <= w.exp):
            raise IdentityChainError(f"warrant {i} outside validity window")
        # Rotation-aware: version-at-issue, not live-registry lookup.
        if w.issuer_version != root.issuer_version:
            raise IdentityChainError(
                f"warrant {i} issuer_version {w.issuer_version} != root "
                f"{root.issuer_version}; possible impersonation, not rotation"
            )
        if i > 0:
            if w.parent_hash != hash(chain[i - 1]):
                raise UnverifiableChain(
                    f"warrant {i} parent_hash does not resolve to verified ancestor"
                )
            if w.depth != chain[i - 1].depth + 1:
                raise IdentityChainError(
                    f"warrant {i} depth {w.depth} not monotonic from parent"
                )
    terminal_depth = chain[-1].depth
    if terminal_depth > root.max_delegation_depth:
        raise DepthExceeded(
            f"terminal depth {terminal_depth} exceeds root budget "
            f"{root.max_delegation_depth}"
        )
