# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-a-peer-s-trust-anchor-against-its-own-policy-epoch-before-accepting-a-capability-grant-in-cross-org-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-a-peer-s-trust-anchor-against-its-own-policy-epoch-before-accepting-a-capability-grant-in-cross-org-federation.warrant.json
# Markdown SHA-256:   b4ff60592b6eb7ab98156893838431020d0a5b978706e35823f6b85ea3e996c7
# Code AST SHA-256:   890f90a2b7bc7700b336e2aba436fbfe8f9df68de05d28615acea737a3846af2
# Verified Classes:   PolicyEpochSkewError, TrustAnchor, CapabilityGrant, LocalPolicy
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class PolicyEpochSkewError(RuntimeError):
    """Raised when a capability grant's anchor epoch cannot be reconciled
    against the receiving instance's cached trust anchor and local policy epoch."""


@dataclass(frozen=True)
class TrustAnchor:
    org_id: str
    policy_epoch: int
    public_key_fingerprint: str
    not_after_unix: int


@dataclass(frozen=True)
class CapabilityGrant:
    grant_id: str
    issuer_org: str
    anchor_epoch: int
    scope: str
    signature_valid: bool


@dataclass(frozen=True)
class LocalPolicy:
    min_anchor_epoch: int


def authorize_grant(
    grant: CapabilityGrant,
    cached_anchor: Optional[TrustAnchor],
    local_policy: LocalPolicy,
    now_unix: int,
) -> bool:
    if not grant.signature_valid:
        raise PolicyEpochSkewError(
            f"grant {grant.grant_id} signature invalid; cannot authorize"
        )
    if cached_anchor is None:
        raise PolicyEpochSkewError(
            f"grant {grant.grant_id} received with no cached anchor for "
            f"{grant.issuer_org}; refresh required before evaluation"
        )
    if cached_anchor.not_after_unix <= now_unix:
        raise PolicyEpochSkewError(
            f"cached anchor for {grant.issuer_org} expired at "
            f"{cached_anchor.not_after_unix}; refresh required"
        )

    # The core boundary: never evaluate a grant against an anchor binding
    # whose epoch differs from the grant's claimed epoch.
    if grant.anchor_epoch > cached_anchor.policy_epoch:
        raise PolicyEpochSkewError(
            f"grant {grant.grant_id} claims anchor_epoch={grant.anchor_epoch} "
            f"but local cache holds epoch={cached_anchor.policy_epoch}; "
            f"grant is unverifiable until anchor refresh — do not evaluate "
            f"scope against stale binding"
        )
    if grant.anchor_epoch < cached_anchor.policy_epoch:
        raise PolicyEpochSkewError(
            f"grant {grant.grant_id} anchor_epoch={grant.anchor_epoch} is "
            f"older than cached epoch={cached_anchor.policy_epoch}; grant is "
            f"stale and must be re-negotiated"
        )
    if cached_anchor.policy_epoch < local_policy.min_anchor_epoch:
        raise PolicyEpochSkewError(
            f"cached anchor epoch={cached_anchor.policy_epoch} below local "
            f"policy minimum {local_policy.min_anchor_epoch}; refuse to "
            f"authorize under under-provisioned anchor"
        )

    # Epochs reconciled; scope evaluation is now sound.
    return True


def handle_handoff(
    grant: CapabilityGrant,
    cached_anchor: Optional[TrustAnchor],
    local_policy: LocalPolicy,
    now_unix: int,
) -> str:
    try:
        authorize_grant(grant, cached_anchor, local_policy, now_unix)
    except PolicyEpochSkewError as exc:
        # Typed block: checkpoint as blocked_on_anchor_refresh, NOT as a
        # transport fault. Prevents retry-loop poisoning and belief drift.
        return f"blocked_on_anchor_refresh: {exc}"
    return "authorized"
