# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-an-a2a-delegation-receipt-was-re-signed-after-the-fact-and-why-does-non-repudiation-silently-fail-when-the-warrant-ch.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-an-a2a-delegation-receipt-was-re-signed-after-the-fact-and-why-does-non-repudiation-silently-fail-when-the-warrant-ch.warrant.json
# Markdown SHA-256:   e14170a910249ab8b946bd9dd369f9ce819c5f5dd2fa4da9c282abdb6c222e11
# Code AST SHA-256:   838c8ac4132ebf720d7cdcf1d20d491f9cf4083ebf19962aa5fbebf3be3f5bf3
# Verified Classes:   NonRepudiationError, Warrant, Receipt
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class NonRepudiationError(RuntimeError):
    """Raised when an A2A receipt cannot be adjudicated against the signed warrant."""
    pass


@dataclass(frozen=True)
class Warrant:
    task: str
    scope: str
    nonce: str
    issued_at: int
    deadline: int
    canon_version: str = "jcs-v1"


@dataclass(frozen=True)
class Receipt:
    attested_hash: str
    outcome: str
    exec_nonce: int
    sig_b: str


def canonicalize(warrant: Warrant) -> bytes:
    # Pinned canonicalizer: sorted keys, no whitespace, integers as integers.
    payload = {
        "canon_version": warrant.canon_version,
        "deadline": warrant.deadline,
        "issued_at": warrant.issued_at,
        "nonce": warrant.nonce,
        "scope": warrant.scope,
        "task": warrant.task,
    }
    return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")


def verify_receipt(
    raw_warrant_bytes: bytes,
    warrant: Warrant,
    receipt: Receipt,
    prior_receipts: list[Receipt],
    expected_canon_version: str,
) -> None:
    if warrant.canon_version != expected_canon_version:
        raise NonRepudiationError(
            f"canon_version skew: warrant={warrant.canon_version} "
            f"verifier={expected_canon_version}; drift indistinguishable from tampering"
        )

    signed_hash = hashlib.sha256(canonicalize(warrant)).hexdigest()
    wire_hash = hashlib.sha256(raw_warrant_bytes).hexdigest()

    if signed_hash != wire_hash:
        raise NonRepudiationError(
            "canonicalization drift: signed form and wire form diverge; "
            f"signed={signed_hash[:12]} wire={wire_hash[:12]}"
        )

    if receipt.attested_hash != wire_hash:
        raise NonRepudiationError(
            "receipt attests to a different byte string than the delegator signed; "
            "signature validity does not restore non-repudiation"
        )

    earlier = [r for r in prior_receipts if r.attested_hash == wire_hash]
    if earlier and min(r.exec_nonce for r in earlier) < receipt.exec_nonce:
        raise NonRepudiationError(
            "receipt re-signing detected: a later exec_nonce cannot supersede the first; "
            "adjudicate against the lowest exec_nonce"
        )
