# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-journal-context-window-edits-as-reversible-operations-and-when-does-append-only-commit-suffice.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-journal-context-window-edits-as-reversible-operations-and-when-does-append-only-commit-suffice.warrant.json
# Markdown SHA-256:   8603e3592473501807e7b8297661e68d72450db2746b067194f1e7f12a6775a3
# Code AST SHA-256:   35087850d38aa5dae0b2d692def9856b8595348dd170a4c97e8e42b8304a5248
# Verified Classes:   JournalReplayError, WindowHashMismatch, JournalEntry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class JournalReplayError(RuntimeError):
    """Raised when a journal entry cannot be soundly inverted."""
    pass


class WindowHashMismatch(JournalReplayError):
    """Raised when reconstructed window diverges from the checkpoint hash."""
    pass


@dataclass
class JournalEntry:
    op: str
    offset: int
    length: int
    content: Optional[str]
    content_hash: Optional[str]
    lossless: bool
    src: Optional[str] = None


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


def apply_inverse(window: str, entry: JournalEntry) -> str:
    if not entry.lossless:
        raise JournalReplayError(
            f"cannot invert lossy entry op={entry.op} at offset={entry.offset}; "
            f"pre-edit reasoning is unrecoverable"
        )
    if entry.content is None or entry.content_hash is None:
        raise JournalReplayError(
            f"entry op={entry.op} offset={entry.offset} lacks inline content or hash; "
            f"src={entry.src} may be TTL-evicted"
        )
    if _hash(entry.content) != entry.content_hash:
        raise JournalReplayError(
            f"content hash mismatch for op={entry.op} offset={entry.offset}; "
            f"source {entry.src} is not byte-identical to write time"
        )
    return window[: entry.offset] + entry.content + window[entry.offset :]


def rollback(window: str, journal: list[JournalEntry], expected_hash: str) -> str:
    for entry in reversed(journal):
        window = apply_inverse(window, entry)
    if _hash(window) != expected_hash:
        raise WindowHashMismatch(
            "reconstructed window does not match checkpoint hash; "
            "refusing to resume autonomous execution"
        )
    return window
