# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-federation-trust-decay-when-capability-grants-outlive-the-policy-that-authorized-them.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-federation-trust-decay-when-capability-grants-outlive-the-policy-that-authorized-them.warrant.json
# Markdown SHA-256:   9c316c759eb488253586ab7a111f55dc0bef5f0aa2e3907cf689d4e2d6514403
# Code AST SHA-256:   842b8ab016f332a396332b88cf820d0bbb2de84976bd3e1edb72278a0d11f410
# Verified Classes:   FederationTrustDecayError, Grant, PolicyAttestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class FederationTrustDecayError(RuntimeError):
    """Raised when a cached grant's policy basis can no longer be re-attested."""
    pass


@dataclass(frozen=True)
class Grant:
    issuer: str
    principal: str
    scope: str
    policy_version: str
    expires_at: float


@dataclass(frozen=True)
class PolicyAttestation:
    issuer: str
    principal: str
    scope: str
    policy_version: str
    effective_at: float
    signed_at: float


FRESHNESS_WINDOW = {
    "data.read:pii": 15 * 60,
    "data.read:meta": 60 * 60,
}


def usable_scopes(
    grant: Grant,
    attestation: Optional[PolicyAttestation],
    now: Optional[float] = None,
) -> set:
    now = now if now is not None else time.time()

    if now >= grant.expires_at:
        return set()

    if attestation is None:
        raise FederationTrustDecayError(
            f"no policy attestation for grant {grant.issuer}/{grant.principal} "
            f"scope={grant.scope} policy_version={grant.policy_version}; "
            f"treating as decayed (fail-closed)"
        )

    if attestation.issuer != grant.issuer or attestation.principal != grant.principal:
        raise FederationTrustDecayError(
            f"attestation identity mismatch for grant {grant.issuer}/{grant.principal}"
        )

    window = FRESHNESS_WINDOW.get(grant.scope)
    if window is None:
        raise FederationTrustDecayError(
            f"no freshness window defined for scope {grant.scope}; refusing to act"
        )

    if now - attestation.signed_at > window:
        raise FederationTrustDecayError(
            f"attestation for {grant.scope} is stale "
            f"({now - attestation.signed_at:.0f}s > {window}s)"
        )

    if attestation.policy_version != grant.policy_version:
        # Policy basis changed: degrade to empty scope set for this scope.
        return set()

    if attestation.effective_at > grant.expires_at:
        return set()

    return {grant.scope}
