# 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-retained-token-budget-is-satisfied-but-the-eviction-frontier-falls-inside-an-active.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-auto-compaction-when-the-retained-token-budget-is-satisfied-but-the-eviction-frontier-falls-inside-an-active.warrant.json
# Markdown SHA-256:   fe13e1b0d1342bea4604f663bd2fdc951509172b056f692f3f6e68df717f08c8
# Code AST SHA-256:   6a6b66a33deaefbb3b04023e5528018c572833559b14fb656ece4d1260380163
# Verified Classes:   CompactionFrontierError, Message
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Literal, Sequence


class CompactionFrontierError(RuntimeError):
    """Raised when an auto-compaction frontier would bisect a tool-call transaction."""


@dataclass(frozen=True)
class Message:
    index: int
    role: Literal["user", "assistant", "tool_call", "tool_result"]
    call_id: str | None = None
    status: Literal["pending", "completed"] | None = None


def _pair_span(messages: Sequence[Message], call_id: str) -> tuple[int, int]:
    call_idx = next((m.index for m in messages if m.role == "tool_call" and m.call_id == call_id), None)
    res_idx = next((m.index for m in messages if m.role == "tool_result" and m.call_id == call_id), None)
    if call_idx is None or res_idx is None:
        raise CompactionFrontierError(f"incomplete tool transaction for call_id={call_id!r}")
    return call_idx, res_idx


def validate_frontier(messages: Sequence[Message], frontier: int, tokens_used: int, threshold: int) -> int:
    """
    Return a legal, pair-aligned frontier at or before the requested one.
    Refuses outright if any pending tool call exists at compaction time.
    """
    if tokens_used < threshold:
        return frontier  # no compaction needed

    pending = [m for m in messages if m.role == "tool_call" and m.status == "pending"]
    if pending:
        raise CompactionFrontierError(
            f"refusing compaction: {len(pending)} pending tool call(s) would be orphaned"
        )

    # Collect the atomic spans of every completed tool transaction.
    spans: list[tuple[int, int]] = []
    seen: set[str] = set()
    for m in messages:
        if m.role == "tool_call" and m.call_id and m.call_id not in seen:
            seen.add(m.call_id)
            spans.append(_pair_span(messages, m.call_id))

    # Snap the frontier backward until it clears every span it would bisect.
    legal = frontier
    changed = True
    while changed:
        changed = False
        for lo, hi in spans:
            if lo < legal <= hi:
                legal = lo  # evict the whole pair rather than split it
                changed = True

    if legal != frontier:
        # Caller must be able to see that the frontier was adjusted.
        return legal
    return legal
