# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-in-place-instruction-rewriting-has-corrupted-the-context-window-s-semantic-anchor.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-in-place-instruction-rewriting-has-corrupted-the-context-window-s-semantic-anchor.warrant.json
# Markdown SHA-256:   d21c1d4512b17d6ab366880d9cffe0b7f6ebf264025a70ec9cbf54b97d965b4d
# Code AST SHA-256:   d701e01da5069c23a4b848ce654d23282165421c4bc612eb6261455103352982
# Verified Classes:   ContextRewriteError, Slot, ContextWindow
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ContextRewriteError(RuntimeError):
    """Raised when an in-place context rewrite would violate single-binding referential integrity."""
    pass


@dataclass
class Slot:
    key: str
    value: str
    region: str  # "live" or "quoted"
    tombstoned: bool = False


@dataclass
class ContextWindow:
    slots: dict[str, Slot] = field(default_factory=dict)
    live_references: set[str] = field(default_factory=set)  # slot keys referenced by live instructions

    def apply_search_replace(self, anchor: str, replacement: str, target_key: str) -> None:
        # Count bindings of the anchor literal across ALL regions.
        matches = [s for s in self.slots.values() if anchor in s.value and not s.tombstoned]
        if len(matches) != 1:
            # Duplicate or absent anchor: underdetermined patch. Refuse to apply.
            raise ContextRewriteError(
                f"anchor {anchor!r} matched {len(matches)} spans; "
                f"in-place rewrite is underdetermined and would create a latent alias"
            )
        target = matches[0]
        if target.key != target_key:
            raise ContextRewriteError(
                f"anchor {anchor!r} resolved to slot {target.key!r} but patch targeted {target_key!r}"
            )
        target.value = target.value.replace(anchor, replacement)

    def apply_delete(self, key: str) -> None:
        if key in self.live_references:
            # Severing a referent that a live instruction depends on.
            # Convert to tombstone so the next read fails loudly instead of resolving stale.
            self.slots[key].tombstoned = True
            raise ContextRewriteError(
                f"deletion of slot {key!r} severs a live referent; tombstoned for loud failure"
            )
        del self.slots[key]


def rewrite_endpoint(window: ContextWindow, new_endpoint: str) -> None:
    slot = window.slots.get("endpoint")
    if slot is None or slot.tombstoned:
        raise ContextRewriteError("endpoint slot is absent or tombstoned; cannot rewrite")
    # Guard: a live value must never be echoed into a quoted region, which would alias it.
    if any(s.region == "quoted" and slot.value in s.value for s in window.slots.values()):
        raise ContextRewriteError(
            "live endpoint value is echoed in a quoted region; textual rewrite is unsafe "
            "in this window until the alias is removed or keyed addressing is used"
        )
    window.apply_search_replace(slot.value, new_endpoint, target_key="endpoint")
