# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-it-cannot-verify-against-its-own-trust-anchor-the-stale-warrant-replay-boundary-in-cross-org.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-it-cannot-verify-against-its-own-trust-anchor-the-stale-warrant-replay-boundary-in-cross-org.warrant.json
# Markdown SHA-256:   94d084ed1251058e4f4dfc31c63af83fd6c9e5627b093c809a54b550bb2548d4
# Code AST SHA-256:   da1794da2e4a95f288ad56318d86fcfdd30eb3a38eeb8b130aba1b6833858c09
# Verified Classes:   StaleWarrantRefused, TrustAnchor, CapabilityWarrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleWarrantRefused(RuntimeError):
    """Raised when a federated capability grant cannot be verified against a
    sufficiently fresh trust anchor. Refusal is mandatory, not advisory."""
    pass


@dataclass(frozen=True)
class TrustAnchor:
    org: str
    epoch: int
    fetched_at: float          # monotonic seconds
    valid_until: float         # monotonic seconds


@dataclass(frozen=True)
class CapabilityWarrant:
    subject: str
    capability: str
    not_after: float           # monotonic seconds
    anchor_epoch: int
    min_anchor_epoch: int      # peer's negotiation constraint


def honor_capability(
    warrant: CapabilityWarrant,
    anchor: TrustAnchor,
    now: float,
    max_anchor_age: float,
) -> bool:
    if anchor.org != warrant.subject.split(".")[0]:
        raise StaleWarrantRefused(
            f"anchor org {anchor.org} does not match warrant subject {warrant.subject}"
        )

    anchor_age = now - anchor.fetched_at
    if anchor_age > max_anchor_age:
        raise StaleWarrantRefused(
            f"anchor epoch {anchor.epoch} is {anchor_age:.1f}s old, "
            f"exceeds max_anchor_age {max_anchor_age:.1f}s; force synchronous refresh"
        )

    if anchor.epoch < warrant.min_anchor_epoch:
        raise StaleWarrantRefused(
            f"cached anchor epoch {anchor.epoch} < grant min_anchor_epoch "
            f"{warrant.min_anchor_epoch}; peer revocation state is ahead of us"
        )

    if warrant.anchor_epoch != anchor.epoch:
        raise StaleWarrantRefused(
            f"warrant signed under epoch {warrant.anchor_epoch}, "
            f"anchor is {anchor.epoch}; signature cannot bind to current trust state"
        )

    if not (anchor.fetched_at <= warrant.not_after <= anchor.valid_until):
        raise StaleWarrantRefused(
            f"warrant window [{now:.0f}, {warrant.not_after:.0f}] not contained "
            f"in anchor validity [{anchor.fetched_at:.0f}, {anchor.valid_until:.0f}]"
        )

    return True
