# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-prune-a-context-segment-whose-relevance-is-only-recoverable-through-the-segment-it-is-about-to-delete.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-prune-a-context-segment-whose-relevance-is-only-recoverable-through-the-segment-it-is-about-to-delete.warrant.json
# Markdown SHA-256:   565f7cfc3bf58e1f845465005def6f5c8d40fcc7988f4394f810c8bb18806034
# Code AST SHA-256:   99d2390997e095038ff69228dd287b32744ca03374c41497ea27507d3ec10a62
# Verified Classes:   UnsoundPruneError, Segment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnsoundPruneError(RuntimeError):
    """Raised when a pruning plan is not a fixed point of the relevance scorer."""
    pass


@dataclass
class Segment:
    sid: str
    text: str
    defines: frozenset[str] = field(default_factory=frozenset)   # terms/schemas/units declared
    references: frozenset[str] = field(default_factory=frozenset)  # terms/schemas/units used


def score(goal: str, segment: Segment, window: list[Segment]) -> float:
    """Relevance of `segment` given the full window. Depends on window, not just segment."""
    # A reference is only legible if some segment in the window defines it.
    defined = set().union(*(s.defines for s in window)) if window else set()
    orphaned = segment.references - defined
    base = 0.6 if goal.lower() in segment.text.lower() else 0.2
    return max(0.0, base - 0.5 * len(orphaned))


def plan_prune(goal: str, window: list[Segment], threshold: float = 0.3) -> list[str]:
    """Return sids to evict. Refuses if the plan breaks the fixed-point invariant."""
    pre = {s.sid: score(goal, s, window) for s in window}
    evict = {s.sid for s in window if pre[s.sid] < threshold}
    survivors = [s for s in window if s.sid not in evict]
    post = {s.sid: score(goal, s, survivors) for s in survivors}

    for sid, p in post.items():
        # A survivor whose score collapsed after eviction was dependent on an evicted definer.
        if p < threshold <= pre[sid]:
            raise UnsoundPruneError(
                f"segment {sid!r} scored {pre[sid]:.2f} pre-eviction but {p:.2f} "
                f"post-eviction: its definer was in the eviction set. "
                f"Retain the definer or inline the definition before pruning."
            )
    return sorted(evict)


def safe_prune(goal: str, window: list[Segment], threshold: float = 0.3) -> list[Segment]:
    """Prune with dependency-cluster closure: never orphan a survivor."""
    try:
        evict = set(plan_prune(goal, window, threshold))
    except UnsoundPruneError:
        # Fallback: only evict segments with no inbound references from survivors.
        survivors = [s for s in window if s.sid not in
                     {x.sid for x in window if score(goal, x, window) < threshold}]
        used = set().union(*(s.references for s in survivors)) if survivors else set()
        evict = {s.sid for s in window
                 if score(goal, s, window) < threshold and not (s.defines & used)}
        if any(score(goal, s, [x for x in window if x.sid not in evict]) < threshold
               for s in window if s.sid not in evict):
            raise UnsoundPruneError("no sound pruning plan exists; defer to checkpoint")
    return [s for s in window if s.sid not in evict]
