# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-capability-attestation-whose-trust-score-is-still-valid-but-whose-supporting-evidence-has-aged-past-its-freshness-windo.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-capability-attestation-whose-trust-score-is-still-valid-but-whose-supporting-evidence-has-aged-past-its-freshness-windo.warrant.json
# Markdown SHA-256:   9cb51123e730666d2ed4f20af152e302723189e112cc3d8c439fe74967dbb729
# Code AST SHA-256:   e1c3cd0a52de7d19283d6497c14fb94f7562bd2a2c25dd41d00398a285b6ae5d
# Verified Classes:   StaleAttestationError, Evidence, Attestation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class StaleAttestationError(RuntimeError):
    """Raised when an attestation's score is in-band but its evidence is not consumable."""
    pass


@dataclass
class Evidence:
    evidence_id: str
    issued_at: float
    ttl: float
    payload_hash: str


@dataclass
class Attestation:
    subject: str
    capability: str
    trust_score: float
    score_valid_until: float
    computed_over_hash: str          # hash of the evidence set the score was derived from
    evidence: list = field(default_factory=list)


def evidence_set_hash(evidence: list) -> str:
    h = hashlib.sha256()
    for e in sorted(evidence, key=lambda x: x.evidence_id):
        h.update(f"{e.evidence_id}:{e.payload_hash}".encode())
    return h.hexdigest()


def assert_consumable(att: Attestation, now: float, threshold: float = 0.85) -> None:
    # 1. Score band
    if att.trust_score < threshold:
        raise StaleAttestationError(
            f"score {att.trust_score} below threshold {threshold} for {att.subject}"
        )
    if now >= att.score_valid_until:
        raise StaleAttestationError(
            f"score expired at {att.score_valid_until} (now {now}) for {att.subject}"
        )

    # 2. Evidence-set pinning: score must describe the evidence we can resolve
    resolved_hash = evidence_set_hash(att.evidence)
    if resolved_hash != att.computed_over_hash:
        raise StaleAttestationError(
            f"evidence-set hash mismatch for {att.subject}: "
            f"score computed over {att.computed_over_hash}, resolved {resolved_hash}"
        )

    # 3. Per-item freshness — checked even though score is in-band
    stale = [e.evidence_id for e in att.evidence if now >= e.issued_at + e.ttl]
    if stale:
        raise StaleAttestationError(
            f"score in-band but evidence past TTL for {att.subject}: {stale}; "
            f"re-attestation required before dispatch"
        )


def dispatch_gate(att: Attestation, now: float, idempotent: bool,
                  destructive: bool, grace: float = 0.0) -> str:
    try:
        assert_consumable(att, now)
        return "consume"
    except StaleAttestationError as exc:
        # Bounded grace only for non-destructive idempotent work
        stale_items = [e for e in att.evidence if now >= e.issued_at + e.ttl]
        if stale_items and idempotent and not destructive and grace > 0.0:
            worst = max(now - (e.issued_at + e.ttl) for e in stale_items)
            if worst <= grace:
                return "consume_under_grace"
        raise StaleAttestationError(
            f"dispatch blocked for {att.subject}: {exc}"
        ) from exc
