# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-in-place-token-rewriting-when-a-self-editing-context-window-rewrites-its-own-provenance-anchors.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-in-place-token-rewriting-when-a-self-editing-context-window-rewrites-its-own-provenance-anchors.warrant.json
# Markdown SHA-256:   03075ccefdaba6f001940ce8c9e81489b9fbc8bd67203e1db0ca474d818a439c
# Code AST SHA-256:   56be1bf767f6715c74cfdcae8389fea5de53aabca33be117c80c21592420b104
# Verified Classes:   ProvenanceDriftError, Anchor, ContextBuffer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List


class ProvenanceDriftError(RuntimeError):
    """Raised when an in-place rewrite would leave anchors stale, dangling, or mis-based."""
    pass


@dataclass
class Anchor:
    anchor_id: str
    position: int      # offset of the anchor token itself in the buffer
    target: int        # offset the anchor points at


@dataclass
class ContextBuffer:
    text: str
    anchors: Dict[str, Anchor] = field(default_factory=dict)
    version: int = 0


def commit_rewrite(
    buf: ContextBuffer,
    start: int,
    end: int,
    replacement: str,
    remaps: Dict[str, int] | None = None,
) -> ContextBuffer:
    """
    Atomically replace buf.text[start:end] with `replacement` and re-base every
    anchor. Fails closed if any live anchor target lies inside the rewritten
    span and no remap is supplied for it.
    """
    remaps = remaps or {}
    delta = len(replacement) - (end - start)

    # 1. Referent-survival check: every anchor targeting the rewritten span
    #    must be explicitly remapped, or the commit is rejected.
    for aid, a in buf.anchors.items():
        if start <= a.target < end and aid not in remaps:
            raise ProvenanceDriftError(
                f"anchor {aid} targets rewritten span [{start},{end}) "
                f"with no remap; commit would produce a dangling anchor"
            )

    # 2. Build the new anchor table with total re-basing.
    new_anchors: Dict[str, Anchor] = {}
    for aid, a in buf.anchors.items():
        new_pos = a.position if a.position < start else a.position + delta
        if start <= a.target < end:
            new_target = remaps[aid]
        elif a.target >= end:
            new_target = a.target + delta
        else:
            new_target = a.target
        new_anchors[aid] = Anchor(aid, new_pos, new_target)

    # 3. Single atomic commit: text and anchors advance together.
    new_text = buf.text[:start] + replacement + buf.text[end:]
    return ContextBuffer(text=new_text, anchors=new_anchors, version=buf.version + 1)


def dereference(buf: ContextBuffer, anchor_id: str, pinned_version: int) -> str:
    """Fail closed if the reasoning step is pinned to a superseded buffer version."""
    if pinned_version != buf.version:
        raise ProvenanceDriftError(
            f"dereference of {anchor_id} against stale version "
            f"{pinned_version} (current {buf.version}); refuse to clamp"
        )
    a = buf.anchors[anchor_id]
    if not (0 <= a.target < len(buf.text)):
        raise ProvenanceDriftError(
            f"anchor {anchor_id} target {a.target} out of bounds "
            f"(len={len(buf.text)}); dangling anchor"
        )
    return buf.text[a.target : a.target + 40]
