# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-eviction-induced-referent-orphaning-when-model-driven-pruning-deletes-an-antecedent-that-a-retained-span-still-depends-on.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-eviction-induced-referent-orphaning-when-model-driven-pruning-deletes-an-antecedent-that-a-retained-span-still-depends-on.warrant.json
# Markdown SHA-256:   9d65e9d4a5b95f444fa84b4f7b45177ecc66857f2ba95d12852f5a026be9d5e1
# Code AST SHA-256:   6d4036b254563282c28a1c74d1ff28135b8be02ecd944b063c06600f2e73c483
# Verified Classes:   ReferentOrphaningError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ReferentOrphaningError(RuntimeError):
    """Raised when eviction would leave a retained span with no antecedent."""


@dataclass
class Span:
    id: str
    text: str
    # symbolic bindings *defined* here and references *used* here
    defines: set[str] = field(default_factory=set)
    uses: set[str] = field(default_factory=set)


def plan_eviction(spans: list[Span], evict_ids: Iterable[str]) -> list[str]:
    """
    Given a set of candidate evictions (chosen by relevance score),
    return the safe eviction set, or raise if a retained span would be orphaned.

    Invariant: a span A is evictable only if no retained span uses a symbol
    that A defines and that no other retained span also defines.
    """
    evict = set(evict_ids)
    retained = [s for s in spans if s.id not in evict]

    # Symbols defined by the evicted set.
    evicted_defs: dict[str, str] = {}
    for s in spans:
        if s.id in evict:
            for sym in s.defines:
                evicted_defs[sym] = s.id

    # Symbols still defined by survivors (a redefinition rescues the symbol).
    survivor_defs: set[str] = set()
    for s in retained:
        survivor_defs |= s.defines

    orphans: list[tuple[str, str, str]] = []  # (retained_span, symbol, evicted_definer)
    for s in retained:
        for sym in s.uses:
            if sym in evicted_defs and sym not in survivor_defs:
                orphans.append((s.id, sym, evicted_defs[sym]))

    if orphans:
        detail = "; ".join(
            f"span {r} uses '{sym}' defined only in evicted {d}"
            for r, sym, d in orphans
        )
        raise ReferentOrphaningError(
            "Eviction would orphan retained references: " + detail
        )

    return sorted(evict)


def compact_with_inlining(spans: list[Span], evict_ids: Iterable[str]) -> list[Span]:
    """
    Safe compaction: inline antecedents into dependents before dropping definers.
    Falls back to raising if inlining is not possible.
    """
    evict = set(evict_ids)
    definers = {s.id: s for s in spans if s.id in evict}
    out: list[Span] = []

    for s in spans:
        if s.id in evict:
            continue
        new_text = s.text
        remaining_uses = set(s.uses)
        for sym in list(s.uses):
            definer = next((d for d in definers.values() if sym in d.defines), None)
            if definer is None:
                continue
            # inline: replace the bare symbol with a self-contained literal
            literal = definer.text  # caller supplies the literal in definer.text
            new_text = new_text.replace(sym, literal)
            remaining_uses.discard(sym)
        out.append(Span(s.id, new_text, defines=set(s.defines), uses=remaining_uses))

    # Second pass: any use still unresolved by a survivor => hard fail.
    survivor_defs: set[str] = set()
    for s in out:
        survivor_defs |= s.defines
    for s in out:
        unresolved = s.uses - survivor_defs
        if unresolved:
            raise ReferentOrphaningError(
                f"span {s.id} still references {sorted(unresolved)} after inlining; "
                "refusing to compact"
            )
    return out
