# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-org-audit-attestations-from-silently-diverging-when-selective-disclosure-drops-the-very-field-a-downstream-verifier-nee.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-org-audit-attestations-from-silently-diverging-when-selective-disclosure-drops-the-very-field-a-downstream-verifier-nee.warrant.json
# Markdown SHA-256:   874bf1ff86cc177e4f90778f6ae4abbb218e726dbd073799c47b2df1fb7663d8
# Code AST SHA-256:   2176092e82f28e476710384cb35dd7ebc856b237b3e193f52604146b83772afa
# Verified Classes:   DisclosureDivergenceError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any


class DisclosureDivergenceError(RuntimeError):
    """Raised when a selectively-disclosed attestation cannot be reconstructed
    to a byte-identical leaf under the committed field manifest."""


def canonical(record: dict[str, Any], manifest: list[str]) -> bytes:
    # Fixed field set from the manifest; missing clear fields are illegal.
    ordered = {k: record[k] for k in manifest}
    return json.dumps(ordered, sort_keys=True, separators=(",", ":")).encode()


def redaction_commitment(salt: bytes, value: Any) -> str:
    return hashlib.sha256(salt + json.dumps(value, sort_keys=True).encode()).hexdigest()


def reconstruct_leaf(
    disclosed: dict[str, Any],
    redactions: dict[str, str],
    manifest: list[str],
    committed_manifest_hash: str,
) -> bytes:
    if sorted(manifest) != sorted(set(manifest)):
        raise DisclosureDivergenceError("manifest contains duplicate field names")
    computed_manifest_hash = hashlib.sha256(",".join(sorted(manifest)).encode()).hexdigest()
    if computed_manifest_hash != committed_manifest_hash:
        raise DisclosureDivergenceError(
            f"manifest hash mismatch: verifier schema does not match committed schema"
        )
    leaf: dict[str, Any] = {}
    for field in manifest:
        if field in disclosed:
            leaf[field] = disclosed[field]
        elif field in redactions:
            # Field existence is preserved; only the value is committed.
            leaf[field] = {"__redacted__": redactions[field]}
        else:
            # The exact collision condition: field in manifest, neither disclosed
            # nor redaction-committed. Absence must never be treated as "not committed".
            raise DisclosureDivergenceError(
                f"field '{field}' is in the committed manifest but neither disclosed "
                f"nor redaction-committed; reconstruction would be non-injective"
            )
    return canonical(leaf, manifest)


def verify_attestation(attestation: dict[str, Any], salt_store: dict[str, bytes]) -> bool:
    manifest = attestation["manifest"]
    disclosed = attestation["disclosed"]
    redactions = attestation["redaction_commitments"]
    committed_manifest_hash = attestation["manifest_hash"]
    committed_leaf_hash = attestation["leaf_hash"]

    # Reconstruct with redaction commitments; reject on any gap.
    try:
        leaf_bytes = reconstruct_leaf(disclosed, redactions, manifest, committed_manifest_hash)
    except DisclosureDivergenceError:
        raise

    if hashlib.sha256(leaf_bytes).hexdigest() != committed_leaf_hash:
        raise DisclosureDivergenceError(
            "reconstructed leaf hash does not match committed leaf; "
            "disclosure is internally consistent but incomplete"
        )
    return True
