# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-memory-write-attestation-whose-provenance-hash-collides-with-a-previously-verified-entry.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-memory-write-attestation-whose-provenance-hash-collides-with-a-previously-verified-entry.warrant.json
# Markdown SHA-256:   dcddaf9fbc3e9ed3fecb8ebec8c68295df836c2964697c640ffff187ec35bb57
# Code AST SHA-256:   2d6707e1e8bc586b38ba7b9ca1c7363be61bd81928f52ce99d1ce8e88e620af9
# Verified Classes:   ProvenanceCollisionError, MemoryEntry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import unicodedata
from dataclasses import dataclass


class ProvenanceCollisionError(RuntimeError):
    """Raised when a provenance hash match cannot be trusted as payload identity."""
    pass


@dataclass(frozen=True)
class MemoryEntry:
    source_id: str
    payload: str
    timestamp: int
    provenance: str
    hash_scheme: str  # e.g. "v1:source+payload+timestamp", "v2:source+payload"


def _normalize(payload: str) -> str:
    return unicodedata.normalize("NFC", " ".join(payload.split()))


def compute_provenance(entry: MemoryEntry) -> str:
    if entry.hash_scheme == "v1:source+payload+timestamp":
        material = f"{entry.source_id}|{entry.payload}|{entry.timestamp}"
    elif entry.hash_scheme == "v2:source+payload":
        material = f"{entry.source_id}|{_normalize(entry.payload)}"
    else:
        raise ProvenanceCollisionError(f"unknown hash scheme: {entry.hash_scheme}")
    return hashlib.sha256(material.encode("utf-8")).hexdigest()


def verify_write(incoming: MemoryEntry, stored: MemoryEntry) -> None:
    """Accept a write as a benign duplicate only if provenance identity is sound."""
    if incoming.provenance != stored.provenance:
        return  # distinct entries, normal path

    # Hash matches -- but is the match trustworthy as payload identity?
    if incoming.hash_scheme != stored.hash_scheme:
        raise ProvenanceCollisionError(
            f"provenance match across hash-scheme boundary "
            f"({stored.hash_scheme!r} vs {incoming.hash_scheme!r}); "
            f"collision cannot be distinguished from duplicate"
        )

    # Same scheme: recompute over the *write-side* tuple and compare payloads.
    recomputed = compute_provenance(incoming)
    if recomputed != incoming.provenance:
        raise ProvenanceCollisionError(
            "recomputed provenance does not match claimed provenance"
        )

    if _normalize(incoming.payload) != _normalize(stored.payload):
        raise ProvenanceCollisionError(
            "provenance hash collides but normalized payloads differ; "
            "quarantine instead of dedup-merge"
        )


def ingest(incoming: MemoryEntry, store: dict[str, MemoryEntry]) -> None:
    stored = store.get(incoming.provenance)
    if stored is not None:
        verify_write(incoming, stored)  # raises on collision
        return  # benign duplicate, no-op
    store[incoming.provenance] = incoming
