# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-negotiated-capability-grant-the-federation-audit-epoch-skew-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-negotiated-capability-grant-the-federation-audit-epoch-skew-boundary.warrant.json
# Markdown SHA-256:   2e016df0a2d620e9baea76e8f1c4c0c15add3ecaddfd1f097ce8cfee65f41234
# Code AST SHA-256:   d0eb67b89e8ed0f4b129ed77835bd5c1e85dfc55b38941bfa93adee5291e7a20
# Verified Classes:   UnreconciledGrantError, CapabilityGrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class UnreconciledGrantError(RuntimeError):
    """Raised when a capability would be exercised before its grant is durable
    in the granting org's audit trail."""
    pass


@dataclass
class CapabilityGrant:
    capability_id: str
    grantor_org: str
    grantee_org: str
    issued_at: float
    ttl_seconds: float
    durable_seq: int | None      # None until grantor acknowledges audit durability
    grantor_max_flush_delay: float
    grantor_epoch: float


def assert_grant_usable(grant: CapabilityGrant, now: float | None = None) -> None:
    now = time.monotonic() if now is None else now
    age = now - grant.issued_at

    if age >= grant.ttl_seconds:
        raise UnreconciledGrantError(
            f"capability {grant.capability_id} expired before use "
            f"(age={age:.1f}s, ttl={grant.ttl_seconds:.1f}s)"
        )

    # Path (a): grantor acknowledged durability.
    if grant.durable_seq is not None:
        return

    # Path (b): TTL covers max flush delay + one full epoch, so any
    # re-evaluation during the capability's life must see the record.
    safe_horizon = grant.grantor_max_flush_delay + grant.grantor_epoch
    if grant.ttl_seconds >= safe_horizon:
        return

    raise UnreconciledGrantError(
        f"capability {grant.capability_id} from {grant.grantor_org} is unreconciled: "
        f"no durable_seq and ttl={grant.ttl_seconds:.1f}s < safe_horizon="
        f"{safe_horizon:.1f}s (max_flush_delay={grant.grantor_max_flush_delay:.1f}s, "
        f"epoch={grant.grantor_epoch:.1f}s); refusing use to avoid a false violation"
    )


def exercise_capability(grant: CapabilityGrant, call, now: float | None = None):
    assert_grant_usable(grant, now=now)
    return call(grant.capability_id)
