# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hierarchical-summarization-compaction-as-unsafe-when-salience-scores-are-computed-over-already-summarized-spa.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hierarchical-summarization-compaction-as-unsafe-when-salience-scores-are-computed-over-already-summarized-spa.warrant.json
# Markdown SHA-256:   72d2960e848a4d58548415cab72b4adf5f77497e1056a55482bf484478dd1e07
# Code AST SHA-256:   cf5fbe228132346123bc54f700e0a85bb1c9c9091739f0ea19e42ad375db97d0
# Verified Classes:   CompactionInvariantError, SpanClass, Node
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CompactionInvariantError(RuntimeError):
    """Raised when a compaction decision would violate level-partitioned eviction
    or evidence pinning. Halting is always preferable to a lossy eviction that
    removes a span whose contradicting evidence has already been summarized away."""


class SpanClass(Enum):
    EVIDENCE = "evidence"      # verbatim error, command, config, code, numeric, user constraint
    NARRATIVE = "narrative"    # ordinary conversational / reasoning span


@dataclass
class Node:
    node_id: str
    level: int                       # 0 = raw, 1 = branch summary, 2 = root-ward
    salience: float                  # 0..100, scorer output at this level
    span_class: SpanClass
    score_inherited: bool = False    # True if salience was copied from a merged parent
    source_ids: frozenset[str] = field(default_factory=frozenset)


def select_evictions(nodes: Iterable[Node], budget_tokens: int,
                     token_cost: dict[str, int]) -> list[str]:
    nodes = list(nodes)

    # Guard 1: refuse cross-level global ranking outright.
    levels = {n.level for n in nodes}
    if len(levels) > 1:
        raise CompactionInvariantError(
            f"eviction ranker received mixed hierarchy levels {sorted(levels)}; "
            "salience scores are not comparable across levels. Partition first."
        )

    # Guard 2: inherited scores are not valid eviction signals at any level.
    for n in nodes:
        if n.score_inherited:
            raise CompactionInvariantError(
                f"node {n.node_id} carries an inherited salience score; "
                "it cannot be ranked against siblings scored in place."
            )

    # Guard 3: evidence-class spans are pinned and never eviction candidates.
    ranked = sorted(
        (n for n in nodes if n.span_class is not SpanClass.EVIDENCE),
        key=lambda n: n.salience,
    )

    evicted: list[str] = []
    freed = 0
    for n in ranked:
        if freed >= budget_tokens:
            break
        evicted.append(n.node_id)
        freed += token_cost.get(n.node_id, 0)

    # Guard 4: if budget cannot be met without touching pinned evidence,
    # signal externalization rather than silently over-evicting narrative.
    if freed < budget_tokens:
        raise CompactionInvariantError(
            f"budget shortfall of {budget_tokens - freed} tokens after evicting all "
            "eligible narrative spans; pinned evidence must be externalized to durable "
            "storage with content hashes, not evicted."
        )

    return evicted
