# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-brokered-federated-capability-warrant-at-the-point-of-use-rather-than-at-issuance.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-brokered-federated-capability-warrant-at-the-point-of-use-rather-than-at-issuance.warrant.json
# Markdown SHA-256:   6a7b0f5b59e2d9edd007997ba24e54c7e61c929a90df3d715a948930fd7a7715
# Code AST SHA-256:   cd755a79ba48c3d29bdae0608b4428a64868eabcb7eb8c16a0e7c4a0e8a69836
# Verified Classes:   WarrantUnusableAtUse, PolicyUndecidable, Warrant, ReceiverPolicy
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class WarrantUnusableAtUse(RuntimeError):
    """Raised when a cryptographically valid warrant cannot be re-evaluated
    under the receiving domain's current policy epoch and must be rejected
    before any side effect is attempted."""


class PolicyUndecidable(WarrantUnusableAtUse):
    """The receiver's policy is a partial function over (chain, scope, epoch)."""


@dataclass(frozen=True)
class Warrant:
    subject: str
    scope: str
    chain: tuple[str, ...]          # full delegation chain, not just a depth int
    policy_epoch_at_issuance: str
    not_after: float
    signature_valid: bool


@dataclass(frozen=True)
class ReceiverPolicy:
    epoch: str
    epoch_sensitive_scopes: frozenset[str]

    def evaluate(self, chain: tuple[str, ...], scope: str, epoch: str) -> Optional[bool]:
        # Returns True=permit, False=deny, None=undecidable.
        if scope not in self.epoch_sensitive_scopes:
            return True
        cross_org_hops = sum(1 for hop in chain if not hop.startswith("beta."))
        if cross_org_hops >= 2 and epoch >= "beta-epoch-442":
            return False
        if cross_org_hops < 2:
            return True
        return None  # partial policy — must not be read as permit


def admit_at_use(
    warrant: Warrant,
    policy: ReceiverPolicy,
    now: float,
    *,
    epoch_available: bool = True,
) -> bool:
    if not warrant.signature_valid:
        raise WarrantUnusableAtUse(f"bad signature on warrant for {warrant.subject}")
    if now > warrant.not_after:
        raise WarrantUnusableAtUse(f"warrant expired for {warrant.subject}")
    if not epoch_available:
        raise WarrantUnusableAtUse(
            "receiver epoch unavailable; refusing to admit on cached/stale epoch"
        )

    epoch_sensitive = warrant.scope in policy.epoch_sensitive_scopes
    epochs_match = warrant.policy_epoch_at_issuance == policy.epoch

    if not epoch_sensitive and epochs_match:
        return True  # verify-only sufficient

    # Re-evaluate under the receiver's current epoch, not the broker's.
    decision = policy.evaluate(warrant.chain, warrant.scope, policy.epoch)
    if decision is None:
        raise PolicyUndecidable(
            f"policy undecidable for chain={warrant.chain} scope={warrant.scope} "
            f"epoch={policy.epoch}; refusing before side effect"
        )
    if decision is False:
        raise WarrantUnusableAtUse(
            f"valid warrant unusable at use: issuance_epoch="
            f"{warrant.policy_epoch_at_issuance} receiver_epoch={policy.epoch} "
            f"chain={warrant.chain}"
        )
    return True
