# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-auto-compaction-when-the-summarizer-s-own-context-window-is-smaller-than-the-transcript-it-is-compacting.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-auto-compaction-when-the-summarizer-s-own-context-window-is-smaller-than-the-transcript-it-is-compacting.warrant.json
# Markdown SHA-256:   75f59b01c0c4b4c6d006a1f849d782341ef2382fb69cc8051cbf5873974571d8
# Code AST SHA-256:   92abbbdf957249b2f1b4cd84dc190e34127741e221266459f546a04842ec4519
# Verified Classes:   CompactionCoverageError, CompactionBudget
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass


class CompactionCoverageError(RuntimeError):
    """Raised when a compaction unit cannot be soundly summarized by the
    configured summarizer, because the summarizer's effective input budget
    is not strictly greater than the unit plus its own overhead.

    This is a *refusal*, not a degradation: the caller must fall back to
    lossless externalization for this unit rather than compact it.
    """


@dataclass(frozen=True)
class CompactionBudget:
    summarizer_window: int          # tokens the summarizer model can attend to
    preamble_tokens: int            # system prompt + instructions + schema
    output_reservation: int        # tokens reserved for the summary itself
    safety_margin: float = 0.08     # tokenizer-drift buffer, fraction of window

    @property
    def effective_input_budget(self) -> int:
        margin = int(self.summarizer_window * self.safety_margin)
        return self.summarizer_window - self.preamble_tokens - self.output_reservation - margin


def plan_compaction(
    unit_token_lengths: list[int],
    budget: CompactionBudget,
    *,
    stack_raises_on_overflow: bool,
) -> list[str]:
    """Decide, per unit, whether to COMPACT or EXTERNALIZE.

    Returns a plan aligned with unit_token_lengths. Raises
    CompactionCoverageError if a unit would be silently truncated and no
    safe fallback is available at the call site.
    """
    plan: list[str] = []
    budget_ok = budget.effective_input_budget

    if budget_ok <= 0:
        raise CompactionCoverageError(
            f"Summarizer overhead ({budget.preamble_tokens} preamble + "
            f"{budget.output_reservation} output + margin) exhausts the "
            f"{budget.summarizer_window}-token window; no unit can be soundly compacted."
        )

    for idx, n in enumerate(unit_token_lengths):
        if n <= budget_ok:
            plan.append("COMPACT")
            continue

        # Unit exceeds the summarizer's real capacity. A summary here would
        # describe a prefix and silently drop the tail.
        if not stack_raises_on_overflow:
            # Cannot even detect the truncation -> must not compact.
            plan.append("EXTERNALIZE")
            continue

        # Stack would raise, but we can do better: refuse compaction of this
        # unit and externalize, rather than let it raise mid-fold.
        raise CompactionCoverageError(
            f"Unit {idx} is {n} tokens but summarizer effective budget is "
            f"{budget_ok}; compacting would amputate a tail of history. "
            f"Externalize this unit verbatim and emit a pointer record."
        )

    return plan


def verify_compaction_output(
    source_tokens: int,
    summary_tokens: int,
    rolling_median_ratio: float,
    *,
    floor_factor: float = 0.5,
) -> None:
    """Post-check: a summary far smaller than baseline signals a coverage gap,
    not efficiency. Call BEFORE freeing the source tokens."""
    if source_tokens <= 0:
        raise CompactionCoverageError("Empty source unit; nothing to compact.")
    ratio = summary_tokens / source_tokens
    if ratio < floor_factor * rolling_median_ratio:
        raise CompactionCoverageError(
            f"Compression ratio {ratio:.3f} is below "
            f"{floor_factor} x median {rolling_median_ratio:.3f}; "
            f"summary is suspect (likely input truncation). Re-inflate from "
            f"retained source and re-compact in smaller sub-units."
        )


# --- usage sketch -------------------------------------------------------
def fold_transcript(unit_lengths: list[int], budget: CompactionBudget) -> list[str]:
    plan = plan_compaction(unit_lengths, budget, stack_raises_on_overflow=False)
    for i, decision in enumerate(plan):
        if decision == "COMPACT":
            # ... summarize unit i, then:
            verify_compaction_output(
                source_tokens=unit_lengths[i],
                summary_tokens=int(unit_lengths[i] * 0.15),  # observed output
                rolling_median_ratio=0.15,
            )
    return plan
