# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-lossy-context-compaction-the-summary-commit-boundary-in-retrieval-backed-restoration.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-lossy-context-compaction-the-summary-commit-boundary-in-retrieval-backed-restoration.warrant.json
# Markdown SHA-256:   614a5783cf699b3c129a33b23b59cc1d3831010356cdc39b80b1c5d758c9b10c
# Code AST SHA-256:   43a641f83c070fd6eb142474eda492174afc915ba5b92f651c455e62a0ab536a
# Verified Classes:   CompactionBoundaryError, RawSpan, Summary
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass, field
from typing import Optional


class CompactionBoundaryError(RuntimeError):
    """Raised when a lossy compaction or summary-only action would cross the
    summary-commit boundary: a binding referent cannot be restored from raw."""
    pass


# Tokens whose presence in a span makes it unsafe to summarize lossily
# without a structured loss manifest (condition C2).
_LITERAL_PATTERN = re.compile(
    r"\b(NOT|never|except|only|before|after)\b"
    r"|arn:aws:[^\s]+"
    r"|\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b"
    r"|\b[a-z0-9][a-z0-9.-]*-(?:east|west|north|south)-\d\b"  # region/bucket-ish
)

# Deictic references in a *current* turn that bind to a prior span (C3).
_DEICTIC_PATTERN = re.compile(
    r"\b(same|that|the one|as before|previous|earlier|we discussed)\b",
    re.IGNORECASE,
)


@dataclass
class RawSpan:
    span_id: str
    text: str
    content_hash: str = field(init=False)

    def __post_init__(self) -> None:
        self.content_hash = hashlib.sha256(self.text.encode()).hexdigest()


@dataclass
class Summary:
    source_span_id: str
    text: str
    raw_span_available: bool          # C1: raw span still addressable
    loss_manifest: dict               # C2: {"negations": [...], "literals": [...]}
    generation: int = 1               # >1 means summary-of-summary (C4)


def _binding_tokens(span: RawSpan) -> list[str]:
    return [m.group(0) for m in _LITERAL_PATTERN.finditer(span.text)]


def compact_span(span: RawSpan, summarizer) -> Summary:
    """Commit a lossy compaction only if condition C2 can be satisfied:
    every literal/negation/ordering token is preserved or explicitly dropped."""
    tokens = _binding_tokens(span)
    summary_text = summarizer(span.text)
    manifest = {"negations": [], "literals": [], "dropped": []}
    for tok in tokens:
        if tok in summary_text:
            manifest["literals"].append(tok)
        else:
            manifest["dropped"].append(tok)
    if manifest["dropped"]:
        raise CompactionBoundaryError(
            f"refusing to commit lossy compaction of {span.span_id}: "
            f"binding tokens dropped without manifest: {manifest['dropped']}"
        )
    return Summary(
        source_span_id=span.span_id,
        text=summary_text,
        raw_span_available=True,
        loss_manifest=manifest,
        generation=1,
    )


def resolve_reference(
    current_turn: str,
    candidate_summary: Optional[Summary],
    raw_store: dict[str, RawSpan],
) -> RawSpan:
    """At restoration time (C3), a binding reference must resolve to the raw
    span, never to the summary text. Refuse if only a summary is reachable."""
    if not _DEICTIC_PATTERN.search(current_turn):
        raise CompactionBoundaryError(
            "resolve_reference called on a non-binding turn; no raw re-read needed"
        )
    if candidate_summary is None:
        raise CompactionBoundaryError(
            "binding reference present but no candidate span located"
        )
    # C4: a terminal summary-of-summary cannot substitute for raw.
    if candidate_summary.generation > 1 and not candidate_summary.raw_span_available:
        raise CompactionBoundaryError(
            f"summary {candidate_summary.source_span_id} is lossy_terminal "
            f"(generation {candidate_summary.generation}); raw span unreachable"
        )
    raw = raw_store.get(candidate_summary.source_span_id)
    if raw is None or not candidate_summary.raw_span_available:
        raise CompactionBoundaryError(
            f"cannot restore binding referent for {candidate_summary.source_span_id}: "
            f"raw span unavailable; summary text is not authoritative"
        )
    # Verify the raw span actually contains the literals the summary claimed.
    for tok in candidate_summary.loss_manifest.get("literals", []):
        if tok not in raw.text:
            raise CompactionBoundaryError(
                f"summary/raw mismatch on token {tok!r} for {raw.span_id}"
            )
    return raw
