# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-window-and-the-rewrite-is-not-idempotent.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-window-and-the-rewrite-is-not-idempotent.warrant.json
# Markdown SHA-256:   2724014a8bbe87add1af207efee0e94078985f8ea03e93ee336c48764d2df213
# Code AST SHA-256:   feaa00b63a213c458e442561292a25c0d10e7caf3d1c67c17b0549bd31a5288e
# Verified Classes:   PruneReentryError, SpanClass, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class PruneReentryError(RuntimeError):
    """Raised when a prune would re-compress already-pruned content without a fidelity guarantee."""


class SpanClass(Enum):
    USER_CONSTRAINT = "user_constraint"      # non_compressible, always verbatim
    DERIVED_INVARIANT = "derived_invariant"  # promoted on first use, non_compressible
    TOOL_OUTPUT = "tool_output"              # compressible
    PRUNED = "pruned"                        # residue of a prior prune: atomic


@dataclass
class Span:
    text: str
    klass: SpanClass
    provenance: Optional[str] = None         # e.g. "pruned_v1"
    subsumes: tuple = field(default_factory=tuple)


def prune(spans: list, budget_tokens: int, token_len) -> list:
    """
    Re-entrant prune. Refuses to re-compress PRUNED spans unless the caller
    explicitly passes a fidelity floor that the new summary can meet.
    """
    # 1. Non-compressible spans are pinned verbatim.
    pinned = [s for s in spans if s.klass in (SpanClass.USER_CONSTRAINT,
                                               SpanClass.DERIVED_INVARIANT)]
    # 2. Pruned residue is atomic: it may be carried forward, never re-summarized.
    residue = [s for s in spans if s.klass is SpanClass.PRUNED]
    compressible = [s for s in spans if s.klass is SpanClass.TOOL_OUTPUT]

    # 3. If we are over budget and the only remaining slack is pruned residue,
    #    we must NOT re-compress it. Raise instead of silently decaying fidelity.
    pinned_cost = sum(token_len(s.text) for s in pinned + residue)
    compressible_cost = sum(token_len(s.text) for s in compressible)

    if pinned_cost > budget_tokens:
        raise PruneReentryError(
            f"pinned+residue cost {pinned_cost} exceeds budget {budget_tokens}; "
            f"re-compressing pruned spans would silently drop derived invariants. "
            f"Escalate (more budget) or restart from immutable log."
        )

    # 4. Compress only TOOL_OUTPUT spans; tag the result as PRUNED so a later
    #    pass treats it as atomic.
    headroom = budget_tokens - pinned_cost
    kept, dropped = [], []
    running = 0
    for s in reversed(compressible):          # keep most recent first
        if running + token_len(s.text) <= headroom:
            kept.append(s)
            running += token_len(s.text)
        else:
            dropped.append(s)

    out = pinned + residue + list(reversed(kept))
    if dropped:
        summary = "summary of " + str(len(dropped)) + " earlier tool outputs"
        out.append(Span(
            text=summary,
            klass=SpanClass.PRUNED,
            provenance="pruned_v1",
            subsumes=tuple(id(s) for s in dropped),
        ))
    return out


def apply_prune(spans, budget_tokens, token_len):
    try:
        return prune(spans, budget_tokens, token_len)
    except PruneReentryError as e:
        # Guardrail: never fall back to re-compressing residue.
        raise PruneReentryError(f"prune aborted, buffer left intact: {e}") from e
