# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-transitive-trust-inflation-when-a-federation-broker-re-signs-delegated-capability-warrants-across-organizati.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-transitive-trust-inflation-when-a-federation-broker-re-signs-delegated-capability-warrants-across-organizati.warrant.json
# Markdown SHA-256:   07fc7719a687e454dcc39e39ff063d79312d58435f809e2aeb50668d850b885f
# Code AST SHA-256:   1d0787dc7b969788128a6fbde0a9afddfbad199f1f81ae130c7d0704790dee4c
# Verified Classes:   TrustInflationError, ChainLink, Warrant
# Defensive Guards:   10 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TrustInflationError(RuntimeError):
    """Raised when a warrant's chain cannot be reconstructed to a trusted root."""
    pass


@dataclass(frozen=True)
class ChainLink:
    issuer: str
    scope: frozenset
    depth_budget: int
    expiry: int
    parent_hash: Optional[str]


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    scope: frozenset
    depth_budget: int
    expiry: int
    chain: tuple = field(default_factory=tuple)


TRUSTED_ROOTS = {"org-a-root"}
TRUSTED_BROKERS = {"org-b-broker", "org-c-broker"}


def evaluate(w: Warrant, now: int) -> frozenset:
    # A chainless warrant is only valid if its issuer is a root.
    if not w.chain:
        if w.issuer not in TRUSTED_ROOTS:
            raise TrustInflationError(
                f"chainless warrant from non-root issuer {w.issuer!r}: "
                f"broker re-signing detected, effective authority unbounded"
            )
        if w.expiry <= now:
            raise TrustInflationError(f"root warrant expired at {w.expiry}")
        return w.scope

    # Reconstruct: chain must terminate at a trusted root and be contiguous.
    if w.chain[0].issuer not in TRUSTED_ROOTS:
        raise TrustInflationError(
            f"chain does not terminate at trusted root: head issuer "
            f"{w.chain[0].issuer!r}"
        )
    for i in range(1, len(w.chain)):
        prev, cur = w.chain[i - 1], w.chain[i]
        if cur.issuer not in TRUSTED_BROKERS:
            raise TrustInflationError(
                f"chain link {i} issuer {cur.issuer!r} is not a trusted broker"
            )
        if cur.parent_hash is None:
            raise TrustInflationError(
                f"chain link {i} missing parent_hash: broker dropped chain "
                f"continuity, attenuation cannot be verified"
            )
        if cur.depth_budget >= prev.depth_budget:
            raise TrustInflationError(
                f"chain link {i} depth {cur.depth_budget} not strictly less "
                f"than parent {prev.depth_budget}: depth reset detected"
            )
        if cur.expiry > prev.expiry:
            raise TrustInflationError(
                f"chain link {i} expiry {cur.expiry} exceeds parent "
                f"{prev.expiry}: expiry extension detected"
            )
        if not cur.scope.issubset(prev.scope):
            raise TrustInflationError(
                f"chain link {i} scope {set(cur.scope)} not subset of parent "
                f"{set(prev.scope)}: scope union detected"
            )

    effective = w.scope
    for link in w.chain:
        effective = effective & link.scope
    effective_expiry = min(link.expiry for link in w.chain)
    if effective_expiry <= now:
        raise TrustInflationError(
            f"effective expiry {effective_expiry} already passed at {now}: "
            f"revocation lag across broker boundary"
        )
    if not effective:
        raise TrustInflationError("effective scope empty after intersection")
    return effective
