# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-compact-the-rehydration-fidelity-invariant-at-the-summarization-tool-pointer-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-compact-the-rehydration-fidelity-invariant-at-the-summarization-tool-pointer-boundary.warrant.json
# Markdown SHA-256:   a0c6b3ece7f9ff4810baf7980c97f19ff0fdda13668f9db6df6ff00f1bf5d771
# Code AST SHA-256:   be674a0b20b84deab3f29ed6aca8c6a42b30ccbf6d0f899f46875ed226c83259
# Verified Classes:   CompactionRefused, ReferentKind, Referent, Span, CompactionResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class CompactionRefused(RuntimeError):
    """Raised when a compaction pass cannot preserve all non-reconstructible referents."""
    pass


class ReferentKind(str, Enum):
    RESUME_TOKEN = "resume_token"
    IDEMPOTENCY_KEY = "idempotency_key"
    CHECKPOINT_HASH = "checkpoint_hash"
    WARRANT_SIGNATURE = "warrant_signature"


@dataclass
class Referent:
    kind: ReferentKind
    literal: str
    for_operation: str
    step: int


@dataclass
class Span:
    text: str
    referents: list[Referent] = field(default_factory=list)


@dataclass
class CompactionResult:
    prose_summary: str
    pointer_sidecar: list[Referent]
    tokens_used: int


def compact(span: Span, prose_budget: int, sidecar_budget: int) -> CompactionResult:
    # Referents are never summarized; they are hoisted verbatim.
    sidecar = list(span.referents)
    sidecar_tokens = sum(len(r.literal) + len(r.for_operation) + 16 for r in sidecar)

    if sidecar_tokens > sidecar_budget:
        # The pointers alone exceed the sidecar budget. We must NOT drop them
        # to fit; the span is not compactible. Refuse and escalate.
        raise CompactionRefused(
            f"pointer sidecar needs {sidecar_tokens} tokens > budget {sidecar_budget}; "
            f"span has {len(sidecar)} non-reconstructible referents "
            f"(steps {[r.step for r in sidecar]}). Checkpoint and hand off instead."
        )

    remaining = prose_budget - sidecar_tokens
    if remaining <= 0:
        raise CompactionRefused(
            f"no prose budget remaining after reserving {sidecar_tokens} pointer tokens"
        )

    # Only the prose remainder is eligible for lossy summarization.
    prose_summary = _summarize(span.text, remaining)
    return CompactionResult(
        prose_summary=prose_summary,
        pointer_sidecar=sidecar,
        tokens_used=len(prose_summary) + sidecar_tokens,
    )


def _summarize(text: str, budget: int) -> str:
    # Placeholder for the lossy summarizer; assumed to respect budget.
    return text[:budget]


def rehydrate(query: str, spans: list[Span], sidecar: list[Referent]) -> Optional[Referent]:
    # A referent request must be satisfied from the sidecar, never from a
    # similarity match over summarized prose.
    for ref in sidecar:
        if ref.for_operation in query or ref.literal in query:
            return ref
    return None


if __name__ == "__main__":
    span = Span(
        text="Resumed migration from the cursor returned at step 14 and continued batches.",
        referents=[
            Referent(
                kind=ReferentKind.RESUME_TOKEN,
                literal="mig_7d2e9a4b::offset=18422",
                for_operation="batch_migration",
                step=14,
            )
        ],
    )
    try:
        result = compact(span, prose_budget=400, sidecar_budget=8)
    except CompactionRefused as e:
        print(f"refused: {e}")
    else:
        print(result)
