# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-an-a2a-escrow-warrant-whose-sla-clock-was-negotiated-against-a-stale-capability-manifest.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-an-a2a-escrow-warrant-whose-sla-clock-was-negotiated-against-a-stale-capability-manifest.warrant.json
# Markdown SHA-256:   34d07b8705474b485a4609a67108d9429900ab12a5f5192ac662c83deea9b2f3
# Code AST SHA-256:   6ae7dcd59ac78a038fd208286ce1f87de255be19612177c3adfc53af744c8bd7
# Verified Classes:   StaleManifestWarrantError, Manifest, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class StaleManifestWarrantError(RuntimeError):
    """Raised when a warrant cannot be bound to a live, attested manifest digest."""
    pass


@dataclass(frozen=True)
class Manifest:
    executor_id: str
    body: bytes
    sequence: int
    published_at: float
    rotation_grace_s: float  # signed commitment: honor prior-manifest warrants this long
    digest: str = ""

    def __post_init__(self):
        if not self.digest:
            object.__setattr__(self, "digest", hashlib.sha256(self.body).hexdigest())


@dataclass(frozen=True)
class Warrant:
    id: str
    executor_id: str
    manifest_digest: str  # MUST be present; absence is the bug this article documents
    sla_wall_clock_s: float
    escrow_credits: int
    penalty_credits: int
    signed_at: float
    executor_attestation: str | None = None


def sign_warrant(
    w: Warrant,
    client_cached: Manifest,
    live: Manifest,
    now: float,
    client_ttl_s: float = 300.0,
) -> Warrant:
    if not w.manifest_digest:
        raise StaleManifestWarrantError(
            f"warrant {w.id} carries no manifest_digest; unarbitrable by construction"
        )
    if w.manifest_digest != client_cached.digest:
        raise StaleManifestWarrantError(
            f"warrant {w.id} digest {w.manifest_digest[:8]} != cached {client_cached.digest[:8]}"
        )
    age = now - client_cached.published_at
    grace = min(client_ttl_s, client_cached.rotation_grace_s)
    if age >= grace:
        raise StaleManifestWarrantError(
            f"cached manifest age {age:.2f}s >= grace {grace:.2f}s; re-fetch required"
        )
    if live.digest != client_cached.digest:
        # A superseding manifest exists; only proceed if still inside its grace window.
        if now - live.published_at >= live.rotation_grace_s:
            raise StaleManifestWarrantError(
                f"executor rotated to {live.digest[:8]} and grace window closed; "
                f"warrant {w.id} would be unenforceable"
            )
    return w


def accept_warrant(w: Warrant, live: Manifest, now: float) -> Warrant:
    if w.manifest_digest != live.digest:
        if now - live.published_at >= live.rotation_grace_s:
            raise StaleManifestWarrantError(
                f"executor cannot attest {w.manifest_digest[:8]}; live is {live.digest[:8]} "
                f"and grace expired — MUST reject, not accept-and-dispute"
            )
    attestation = hashlib.sha256(
        f"{w.id}:{w.manifest_digest}:{now}".encode()
    ).hexdigest()
    return Warrant(**{**w.__dict__, "executor_attestation": attestation})
