# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-peer-s-agent-card-despite-a-valid-signature-the-manifest-freshness-gap-in-a2a-v1-0-discovery.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-peer-s-agent-card-despite-a-valid-signature-the-manifest-freshness-gap-in-a2a-v1-0-discovery.warrant.json
# Markdown SHA-256:   236145136141e74feb944256d8647804701bc561ffc93046488376faff9f30c1
# Code AST SHA-256:   4ca1d8d1940d4c76447cf5545c3601b9885ecafb800b3c393f2f429afc7505b0
# Verified Classes:   StaleManifestError, SignedAgentCard
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class StaleManifestError(RuntimeError):
    """Raised when a signature-valid Agent Card is not operationally current."""


@dataclass(frozen=True)
class SignedAgentCard:
    body: dict            # signed manifest body
    signature: bytes      # detached signature over body
    kid: str              # key id for JWKS resolution
    fetched_at: float     # unix time of last successful fetch

    def signed_digest(self) -> str:
        # canonical serialization is assumed deterministic upstream
        import json
        return hashlib.sha256(
            json.dumps(self.body, sort_keys=True, separators=(",", ":")).encode()
        ).hexdigest()


def verify_provenance(card: SignedAgentCard, jwks: dict) -> bool:
    # placeholder: real impl verifies signature over signed_digest() with jwks[card.kid]
    return card.kid in jwks


def assert_dispatch_authorized(
    card: SignedAgentCard,
    jwks: dict,
    fresh_epoch: int | None,
    now: float | None = None,
) -> None:
    """Two-gate check. Provenance alone never authorizes dispatch."""
    now = time.time() if now is None else now

    if not verify_provenance(card, jwks):
        raise StaleManifestError(f"provenance failed for kid={card.kid}")

    not_after = card.body.get("not_after")
    if not_after is None:
        raise StaleManifestError(
            "manifest lacks signed not_after; provenance != currency"
        )
    if now >= not_after:
        raise StaleManifestError(
            f"manifest expired at {not_after:.0f}, now={now:.0f}; refetch required"
        )

    signed_epoch = card.body.get("manifest_epoch")
    if signed_epoch is None:
        raise StaleManifestError("manifest lacks signed manifest_epoch")
    if fresh_epoch is None:
        # discovery endpoint unreachable: fail closed, do not fall back to cache
        raise StaleManifestError(
            "cannot confirm epoch; discovery unreachable -> fail closed"
        )
    if signed_epoch != fresh_epoch:
        raise StaleManifestError(
            f"epoch drift: cached={signed_epoch} fresh={fresh_epoch}; peer rotated"
        )

    for field in ("capabilities", "max_concurrency", "schema"):
        if field not in card.body:
            raise StaleManifestError(
                f"dispatch-relevant field '{field}' not in signed body"
            )
