# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-score-context-compaction-when-the-summarizer-is-the-same-model-that-will-later-depend-on-the-summary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-score-context-compaction-when-the-summarizer-is-the-same-model-that-will-later-depend-on-the-summary.warrant.json
# Markdown SHA-256:   d58058d97bc69e6ea497ab71aff144ebb9ac19677599f8ce660dddf58bf3d9a2
# Code AST SHA-256:   71524d9e9b32c40a02a15b3871606d6421883df190375f3a537502218370c02f
# Verified Classes:   CompactionSufficiencyError, ProtectedInventory
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CompactionSufficiencyError(RuntimeError):
    """Raised when a self-produced summary drops a protected span.

    Fidelity metrics are irrelevant here: the compressor and consumer share
    weights, so similarity is a self-report and cannot gate acceptance.
    """


@dataclass
class ProtectedInventory:
    constraints: list[str] = field(default_factory=list)
    identifiers: list[str] = field(default_factory=list)
    error_strings: list[str] = field(default_factory=list)

    def all_spans(self) -> Iterable[str]:
        yield from self.constraints
        yield from self.identifiers
        yield from self.error_strings


def score_compaction(summary: str, inventory: ProtectedInventory) -> float:
    spans = list(inventory.all_spans())
    if not spans:
        return 1.0
    norm = summary.lower()
    present = sum(1 for s in spans if s.lower() in norm)
    return present / len(spans)


def gate_compaction(summary: str, inventory: ProtectedInventory) -> None:
    recall = score_compaction(summary, inventory)
    if recall < 1.0:
        missing = [s for s in inventory.all_spans() if s.lower() not in summary.lower()]
        raise CompactionSufficiencyError(
            f"protected-span recall {recall:.2f} < 1.0; "
            f"dropped spans: {missing}. Re-summarize with pins or write sidecar."
        )


def compact_with_gate(raw_context: str, summarizer, inventory: ProtectedInventory) -> str:
    summary = summarizer(raw_context)
    try:
        gate_compaction(summary, inventory)
    except CompactionSufficiencyError:
        # structural bypass: carry protected spans outside the summarizer
        sidecar = "\n".join(f"PINNED: {s}" for s in inventory.all_spans())
        summary = summary + "\n\n" + sidecar
        gate_compaction(summary, inventory)  # must now pass, else escalate
    return summary
