# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-collapse-during-self-editing-context-distillation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-collapse-during-self-editing-context-distillation.warrant.json
# Markdown SHA-256:   bfd9f9bcdb6a8b06ea49ba99f60dc6b30f516667303ab6174e01fe4b7a785d42
# Code AST SHA-256:   6db714a59cdc2ad42385825dfd0970604bfd6019e8f541e3c3065d570470f6cb
# Verified Classes:   SpanType, Span, SemanticCollapseError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class SpanType(Enum):
    CONSTRAINT = "constraint"
    OBSERVATION = "observation"
    NARRATIVE = "narrative"


@dataclass(frozen=True)
class Span:
    span_id: str
    kind: SpanType
    text: str
    polarity_tokens: frozenset  # e.g. {"do not", "never", "must", "only"}


class SemanticCollapseError(RuntimeError):
    """Raised when a self-edit drops a constraint's polarity or back-reference."""


def distill(spans: list[Span], paraphrase_check) -> list[Span]:
    """
    Rewrite context, but refuse if any CONSTRAINT span loses its
    polarity-preserving paraphrase or its back-reference.
    """
    surviving: list[Span] = []
    for span in spans:
        if span.kind is SpanType.NARRATIVE:
            continue  # safe to drop
        if span.kind is SpanType.CONSTRAINT:
            restated = paraphrase_check(span)
            if restated is None:
                raise SemanticCollapseError(
                    f"constraint {span.span_id} has no surviving paraphrase; "
                    f"refusing distillation (polarity would be lost: {sorted(span.polarity_tokens)})"
                )
            if not span.polarity_tokens.issubset(restated.polarity_tokens):
                raise SemanticCollapseError(
                    f"constraint {span.span_id} lost polarity tokens "
                    f"{sorted(span.polarity_tokens - restated.polarity_tokens)}; "
                    f"summary would read as complete while dropping the imperative"
                )
            surviving.append(restated)
        else:
            surviving.append(span)
    return surviving


def guarded_edit(spans: list[Span], paraphrase_check) -> list[Span]:
    try:
        return distill(spans, paraphrase_check)
    except SemanticCollapseError:
        # Fall back to eviction: keep raw constraint + observation spans verbatim.
        return [s for s in spans if s.kind is not SpanType.NARRATIVE]
