# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-task-critical-state-when-automatic-compaction-summarizes-the-wrong-slice-of-its-own-history.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-task-critical-state-when-automatic-compaction-summarizes-the-wrong-slice-of-its-own-history.warrant.json
# Markdown SHA-256:   60a77010458aa235effdb930d211212e12bfc858cece31711cdca430c28a7bf3
# Code AST SHA-256:   7cb9d77c156c52f4c4954ec0c3403b481573cb088a13009b8e8ee3a20db19dab
# Verified Classes:   CompactionIntegrityError, Turn, CompactionPlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionIntegrityError(RuntimeError):
    """Raised when a compaction pass would drop a literal binding that future
    references depend on, or when the summarizer reserve is insufficient."""
    pass


@dataclass
class Turn:
    idx: int
    text: str
    # literal bindings introduced this turn: name -> opaque value
    bindings: dict = field(default_factory=dict)
    # names referenced this turn (must resolve against surviving state)
    references: list = field(default_factory=list)


@dataclass
class CompactionPlan:
    pinned: list       # turns carried verbatim (contain literal bindings)
    to_summarize: list # turns eligible for lossy compression
    reserve_tokens: int


def plan_compaction(
    turns: list,
    budget_tokens: int,
    current_tokens: int,
    trigger_ratio: float = 0.85,
    summarizer_max_tokens: int = 2000,
) -> Optional[CompactionPlan]:
    if current_tokens < budget_tokens * trigger_ratio:
        return None  # no pressure, no compaction

    # Reserve is MEASURED from the summarizer's hard cap, not guessed.
    reserve = summarizer_max_tokens
    headroom = budget_tokens - current_tokens + reserve

    # Classify: any turn that introduces a binding is pinned unconditionally.
    # Irreversibility is orthogonal to recency/relevance, so we do not rank.
    pinned = [t for t in turns if t.bindings]
    to_summarize = [t for t in turns if not t.bindings]

    # Invariant check: every reference in the *surviving* set must resolve
    # against a pinned binding or a verbatim-kept turn. If a reference's
    # binding lives only inside a to-be-summarized turn, we cannot drop it.
    surviving_names = set()
    for t in pinned:
        surviving_names.update(t.bindings.keys())

    for t in to_summarize:
        for ref in t.references:
            if ref not in surviving_names:
                # Binding exists only in a turn we were about to compress.
                # Promote that turn to pinned rather than lose the literal.
                owner = next(
                    (o for o in turns if ref in o.bindings), None
                )
                if owner is None:
                    raise CompactionIntegrityError(
                        f"reference {ref!r} at turn {t.idx} has no binding "
                        f"anywhere in transcript; state already corrupt"
                    )
                if owner not in pinned:
                    pinned.append(owner)
                    surviving_names.update(owner.bindings.keys())

    pinned_cost = sum(len(t.text) // 4 for t in pinned)  # rough token est.
    if pinned_cost > headroom:
        raise CompactionIntegrityError(
            f"pinned literals need {pinned_cost} tokens but only "
            f"{headroom} available after reserving {reserve} for summarizer; "
            f"compaction cannot proceed without dropping a live binding"
        )

    return CompactionPlan(
        pinned=pinned,
        to_summarize=to_summarize,
        reserve_tokens=reserve,
    )


def execute_compaction(plan: CompactionPlan, turns: list) -> list:
    if plan is None:
        return turns
    # Digests are marked so they are never re-summarized (idempotence).
    digest_turns = []
    for t in plan.to_summarize:
        digest_turns.append(Turn(
            idx=t.idx,
            text=f"[digest of turns {t.idx}]",
            bindings={},           # digests never carry bindings
            references=[],         # digests never introduce references
        ))
    result = plan.pinned + digest_turns
    result.sort(key=lambda t: t.idx)
    return result
