# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-attestation-decay-at-a-federation-trust-broker-when-capability-warrants-outlive-the-policy-epoch-that-issued-them.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-attestation-decay-at-a-federation-trust-broker-when-capability-warrants-outlive-the-policy-epoch-that-issued-them.warrant.json
# Markdown SHA-256:   f7a812540329177ab69d60cb95765ea13af7140bf7ce979051b80325bb1b7331
# Code AST SHA-256:   63e1a15e30c755056f212cd037318d7eff778803d105bb0aae8cac9a7d60b8aa
# Verified Classes:   AttestationDecayError, Warrant, EpochAttestation
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class AttestationDecayError(RuntimeError):
    """Raised when a warrant's policy binding no longer matches the broker's current epoch."""


@dataclass(frozen=True)
class Warrant:
    subject_org: str
    capability: str
    claims: dict
    policy_hash: str          # hash(policy(epoch)) at mint time; first-class, not opaque ext
    exp: float
    signature_ok: bool


@dataclass(frozen=True)
class EpochAttestation:
    epoch: int
    policy_hash: str
    issued_at: float
    ttl: float
    signature_ok: bool

    def is_fresh(self, now: float) -> bool:
        return (now - self.issued_at) < self.ttl


def _hash_policy(policy_text: str) -> str:
    return hashlib.sha256(policy_text.encode()).hexdigest()


def authorize_execution(
    warrant: Warrant,
    action: str,
    epoch_att: EpochAttestation | None,
    now: float,
    mutating: bool,
) -> bool:
    # Token integrity and temporal validity: necessary, never sufficient.
    if not warrant.signature_ok:
        raise AttestationDecayError(f"warrant signature invalid for {warrant.capability}")
    if now >= warrant.exp:
        raise AttestationDecayError(f"warrant expired at {warrant.exp}, now={now}")
    if warrant.capability != action:
        raise AttestationDecayError(f"capability mismatch: {warrant.capability} != {action}")

    # Epoch binding is only required on the mutating path; reads may proceed on token alone.
    if not mutating:
        return True

    if epoch_att is None:
        raise AttestationDecayError(
            "no epoch attestation available; failing closed on mutating action"
        )
    if not epoch_att.signature_ok:
        raise AttestationDecayError("epoch attestation signature invalid")
    if not epoch_att.is_fresh(now):
        raise AttestationDecayError(
            f"epoch attestation stale: age={now - epoch_att.issued_at:.1f}s ttl={epoch_att.ttl}s"
        )

    # The predicate the naive federation omits: does the warrant's policy binding
    # match the broker's currently-endorsed policy?
    if warrant.policy_hash != epoch_att.policy_hash:
        raise AttestationDecayError(
            f"attestation decay: warrant bound to policy {warrant.policy_hash[:12]} "
            f"but broker epoch {epoch_att.epoch} endorses {epoch_att.policy_hash[:12]}"
        )

    # Semantic revalidation under the current epoch's reconciled policy.
    if not _recheck_under_current(warrant.claims, action):
        raise AttestationDecayError(
            f"claims {warrant.claims} fail recheck under epoch {epoch_att.epoch}"
        )
    return True


def _recheck_under_current(claims: dict, action: str) -> bool:
    # Placeholder for the reconciled-policy evaluator; the E18 rule in the trace
    # requires purpose=settlement for writes to the shared ledger.
    if action.startswith("filesystem.write:") and "/shared" in action:
        return claims.get("purpose") == "settlement" and claims.get(
            "data_classification"
        ) in ("restricted", "internal")
    return True


def replay_verdict(warrant: Warrant, action: str, policy_text: str) -> str:
    """Auditor-side replay: recompute the verdict under an explicit policy."""
    if _hash_policy(policy_text) != warrant.policy_hash:
        # Warrant was minted under a different policy than the one being replayed against.
        return "INDETERMINATE_EPOCH_MISMATCH"
    return "ALLOW" if _recheck_under_current(warrant.claims, action) else "DENY"
