# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-capability-grant-as-invalid-when-the-trust-anchor-rotates-mid-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-capability-grant-as-invalid-when-the-trust-anchor-rotates-mid-negotiation.warrant.json
# Markdown SHA-256:   b652b0b38c9dfaec493d8e9daa6aeec6f9660600dcf734019b1bef387f424d78
# Code AST SHA-256:   39ca0ee36ba21faaa5870a6154a995fe28f7938bf2ddaabb0dca3177a3c34bc4
# Verified Classes:   FederatedGrantInvalid, AnchorMetadata, CapabilityGrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class FederatedGrantInvalid(RuntimeError):
    """Raised when a capability grant cannot be honored under current anchor authority."""
    pass


@dataclass
class AnchorMetadata:
    org: str
    authoritative_epoch: int
    trusted_epochs: set
    overlap_window: tuple  # (start_ts, end_ts) during which rotation is in progress
    reattested_epochs: set = field(default_factory=set)


@dataclass
class CapabilityGrant:
    grantee: str
    scope: str
    issued_at: float
    anchor_epoch: Optional[int]   # None == legacy grant with no epoch binding
    signature_valid: bool
    reattested_by: Optional[int] = None


def verify_grant_for_handoff(grant: CapabilityGrant, meta: AnchorMetadata, now: float) -> bool:
    if not grant.signature_valid:
        raise FederatedGrantInvalid(
            f"signature invalid for grant scope={grant.scope!r}; refusing handoff"
        )

    # Legacy grant: no epoch binding. Safe only if no rotation is in progress
    # and only one trusted epoch exists for the issuer.
    if grant.anchor_epoch is None:
        in_overlap = meta.overlap_window[0] <= now <= meta.overlap_window[1]
        if in_overlap or len(meta.trusted_epochs) > 1:
            raise FederatedGrantInvalid(
                f"grant scope={grant.scope!r} has no anchor_epoch and issuer {meta.org!r} "
                f"is mid-rotation (trusted_epochs={sorted(meta.trusted_epochs)}, "
                f"overlap={meta.overlap_window}); cannot disambiguate authority"
            )
        return True

    # Epoch-bound grant: must match the authoritative epoch at issuance.
    if grant.anchor_epoch != meta.authoritative_epoch:
        if grant.anchor_epoch in meta.reattested_epochs:
            return True
        if grant.reattested_by == meta.authoritative_epoch:
            return True
        raise FederatedGrantInvalid(
            f"grant scope={grant.scope!r} issued under epoch {grant.anchor_epoch} "
            f"but authoritative epoch is {meta.authoritative_epoch} and grant "
            f"was not re-attested; superseded authority"
        )

    # Grant issued inside an overlap window under the *current* epoch is fine.
    return True


def exercise_grant(grant: CapabilityGrant, meta: AnchorMetadata, now: float) -> str:
    # Fail closed: any ambiguity on a cross-org boundary is a refusal.
    if not verify_grant_for_handoff(grant, meta, now):
        raise FederatedGrantInvalid("unreachable: verifier must raise, not return False")
    return f"admitted scope={grant.scope!r} epoch={grant.anchor_epoch}"
