# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-a2a-delegation-whose-trust-broker-warrant-was-valid-at-issuance-but-whose-policy-negotiation-clo.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-a2a-delegation-whose-trust-broker-warrant-was-valid-at-issuance-but-whose-policy-negotiation-clo.warrant.json
# Markdown SHA-256:   40780834d376a70e2c241fabb7286dc14d9cbb277a0f9ce0662a53062866765c
# Code AST SHA-256:   0190abc5f10fa71d73754dc6c8cab8a58d542097c6bd9e6de689aa8d805c46f5
# Verified Classes:   StaleClosureWarrantError, Warrant, EpochManifest
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleClosureWarrantError(RuntimeError):
    """Raised when a federated A2A warrant is live-by-signature but stale-by-closure."""


@dataclass(frozen=True)
class Warrant:
    subject: str
    epoch: int
    closure_digest: str
    capabilities: frozenset
    obligations: frozenset
    not_after: float
    signature_valid: bool


@dataclass(frozen=True)
class EpochManifest:
    epoch: int
    peer_set: frozenset
    schema_versions: dict
    obligations: frozenset
    monotonic_counter: int


def recompute_closure_digest(manifest: EpochManifest) -> str:
    h = hashlib.sha256()
    h.update(str(manifest.epoch).encode())
    for peer in sorted(manifest.peer_set):
        h.update(peer.encode())
    for k in sorted(manifest.schema_versions):
        h.update(f"{k}={manifest.schema_versions[k]}".encode())
    for ob in sorted(manifest.obligations):
        h.update(ob.encode())
    return h.hexdigest()


def validate_delegation(
    warrant: Warrant,
    current: EpochManifest,
    last_seen_counter: int,
    now: float,
) -> None:
    if not warrant.signature_valid:
        raise StaleClosureWarrantError("signature invalid; transport integrity failed")
    if now >= warrant.not_after:
        raise StaleClosureWarrantError("warrant expired by clock")
    if current.monotonic_counter <= last_seen_counter:
        raise StaleClosureWarrantError(
            f"epoch manifest replay: counter {current.monotonic_counter} <= {last_seen_counter}"
        )

    if warrant.epoch == current.epoch:
        expected = recompute_closure_digest(current)
        if warrant.closure_digest != expected:
            raise StaleClosureWarrantError(
                "same-epoch closure drift: TB bumped schema/peer-set without epoch bump"
            )
        return

    if warrant.epoch < current.epoch:
        # Re-derivation path: only legal if obligations are a superset and digest matches
        # a locally retained transcript for the old epoch. We do NOT retain transcripts,
        # so the conservative and correct action is rejection.
        added = current.obligations - warrant.obligations
        if added:
            raise StaleClosureWarrantError(
                f"stale epoch {warrant.epoch} < {current.epoch}; new obligations {sorted(added)} "
                "not carried by warrant — reject to avoid honoring dissolved-federation terms"
            )
        raise StaleClosureWarrantError(
            f"stale epoch {warrant.epoch} < {current.epoch}; closure digest unverifiable "
            "without retained transcript — reject and force re-negotiation"
        )

    raise StaleClosureWarrantError(
        f"warrant epoch {warrant.epoch} is ahead of current {current.epoch}; "
        "clock or manifest skew — reject"
    )
