# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-lose-its-delegation-chain-when-an-aaif-warrant-is-re-signed-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-lose-its-delegation-chain-when-an-aaif-warrant-is-re-signed-mid-handoff.warrant.json
# Markdown SHA-256:   2d4ce3857573a8f12aa657227ce95a5bf6ef612d904a3b66d981c75b121ff0cc
# Code AST SHA-256:   3285b1bebc1f3a015bcc7be4b4aede2eea5d8d56766dd25f5dfb20e47a772d25
# Verified Classes:   ChainIntegrityError, Warrant, WarrantStore
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ChainIntegrityError(RuntimeError):
    """Raised when a warrant chain cannot be verified as a contiguous,
    hash-linked, scope-monotonic sequence."""
    pass


@dataclass(frozen=True)
class Warrant:
    jti: str
    iss: str
    sub: str
    aud: str
    scope: frozenset
    exp: int
    chain_gen: int
    parent_hash: str | None
    signature: bytes = field(default=b"", compare=False)

    def canonical_hash(self) -> str:
        # Bytes that descendants commit to via parent_hash.
        body = f"{self.jti}|{self.iss}|{self.sub}|{self.aud}|" \
               f"{','.join(sorted(self.scope))}|{self.exp}|" \
               f"{self.chain_gen}|{self.parent_hash}"
        return hashlib.sha256(body.encode()).hexdigest()


class WarrantStore:
    def __init__(self):
        self._by_hash: dict[str, Warrant] = {}

    def put(self, w: Warrant) -> None:
        self._by_hash[w.canonical_hash()] = w

    def resolve(self, h: str) -> Warrant | None:
        return self._by_hash.get(h)


def verify_chain(presented: Warrant, store: WarrantStore, now: int) -> frozenset:
    """Walk ancestors by hash; intersect scopes; fail closed on any gap."""
    effective = presented.scope
    link = presented
    seen_gens: list[int] = [link.chain_gen]

    while link.parent_hash is not None:
        parent = store.resolve(link.parent_hash)
        if parent is None:
            # The observed failure: a re-signed ancestor changed bytes,
            # so the recorded parent_hash no longer resolves. We must NOT
            # fall back to trusting link.signature as a detached root.
            raise ChainIntegrityError(
                f"parent_hash {link.parent_hash[:12]}… unresolvable for "
                f"warrant {link.jti} (iss={link.iss}); chain broken — "
                f"ancestor likely re-signed in place"
            )
        if not link.scope <= parent.scope:
            raise ChainIntegrityError(
                f"scope escalation: {link.jti} grants {link.scope} "
                f"not subset of parent {parent.jti} {parent.scope}"
            )
        if link.chain_gen < parent.chain_gen:
            raise ChainIntegrityError(
                f"chain_gen regression at {link.jti}: "
                f"{link.chain_gen} < parent {parent.chain_gen}"
            )
        if link.exp > parent.exp:
            raise ChainIntegrityError(
                f"expiry inversion at {link.jti}: {link.exp} > parent {parent.exp}"
            )
        effective = effective & parent.scope
        seen_gens.append(parent.chain_gen)
        link = parent

    if now >= presented.exp:
        raise ChainIntegrityError(f"warrant {presented.jti} expired at {presented.exp}")

    # chain_gen must be monotonically non-decreasing root -> leaf.
    if seen_gens != sorted(seen_gens):
        raise ChainIntegrityError(
            f"non-monotonic chain_gen across chain: {seen_gens}"
        )
    return effective


def refresh_warrant(w: Warrant, new_exp: int, descendants_exist: bool) -> Warrant:
    """Re-sign in place is only legal for leaves. Interior nodes must
    re-issue the subtree so descendants' parent_hash commitments stay valid."""
    if descendants_exist:
        raise ChainIntegrityError(
            f"refusing to re-sign interior warrant {w.jti}: descendants hold "
            f"parent_hash={w.canonical_hash()[:12]}…; re-issue subtree with "
            f"chain_gen={w.chain_gen + 1} instead"
        )
    return Warrant(
        jti=w.jti, iss=w.iss, sub=w.sub, aud=w.aud, scope=w.scope,
        exp=new_exp, chain_gen=w.chain_gen, parent_hash=w.parent_hash,
        signature=b"<re-signed>",
    )
