# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-validate-delegated-capability-tokens-when-cross-issuer-trust-chains-bifurcate-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-validate-delegated-capability-tokens-when-cross-issuer-trust-chains-bifurcate-mid-handoff.warrant.json
# Markdown SHA-256:   a65f3ceb7d6873f147e40ebbbccb2fdb8e7616e8a5fbf2b31e1d5542a8c2352b
# Code AST SHA-256:   caa6195abffafe44bae3a236ae4badfcea9fe2f1dd035483abae65ee8b127497
# Verified Classes:   TrustChainBifurcationError, Constraint, DelegatedToken
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class TrustChainBifurcationError(RuntimeError):
    """Raised when a multi-issuer delegation envelope cannot be safely composed."""
    pass

@dataclass(frozen=True)
class Constraint:
    # None means unconstrained (lattice bottom). A concrete value means pinned.
    tenant: Optional[str] = None
    region: Optional[str] = None

    def intersect(self, other: "Constraint") -> "Constraint":
        def meet(a, b):
            if a is None: return b
            if b is None: return a
            if a != b:
                raise TrustChainBifurcationError(
                    f"constraint conflict: {a!r} vs {b!r}"
                )
            return a
        return Constraint(
            tenant=meet(self.tenant, other.tenant),
            region=meet(self.region, other.region),
        )

@dataclass(frozen=True)
class DelegatedToken:
    issuer: str
    schema_version: str
    constraint: Constraint
    max_calls: int
    expires_at: int

def compose_envelope(tokens: list[DelegatedToken], now: int) -> tuple[Constraint, int, int]:
    if not tokens:
        raise TrustChainBifurcationError("empty envelope: no attesting tokens")
    versions = {t.schema_version for t in tokens}
    if len(versions) > 1:
        raise TrustChainBifurcationError(
            f"schema mismatch across issuers: {sorted(versions)}"
        )
    composed = Constraint()
    budget = min(t.max_calls for t in tokens)
    expiry = min(t.expires_at for t in tokens)
    for t in tokens:
        if t.expires_at <= now:
            raise TrustChainBifurcationError(
                f"token from {t.issuer} expired at {t.expires_at}"
            )
        composed = composed.intersect(t.constraint)
    return composed, budget, expiry

def authorize_call(
    tokens: list[DelegatedToken],
    now: int,
    call_tenant: str,
    call_region: str,
    calls_used: int,
) -> None:
    composed, budget, _ = compose_envelope(tokens, now)
    if calls_used >= budget:
        raise TrustChainBifurcationError(
            f"call budget exhausted: {calls_used}/{budget}"
        )
    if composed.tenant is not None and composed.tenant != call_tenant:
        raise TrustChainBifurcationError(
            f"call tenant {call_tenant!r} violates composed constraint {composed.tenant!r}"
        )
    if composed.region is not None and composed.region != call_region:
        raise TrustChainBifurcationError(
            f"call region {call_region!r} violates composed constraint {composed.region!r}"
        )
