# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-model-authored-context-diff-because-the-edit-journal-cannot-reconstruct-the-pre-edit-context-byte-for-byte.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-model-authored-context-diff-because-the-edit-journal-cannot-reconstruct-the-pre-edit-context-byte-for-byte.warrant.json
# Markdown SHA-256:   d7aac0b8d57e77a6d924f140cc07979cb12e694e18f8d2ddb18358db529cf813
# Code AST SHA-256:   54778bb9f65dcfec27b526864bd8b5171edba843d6f67a7838911e3c3ff9514e
# Verified Classes:   UnreconstructableRollback, JournalEntry, EditJournal
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class UnreconstructableRollback(RuntimeError):
    """Raised when inverse replay cannot prove it reconstructs a real prior state."""
    pass


@dataclass
class JournalEntry:
    step: int
    pre_image: bytes
    post_image: bytes
    pre_hash: str
    post_hash: str
    committed: bool = False


class EditJournal:
    def __init__(self, initial_buffer: bytes):
        self.buffer = initial_buffer
        self.entries: list[JournalEntry] = []
        self._hash = self._digest(initial_buffer)

    @staticmethod
    def _digest(b: bytes) -> str:
        return hashlib.sha256(b).hexdigest()

    def apply(self, step: int, anchor: bytes, replacement: bytes) -> JournalEntry:
        # Anchor uniqueness is checked against the LIVE buffer, not the model's claim.
        occurrences = self.buffer.count(anchor)
        if occurrences != 1:
            raise UnreconstructableRollback(
                f"step {step}: anchor occurs {occurrences} times; diff is underdetermined"
            )
        idx = self.buffer.index(anchor)
        pre_image = self.buffer[idx:idx + len(anchor)]
        pre_hash = self._hash
        new_buffer = self.buffer[:idx] + replacement + self.buffer[idx + len(anchor):]
        post_hash = self._digest(new_buffer)
        entry = JournalEntry(
            step=step,
            pre_image=pre_image,
            post_image=replacement,
            pre_hash=pre_hash,
            post_hash=post_hash,
        )
        self.buffer = new_buffer
        self._hash = post_hash
        self.entries.append(entry)
        return entry

    def commit(self, entry: JournalEntry) -> None:
        # A commit is only valid if the entry's claimed pre_hash matches the
        # hash of the state it was applied to. An entry applied against a
        # buffer that had already moved (batch-authored against one snapshot)
        # will fail here and must not be treated as invertible.
        if entry.pre_hash != self._hash_of_predecessor(entry):
            raise UnreconstructableRollback(
                f"step {entry.step}: pre_hash does not match predecessor state; "
                f"entry is non-invertible and rollback must re-derive from checkpoint"
            )
        entry.committed = True

    def _hash_of_predecessor(self, entry: JournalEntry) -> str:
        i = self.entries.index(entry)
        return self.entries[i - 1].post_hash if i > 0 else self.entries[0].pre_hash

    def rollback_to(self, step: int) -> bytes:
        for entry in reversed(self.entries):
            if entry.step <= step:
                break
            if not entry.committed:
                raise UnreconstructableRollback(
                    f"step {entry.step}: uncommitted entry in rollback path; "
                    f"cannot prove reconstructed state existed"
                )
            idx = self.buffer.find(entry.post_image)
            if idx < 0:
                raise UnreconstructableRollback(
                    f"step {entry.step}: post_image absent from buffer; "
                    f"region overwritten by non-intersecting later edit"
                )
            self.buffer = (
                self.buffer[:idx] + entry.pre_image + self.buffer[idx + len(entry.post_image):]
            )
            if self._digest(self.buffer) != entry.pre_hash:
                raise UnreconstructableRollback(
                    f"step {entry.step}: post-inverse hash mismatch; "
                    f"reconstructed state is counterfactual"
                )
            self._hash = entry.pre_hash
        return self.buffer
