# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-validate-a-self-authored-context-rewrite-when-the-diff-is-semantically-empty-but-syntactically-large.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-validate-a-self-authored-context-rewrite-when-the-diff-is-semantically-empty-but-syntactically-large.warrant.json
# Markdown SHA-256:   27d5e4c753f8e714b0426ad4c4c5c38b541a36a288a69b8327e3763cf88d6607
# Code AST SHA-256:   0548eb2a0f58cfdaf5a14630dd60e075e2a226f7588024d092203f1b4744bb3a
# Verified Classes:   ContextRewriteRejected, ProtectedSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class ContextRewriteRejected(RuntimeError):
    """Raised when a self-authored context rewrite fails the displacement invariant."""


@dataclass(frozen=True)
class ProtectedSpan:
    span_id: str
    text: str
    section_class: str  # "active" | "deferred" | "archive"


def validate_rewrite(
    before: Sequence[ProtectedSpan],
    after: Sequence[ProtectedSpan],
    context_len_after: int,
    max_position_delta: float = 0.35,
    independent_validator: bool = True,
) -> None:
    """
    Enforce the split invariant: deletion is checked by span ID, displacement is
    checked by normalized rank position and section class. The displacement check
    must be run by an independent validator; if none is available, the caller must
    fall back to deletion-only compaction.
    """
    before_by_id = {s.span_id: s for s in before}
    after_by_id = {s.span_id: s for s in after}

    missing = set(before_by_id) - set(after_by_id)
    if missing:
        raise ContextRewriteRejected(
            f"ProtectedSpanRemoved: {sorted(missing)} dropped by rewrite"
        )

    if not independent_validator:
        # Deletion-only mode: reordering/reclassification is not permitted.
        for span_id, span in before_by_id.items():
            if after_by_id[span_id].section_class != span.section_class:
                raise ContextRewriteRejected(
                    f"ProtectedSpanReclassified: {span_id} moved to "
                    f"{after_by_id[span_id].section_class} without independent validator"
                )
        return

    for span_id, old in before_by_id.items():
        new = after_by_id[span_id]
        old_pos = old_position_fraction(old, before, context_len_after)
        new_pos = new_position_fraction(new, after, context_len_after)
        if new_pos - old_pos > max_position_delta:
            raise ContextRewriteRejected(
                f"ProtectedSpanDisplaced: {span_id} moved from "
                f"{old_pos:.2f} to {new_pos:.2f} of context"
            )
        if new.section_class in ("deferred", "archive") and old.section_class == "active":
            raise ContextRewriteRejected(
                f"ProtectedSpanDeferral: {span_id} reclassified active->{new.section_class}"
            )


def old_position_fraction(span, spans, context_len_after):
    idx = list(spans).index(span)
    return idx / max(len(spans), 1)


def new_position_fraction(span, spans, context_len_after):
    idx = list(spans).index(span)
    char_estimate = sum(len(s.text) for s in spans[: idx + 1])
    return char_estimate / max(context_len_after, 1)


def commit_or_rollback(before, after, context_len_after, independent_validator):
    try:
        validate_rewrite(before, after, context_len_after, independent_validator=independent_validator)
    except ContextRewriteRejected as exc:
        return {"committed": False, "reason": str(exc)}
    return {"committed": True, "reason": None}
