# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-diverge-from-its-attested-audit-ledger-when-a-federated-peer-re-derives-the-same-tool-call-transcript-under-a-different-tokenizat.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-diverge-from-its-attested-audit-ledger-when-a-federated-peer-re-derives-the-same-tool-call-transcript-under-a-different-tokenizat.warrant.json
# Markdown SHA-256:   1fb64efbfe95d0a88ca2043c090d16d95bead3ad4d6ca7104b06b7b0f78a29f0
# Code AST SHA-256:   9675c3a5af4dea1ace379384ef593d08f253995ea918477fe03f00f29c14da2d
# Verified Classes:   CanonicalizationMismatch, PartialSpecDivergence
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import unicodedata
from decimal import Decimal, InvalidOperation


class CanonicalizationMismatch(RuntimeError):
    """Raised when a peer's pre-image cannot be reproduced under the declared spec version."""
    pass


class PartialSpecDivergence(RuntimeError):
    """Raised when a digest is compared against a re-derived pre-image under a partial spec."""
    pass


SPEC_VERSION = "cf-audit-canon/1"


def _canon_number(value) -> str:
    # Fixed decimal grammar: no floats, no exponent, trailing zeros trimmed.
    if isinstance(value, float):
        raise CanonicalizationMismatch(
            f"float {value!r} is not a legal canonical number under {SPEC_VERSION}"
        )
    try:
        d = Decimal(str(value))
    except InvalidOperation as exc:
        raise CanonicalizationMismatch(f"unparseable number {value!r}") from exc
    if d == d.to_integral_value():
        return str(int(d))
    return format(d.normalize(), "f")


def _canon_text(value: str) -> str:
    nfc = unicodedata.normalize("NFC", value)
    if nfc != value:
        raise CanonicalizationMismatch(
            "non-NFC text in pre-image; verifier must reject, not silently normalize"
        )
    return nfc


def _canon_map(mapping: dict) -> str:
    # Recursive, byte-ordered by UTF-8; locale collation is forbidden.
    items = []
    for k in sorted(mapping.keys(), key=lambda s: s.encode("utf-8")):
        items.append(f"{_canon_text(k)}:{_canon_value(mapping[k])}")
    return "{" + ",".join(items) + "}"


def _canon_value(value):
    if isinstance(value, dict):
        return _canon_map(value)
    if isinstance(value, str):
        return _canon_text(value)
    if isinstance(value, bool):
        return "true" if value else "false"
    if value is None:
        return "null"
    if isinstance(value, (int, float, Decimal)):
        return _canon_number(value)
    if isinstance(value, list):
        return "[" + ",".join(_canon_value(v) for v in value) + "]"
    raise CanonicalizationMismatch(f"unsupported type {type(value).__name__}")


def canonical_bytes(event: dict, spec_version: str) -> bytes:
    if spec_version != SPEC_VERSION:
        raise CanonicalizationMismatch(
            f"peer cites spec {spec_version!r}; verifier implements {SPEC_VERSION!r} — refuse to attest"
        )
    body = _canon_map(event)
    return f"{spec_version}\n{body}".encode("utf-8")


def attest(event: dict, transmitted_preimage: bytes, peer_digest: str) -> bool:
    # Sound path: verify the digest over the *transmitted* pre-image, then
    # separately validate that the pre-image is the canonical form.
    spec_version = event.get("spec_version")
    digest = hashlib.sha256(transmitted_preimage).hexdigest()
    if digest != peer_digest:
        # Spec version matched and bytes differ => genuine integrity divergence.
        raise CanonicalizationMismatch("digest mismatch over transmitted pre-image")

    rederived = canonical_bytes(event, spec_version)
    if rederived != transmitted_preimage:
        # The peer's bytes are not canonical under the declared spec. This is
        # NOT tampering; it is a partial-spec divergence and must be quarantined.
        raise PartialSpecDivergence(
            "transmitted pre-image is non-canonical; quarantine and request re-serialization"
        )
    return True
