# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hierarchical-summarization-compaction-as-a-lossy-invariant-rather-than-a-safe-memory-optimization.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hierarchical-summarization-compaction-as-a-lossy-invariant-rather-than-a-safe-memory-optimization.warrant.json
# Markdown SHA-256:   d34acce224a75f36326b27ac198fb5ec176adc6fe87dd06db756d68becd5d2d3
# Code AST SHA-256:   3c93e83f025f247ff9b279794ade6a10e1ca72b9581fe22fc1fda7d09a245c65
# Verified Classes:   CompactionManifestViolation, Constraint, CompactionResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CompactionManifestViolation(RuntimeError):
    """Raised when a hierarchical summary fails to preserve the constraint manifest."""


@dataclass
class Constraint:
    key: str            # stable identifier, e.g. "forbid_path:migrations/0007_*.sql"
    polarity: bool      # True = must hold, False = must not happen
    payload: str        # verbatim predicate text


@dataclass
class CompactionResult:
    summary_text: str
    tokens_before: int
    tokens_after: int
    manifest: list[Constraint] = field(default_factory=list)


def extract_manifest(region_text: str) -> list[Constraint]:
    # In production this is a deterministic extractor (regex + schema match),
    # NOT the summarizer model — the extractor must be lossless.
    raise NotImplementedError("wire to deterministic predicate extractor")


def rederive_manifest(summary_text: str) -> list[Constraint]:
    # Re-run the extractor over the summary alone. Anything the summary
    # dropped will be absent here and caught by the diff below.
    raise NotImplementedError("wire to deterministic predicate extractor")


def commit_compaction(region_text: str, summary: CompactionResult) -> CompactionResult:
    pre = extract_manifest(region_text)
    post = rederive_manifest(summary.summary_text)

    pre_map = {(c.key, c.polarity): c for c in pre}
    post_map = {(c.key, c.polarity): c for c in post}

    dropped = [k for k in pre_map if k not in post_map]
    flipped = [
        k for k in pre_map
        if k not in post_map and (k[0], not k[1]) in post_map
    ]

    if dropped or flipped:
        raise CompactionManifestViolation(
            f"compaction rejected: dropped={dropped!r} polarity_flipped={flipped!r}. "
            f"Fall back to eviction-with-sidecar; do NOT commit summary."
        )

    summary.manifest = pre
    return summary


def maybe_compact(region_text: str, budget_ratio: float, summarize_fn) -> CompactionResult:
    summary_text = summarize_fn(region_text, budget_ratio)
    result = CompactionResult(
        summary_text=summary_text,
        tokens_before=len(region_text.split()),
        tokens_after=len(summary_text.split()),
    )
    return commit_compaction(region_text, result)
