# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-an-in-place-context-rewrite-when-the-diff-s-base-hash-no-longer-matches-the-live-window.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-an-in-place-context-rewrite-when-the-diff-s-base-hash-no-longer-matches-the-live-window.warrant.json
# Markdown SHA-256:   1b80c60d89389b525f0a21242fc740a90c507408d42a987c8419348c2dc11abd
# Code AST SHA-256:   cf42ac2fc44215edba172ece244c284c667e3bff910131b457ef5462fd59adbb
# Verified Classes:   Provenance, ContextAnchorError, Span, PendingDiff
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class Provenance(Enum):
    AGENT = "agent"
    TOOL = "tool"
    EXTERNAL = "external"


class ContextAnchorError(RuntimeError):
    """Raised when a diff-based context mutation cannot be safely applied."""


@dataclass(frozen=True)
class Span:
    text: str
    provenance: Provenance


@dataclass(frozen=True)
class PendingDiff:
    base_hash: str
    anchor: str
    replacement: str
    author: Provenance


def window_hash(window: list[Span]) -> str:
    h = hashlib.sha256()
    for s in window:
        h.update(s.provenance.value.encode())
        h.update(b"\x00")
        h.update(s.text.encode())
        h.update(b"\x01")
    return h.hexdigest()


def resolve_anchor(window: list[Span], anchor: str) -> list[int]:
    """Return indices of spans whose text contains the anchor (fuzzy-tolerant)."""
    hits = []
    for i, s in enumerate(window):
        if anchor in s.text:
            hits.append(i)
        elif _fuzzy_contains(s.text, anchor):
            hits.append(i)
    return hits


def _fuzzy_contains(haystack: str, needle: str) -> bool:
    # Placeholder for the matcher's tolerance; intentionally permissive so
    # that the uniqueness check below is what bounds the failure.
    if len(needle) < 4:
        return False
    return needle[: len(needle) - 1] in haystack


def apply_self_edit(window: list[Span], diff: PendingDiff) -> list[Span]:
    live = window_hash(window)
    if live != diff.base_hash:
        raise ContextAnchorError(
            f"base hash mismatch: diff authored against {diff.base_hash[:12]}, "
            f"live window is {live[:12]}; re-derive the diff"
        )

    hits = resolve_anchor(window, diff.anchor)
    if len(hits) != 1:
        raise ContextAnchorError(
            f"anchor {diff.anchor!r} resolved to {len(hits)} spans; "
            f"fuzzy match without uniqueness is the wrong-block vector"
        )

    idx = hits[0]
    target = window[idx]
    if target.provenance != diff.author:
        raise ContextAnchorError(
            f"provenance mutation refused: target is {target.provenance.value}, "
            f"replacement authored by {diff.author.value}; route through annotate path"
        )

    new_window = list(window)
    new_window[idx] = Span(text=diff.replacement, provenance=diff.author)
    return new_window
