# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-phantom-hunk-rebase-when-a-diff-based-context-controller-rewrites-its-own-workspace-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-phantom-hunk-rebase-when-a-diff-based-context-controller-rewrites-its-own-workspace-mid-task.warrant.json
# Markdown SHA-256:   3a1fcb0ade19ec4c89cbd65407fda6d9a865e067597230d3656d4b2a73181e1d
# Code AST SHA-256:   28fa98ab6bd61174e5aacdc5c6606f7c0e8bd4745892869e9f82fedf418efc99
# Verified Classes:   PhantomHunkError, WorkspaceView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class PhantomHunkError(RuntimeError):
    """Raised when a diff would apply against a workspace image the agent never saw,
    or would resolve an anchor ambiguously / at a nonzero offset."""


@dataclass(frozen=True)
class WorkspaceView:
    path: str
    content: str
    believed_hash: str          # sha256 the agent computed at last read
    believed_anchor_line: int   # line number the agent's reasoning assumes


def _sha(s: str) -> str:
    return hashlib.sha256(s.encode("utf-8")).hexdigest()


def apply_hunk(view: WorkspaceView, disk_content: str, hunk: dict) -> str:
    """Compare-and-swap apply. hunk = {old_start, context, replacement}."""
    # 1. Hash continuity: the agent must be patching the image it read.
    if _sha(disk_content) != view.believed_hash:
        raise PhantomHunkError(
            f"{view.path}: pre-image hash mismatch — workspace mutated since read "
            f"(self-normalization or peer write); refusing offset-corrected apply"
        )

    lines = disk_content.splitlines(keepends=True)
    ctx = hunk["context"]
    matches = [i for i, ln in enumerate(lines) if ln.rstrip("\n") == ctx]

    # 2. Anchor uniqueness: a context string that appears twice is a coin flip.
    if len(matches) > 1:
        raise PhantomHunkError(
            f"{view.path}: anchor {ctx!r} matched {len(matches)} locations — ambiguous hunk"
        )
    if not matches:
        raise PhantomHunkError(f"{view.path}: anchor {ctx!r} not found")

    actual_line = matches[0] + 1  # 1-indexed

    # 3. Offset is invalidation, not success: line model is provably stale.
    if actual_line != view.believed_anchor_line or hunk["old_start"] != view.believed_anchor_line:
        raise PhantomHunkError(
            f"{view.path}: anchor drift — believed line {view.believed_anchor_line}, "
            f"disk line {actual_line}; agent must re-read before further hunks"
        )

    out = lines[: matches[0]] + [hunk["replacement"] + "\n"] + lines[matches[0] + 1 :]
    return "".join(out)
