# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-corrupt-its-own-context-when-a-diff-based-self-edit-patch-applies-cleanly-but-anchors-to-a-stale-pre-image.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-corrupt-its-own-context-when-a-diff-based-self-edit-patch-applies-cleanly-but-anchors-to-a-stale-pre-image.warrant.json
# Markdown SHA-256:   2ff6b4415ccefad6a5727015ab3ac9b0c1e6c21ce88da99cf7ed9dd2a2e0b2ac
# Code AST SHA-256:   314f074738d33f92d5734270467bc774a1881870af02881e31e1ff64d399f8d9
# Verified Classes:   StalePreImageError, Hunk, SelfEditContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class StalePreImageError(RuntimeError):
    """Raised when a self-edit hunk's recorded pre-image does not match the
    region bytes at apply time, or when the hunk would require fuzzy matching."""


@dataclass
class Hunk:
    region_id: str
    pre_image_hash: str          # hash of the bytes the model authored against
    replacement: bytes
    fuzz: int = 0                # lines the engine had to fuzz to match


@dataclass
class SelfEditContext:
    regions: dict[str, bytes] = field(default_factory=dict)
    rollback_log: dict[str, Hunk] = field(default_factory=dict)

    def _hash(self, b: bytes) -> str:
        return hashlib.sha256(b).hexdigest()

    def read(self, region_id: str) -> tuple[bytes, str]:
        """Return (bytes, hash) so the model can bind its hunk to this pre-image."""
        body = self.regions[region_id]
        return body, self._hash(body)

    def apply(self, hunk: Hunk) -> None:
        if hunk.region_id not in self.regions:
            raise StalePreImageError(f"region {hunk.region_id!r} no longer exists")
        current = self.regions[hunk.region_id]
        current_hash = self._hash(current)

        # Invariant 1: the hunk must be anchored to the *current* bytes.
        if hunk.pre_image_hash != current_hash:
            raise StalePreImageError(
                f"stale pre-image for {hunk.region_id!r}: "
                f"authored against {hunk.pre_image_hash[:12]}, "
                f"region is now {current_hash[:12]} — re-read required"
            )

        # Invariant 2: self-edits must not rely on fuzzy matching.
        if hunk.fuzz > 0:
            raise StalePreImageError(
                f"fuzz={hunk.fuzz} on self-edit of {hunk.region_id!r}: "
                f"context lines did not match exactly — refusing to splice"
            )

        # Record inverse hunk bound to the pre-image we just verified.
        self.rollback_log[hunk.region_id] = Hunk(
            region_id=hunk.region_id,
            pre_image_hash=self._hash(hunk.replacement),
            replacement=current,
            fuzz=0,
        )
        self.regions[hunk.region_id] = hunk.replacement

    def rollback(self, region_id: str) -> None:
        if region_id not in self.rollback_log:
            raise StalePreImageError(f"no rollback entry for {region_id!r}")
        self.apply(self.rollback_log.pop(region_id))

    def compact(self, region_id: str, transform: Callable[[bytes], bytes]) -> None:
        """Any transformation that mutates a region MUST invalidate rollback
        entries bound to the old bytes, or rollback becomes a corruption vector."""
        self.regions[region_id] = transform(self.regions[region_id])
        if region_id in self.rollback_log:
            del self.rollback_log[region_id]
