# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-self-authored-context-diff-as-an-unverified-hypothesis-rather-than-a-committed-state-transition.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-self-authored-context-diff-as-an-unverified-hypothesis-rather-than-a-committed-state-transition.warrant.json
# Markdown SHA-256:   51316c9bcef714ee925eb471fcbe72ad753806c7ca6317d52b811c789a2cccca
# Code AST SHA-256:   bcfaeba60351459e5abec303b37b325c170babbb5f76d17b30776afd642d84c8
# Verified Classes:   SelfEditInvariantViolation, Hunk, PinnedRange, EditProposal
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class SelfEditInvariantViolation(RuntimeError):
    """Raised when a self-authored context diff cannot be soundly validated."""


@dataclass(frozen=True)
class Hunk:
    start: int
    end: int
    replacement: str


@dataclass
class PinnedRange:
    name: str
    start: int
    end: int


@dataclass
class EditProposal:
    hunks: list[Hunk]
    oracle_def_span: tuple[int, int]
    pinned: list[PinnedRange] = field(default_factory=list)


def _overlaps(a_start: int, a_end: int, b_start: int, b_end: int) -> bool:
    return a_start < b_end and b_start < a_end


def pre_application_check(buffer: str, proposal: EditProposal) -> str:
    """Reject diffs that can reach their own referee. Returns sealed pre-image hash."""
    o_start, o_end = proposal.oracle_def_span
    for i, h in enumerate(proposal.hunks):
        if _overlaps(h.start, h.end, o_start, o_end):
            raise SelfEditInvariantViolation(
                f"hunk {i} span [{h.start},{h.end}) intersects oracle definition "
                f"[{o_start},{o_end}); oracle would be self-referential"
            )
        for p in proposal.pinned:
            if _overlaps(h.start, h.end, p.start, p.end):
                raise SelfEditInvariantViolation(
                    f"hunk {i} intersects pinned fact '{p.name}' "
                    f"[{p.start},{p.end}); grounding fact would be destroyed"
                )
    # Seal the pre-image of every touched range BEFORE any mutation.
    pre_image = "".join(buffer[h.start:h.end] for h in proposal.hunks)
    return hashlib.sha256(pre_image.encode()).hexdigest()


def apply_with_rollback(buffer: str, proposal: EditProposal, oracle) -> str:
    sealed = pre_application_check(buffer, proposal)

    # Apply to a shadow copy; never mutate the live buffer until validated.
    shadow = buffer
    for h in sorted(proposal.hunks, key=lambda x: x.start, reverse=True):
        shadow = shadow[: h.start] + h.replacement + shadow[h.end:]

    if not oracle(shadow):
        # Rollback path: restore from sealed pre-image, not from shadow.
        restored = buffer  # untouched, since we only wrote to shadow
        if not oracle(restored):
            raise SelfEditInvariantViolation(
                f"snapshot {sealed[:12]} fails oracle on restore; "
                f"pre-image was taken post-corruption — escalate, do not re-roll"
            )
        return restored

    return shadow
