# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-memory-write-when-the-provenance-hash-chain-verifies-clean-the-write-audit-trail-s-commit-ordering-invariant-an.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-memory-write-when-the-provenance-hash-chain-verifies-clean-the-write-audit-trail-s-commit-ordering-invariant-an.warrant.json
# Markdown SHA-256:   d92a5fedd6921d8721e78c22180d0f55554ee7eaf8fc09369e7cecef96a71fa3
# Code AST SHA-256:   5b9698d83d42f19e2b1b79fc5a5873d632c4ad6a9f36fbfda21077be0fb16f21
# Verified Classes:   ProjectionDivergenceError, LogRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ProjectionDivergenceError(RuntimeError):
    """Raised when served index content disagrees with the authoritative log record."""
    pass


@dataclass(frozen=True)
class LogRecord:
    commit_id: int
    key: str
    content: str
    prev_hash: str
    content_digest: str


def _digest(content: str) -> str:
    return hashlib.sha256(content.encode("utf-8")).hexdigest()


def verify_chain(records: list[LogRecord]) -> bool:
    prev = "GENESIS"
    for r in records:
        if r.prev_hash != prev:
            return False
        if r.content_digest != _digest(r.content):
            return False
        prev = r.content_digest
    return True


def assert_projection_matches_log(
    key: str,
    served_content: str,
    records: list[LogRecord],
) -> None:
    """Enforce the invariant: index_content(key) == log_content(max commit_id for key).

    A clean hash chain is necessary but NOT sufficient. This check is the one that
    catches append-then-index divergence where the projection was assembled in a
    different order than the log.
    """
    if not verify_chain(records):
        raise ProjectionDivergenceError(
            f"audit chain for key {key!r} failed integrity verification"
        )

    candidates = [r for r in records if r.key == key]
    if not candidates:
        raise ProjectionDivergenceError(
            f"no committed record for key {key!r} but index served content"
        )

    authoritative = max(candidates, key=lambda r: r.commit_id)
    if _digest(served_content) != authoritative.content_digest:
        raise ProjectionDivergenceError(
            f"projection divergence on key {key!r}: index serves "
            f"digest {_digest(served_content)[:12]} but log commit "
            f"{authoritative.commit_id} holds {authoritative.content_digest[:12]}; "
            f"refusing high-trust read"
        )


def high_trust_read(key: str, index, records: list[LogRecord]) -> str:
    served = index.get(key)
    if served is None:
        raise ProjectionDivergenceError(f"key {key!r} absent from index")
    assert_projection_matches_log(key, served, records)
    return served
