# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-semantic-summarization-compaction-has-silently-crossed-the-eviction-budget-the-summary-of-summary-drift-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-semantic-summarization-compaction-has-silently-crossed-the-eviction-budget-the-summary-of-summary-drift-invariant.warrant.json
# Markdown SHA-256:   266bf3df2f9ee7f97d794a180cb2d480d54d9dec9b6d2a5f37a9c82c5d1c9a68
# Code AST SHA-256:   078227bd8c4ca0152c0a651892c878e4cd537036b3348868ba3933692bdfd938
# Verified Classes:   CompactionFidelityError, Tier, Span, CompactionPolicy
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class CompactionFidelityError(RuntimeError):
    """Raised when a compaction policy attempts to re-summarize a span
    past its generation-depth limit without re-grounding to primary source."""


class Tier(Enum):
    VERBATIM = "verbatim"      # secrets, exact tokens, protocol strings
    CONSTRAINT = "constraint"  # paths, IDs, permissions, numeric limits
    NARRATIVE = "narrative"    # explored/abandoned rationale


D_MAX = {
    Tier.VERBATIM: 1,
    Tier.CONSTRAINT: 2,
    Tier.NARRATIVE: 3,
}


@dataclass
class Span:
    span_id: str
    generation: int
    tier: Tier
    token_count: int
    text: str
    parent_token_count: int = 0  # token count of the span this was summarized from


@dataclass
class CompactionPolicy:
    eviction_budget: int
    protected: set[str] = field(default_factory=set)

    def should_summarize(self, span: Span) -> bool:
        if span.span_id in self.protected:
            return False
        if span.generation >= D_MAX[span.tier]:
            return False
        return True

    def compact(self, spans: list[Span], summarize_fn) -> list[Span]:
        out: list[Span] = []
        for span in spans:
            if not self.should_summarize(span):
                # Depth limit reached: must re-ground or promote, never re-summarize.
                if span.generation >= D_MAX[span.tier]:
                    if span.span_id in self.protected:
                        out.append(span)
                        continue
                    # Attempt re-grounding to primary source.
                    primary = self._reground(span)
                    if primary is None:
                        # Cannot re-ground: promote to protected, carry at full cost.
                        self.protected.add(span.span_id)
                        out.append(span)
                        continue
                    new = summarize_fn(primary, target_tokens=span.token_count)
                    new.generation = 1
                    new.parent_token_count = primary.token_count
                    out.append(new)
                else:
                    out.append(span)
                continue

            new = summarize_fn(span, target_tokens=span.token_count)
            new.generation = span.generation + 1
            new.parent_token_count = span.token_count

            # Structural drift signal: summary grew while compressing a summary.
            if new.generation > 1 and new.token_count >= span.token_count:
                raise CompactionFidelityError(
                    f"span {span.span_id}: Gen-{new.generation} summary "
                    f"({new.token_count}t) did not shrink parent "
                    f"({span.token_count}t); compressible content exhausted, "
                    f"re-ground required before further compaction"
                )
            out.append(new)
        return out

    def _reground(self, span: Span):
        # In production: fetch original source span from durable storage.
        return None
