# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-model-authored-context-rewrite-that-preserves-token-count-but-destroys-the-provenance-of-already-verif.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-model-authored-context-rewrite-that-preserves-token-count-but-destroys-the-provenance-of-already-verif.warrant.json
# Markdown SHA-256:   c411b3fef1f0fcb3aef8cc742ea7166f75cc299d01cf89b7204d48d53114777a
# Code AST SHA-256:   fe02950760218c228ce3c443b4ea104ae3d4b334b48fd884ee56cffe57b82e25
# Verified Classes:   ProvenanceOrphanedError, ProtectedSpan, RewriteRequest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ProvenanceOrphanedError(RuntimeError):
    """Raised when a model-authored context rewrite would orphan an outstanding
    reference (authorization, citation, replay checkpoint) by altering bytes
    that the reference still points at, with no migration warrant supplied."""


@dataclass(frozen=True)
class ProtectedSpan:
    span_id: str
    start: int
    end: int
    obligation: str  # e.g. "auth:write_file", "cite:report", "replay:ckpt-7"


@dataclass
class RewriteRequest:
    target_start: int
    target_end: int
    replacement: str
    migration_warrant: dict[str, str] = field(default_factory=dict)  # span_id -> new_anchor


def apply_model_rewrite(
    window: str,
    protected: list[ProtectedSpan],
    req: RewriteRequest,
) -> str:
    """Execute a model-authored rewrite only if it does not orphan any
    protected span. Protected set must be derived from the LIVE obligation
    table at call time, not snapshotted at window construction."""

    intersecting = [
        p for p in protected
        if not (req.target_end <= p.start or req.target_start >= p.end)
    ]

    if intersecting:
        unmigrated = [p for p in intersecting if p.span_id not in req.migration_warrant]
        if unmigrated:
            detail = ", ".join(
                f"{p.span_id}[{p.start}:{p.end}]<{p.obligation}>" for p in unmigrated
            )
            raise ProvenanceOrphanedError(
                f"rewrite [{req.target_start}:{req.target_end}] intersects "
                f"{len(unmigrated)} protected span(s) with no migration warrant: {detail}. "
                f"Refuse rewrite-through; rewrite around protected ranges or supply "
                f"a warrant naming the new anchor for each affected reference."
            )

    # Safe: no protected span is orphaned (either no intersection, or every
    # intersecting span has an explicit migration warrant re-anchoring it).
    return window[: req.target_start] + req.replacement + window[req.target_end :]
