# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-window-with-diff-based-patches-and-the-patch-anchor-has-drifted.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-window-with-diff-based-patches-and-the-patch-anchor-has-drifted.warrant.json
# Markdown SHA-256:   6ec5a5ee6087cef2e1353b37f55f3de6b384ca321aac496dfba4279e74448100
# Code AST SHA-256:   4a82a3c7e88d639ea5dcaa112a7ca08e6ce9b5b805a570e89d92f7a06daa9216
# Verified Classes:   PatchAnchorError, Patch
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class PatchAnchorError(RuntimeError):
    """Raised when a self-edit patch cannot be applied exactly once."""


@dataclass
class Patch:
    search: str
    replace: str
    origin_turn: int
    derived_from_verbatim_read: bool


def apply_self_patch(buffer: str, patch: Patch, current_turn: int) -> str:
    # Provenance guard: a patch built from a summary or recollection is
    # not trustworthy even if it happens to match; reject it outright.
    if not patch.derived_from_verbatim_read:
        raise PatchAnchorError(
            f"patch from turn {patch.origin_turn} was not derived from a "
            f"verbatim read of the buffer; re-read and re-emit"
        )

    # Exact-match-or-reject. No fuzzy fallback. Count occurrences.
    occurrences = buffer.count(patch.search)

    if occurrences == 0:
        # Return the live region so the model can re-derive against reality.
        raise PatchAnchorError(
            "search block not found in live buffer (anchor drift). "
            f"current tail: {buffer[-200:]!r}"
        )

    if occurrences > 1:
        raise PatchAnchorError(
            f"search block is ambiguous ({occurrences} matches); "
            "widen the anchor with surrounding context"
        )

    # Exactly one match: safe to splice.
    idx = buffer.index(patch.search)
    new_buffer = (
        buffer[:idx] + patch.replace + buffer[idx + len(patch.search):]
    )

    # Post-condition: the replacement must be present exactly once and the
    # buffer length must change by exactly the expected delta.
    expected_delta = len(patch.replace) - len(patch.search)
    if len(new_buffer) - len(buffer) != expected_delta:
        raise PatchAnchorError(
            "post-apply length invariant violated; buffer corrupted"
        )
    if new_buffer.count(patch.replace) != 1:
        raise PatchAnchorError(
            "replacement block collides with existing buffer content"
        )

    return new_buffer
