# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-compaction-checkpoint-because-the-summarizer-s-own-context-window-is-already-saturated-by-the-transcript-i.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-compaction-checkpoint-because-the-summarizer-s-own-context-window-is-already-saturated-by-the-transcript-i.warrant.json
# Markdown SHA-256:   2413333ac350e109ecd36b384430750a1c1fc4ec6259ccee8c01ec28215fa042
# Code AST SHA-256:   32a6cda72a496352839de6e02a9aa73efea3f80d82d9a067bd9996bbe22259ea
# Verified Classes:   CompactionInfeasibleError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CompactionInfeasibleError(RuntimeError):
    """Raised when a compaction span exceeds the summarizer's honest-read budget.

    The span must be folded or externalized; a flat summarize call would
    silently summarize a truncation of the span.
    """


SUMMARIZER_WINDOW = 32_000
SAFETY_MARGIN = 0.08          # observed safe margin on code/JSON-heavy transcripts
FLAT_CALL_CEILING = 0.60      # fraction of window below which flat summarize is safe
FOLD_TRIGGER = 0.92           # above this, refuse the flat call outright
MAX_FOLD_DEPTH = 3


def plan_compaction(span_tokens, summarizer_overhead, fold_depth=0):
    usable = SUMMARIZER_WINDOW * (1.0 - SAFETY_MARGIN)
    budget = usable - summarizer_overhead
    if budget <= 0:
        raise CompactionInfeasibleError(
            f"summarizer_overhead={summarizer_overhead} consumes the entire "
            f"usable window {usable:.0f}; no span can be honestly summarized"
        )

    ratio = span_tokens / budget
    if ratio <= FLAT_CALL_CEILING:
        return {"mode": "flat", "span": span_tokens, "depth": fold_depth}

    if ratio > FOLD_TRIGGER:
        if fold_depth >= MAX_FOLD_DEPTH:
            return {"mode": "externalize", "span": span_tokens, "depth": fold_depth}
        n_sub = int(span_tokens // (budget * FLAT_CALL_CEILING)) + 1
        sub_span = span_tokens / n_sub
        if sub_span / budget > FLAT_CALL_CEILING:
            raise CompactionInfeasibleError(
                f"cannot fold span={span_tokens} at depth={fold_depth}: "
                f"sub_span={sub_span:.0f} still exceeds flat-call ceiling "
                f"{budget * FLAT_CALL_CEILING:.0f}"
            )
        return {
            "mode": "fold",
            "span": span_tokens,
            "sub_spans": n_sub,
            "sub_span": sub_span,
            "depth": fold_depth + 1,
        }

    # 60% < ratio <= 92%: flat call is permitted but must be probed for
    # truncation afterward; if the probe fails, escalate to fold.
    return {"mode": "flat_probed", "span": span_tokens, "depth": fold_depth}


def compact(transcript_span_tokens, summarizer_overhead, fold_depth=0):
    plan = plan_compaction(transcript_span_tokens, summarizer_overhead, fold_depth)
    if plan["mode"] == "externalize":
        # Pointer + verified index is cheaper than a deep lossy fold.
        return {"action": "externalize", "provenance": plan}
    if plan["mode"] == "fold":
        # Recurse over sub-spans, then summarize the concatenated sub-summaries.
        for i in range(plan["sub_spans"]):
            compact(plan["sub_span"], summarizer_overhead, plan["depth"])
        return {"action": "fold", "provenance": plan}
    # flat or flat_probed: caller must attach provenance and, for probed,
    # run a tail-coverage check on the returned summary.
    return {"action": plan["mode"], "provenance": plan}


if __name__ == "__main__":
    # 80k span against a 32k summarizer window: the boundary case.
    try:
        plan_compaction(span_tokens=80_000, summarizer_overhead=2_000)
    except CompactionInfeasibleError as e:
        raise CompactionInfeasibleError(
            "flat summarize of an 80k span at a 32k window would clip the "
            "interior; fold or externalize instead"
        ) from e
