# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-honor-its-own-pruning-policy-when-the-eviction-relevance-score-was-computed-against-a-context-that-the-pruning-itself.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-honor-its-own-pruning-policy-when-the-eviction-relevance-score-was-computed-against-a-context-that-the-pruning-itself.warrant.json
# Markdown SHA-256:   aa967b79b13db9a02d813af6e40b9249838b8d2b6e3d9b8bff303e65376797d0
# Code AST SHA-256:   28af13960d8d86dc9c15e931e1eb2eba56f72bfe48427efe706cd7364b7d43ea
# Verified Classes:   UnsafeSelfPruneError, Span, ContextWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class UnsafeSelfPruneError(RuntimeError):
    """Raised when a relevance-scored eviction is attempted against a mutable anchor."""
    pass


@dataclass
class Span:
    span_id: str
    text: str
    pinned: bool = False
    score: float = 0.0


@dataclass
class ContextWindow:
    spans: list[Span]
    intent_summary: str
    audit_log: list[dict] = field(default_factory=list)

    def anchor_hash(self) -> str:
        pinned = "".join(s.text for s in self.spans if s.pinned)
        return hashlib.sha256(pinned.encode()).hexdigest()[:16]


def self_prune(window: ContextWindow, evict_fraction: float, scoring_anchor: str) -> ContextWindow:
    """
    Execute a model-authored relevance eviction.

    scoring_anchor must be 'pinned' or 'external'. If it is 'intent_summary',
    the score is computed against state the edit will destroy -> refuse.
    """
    if scoring_anchor not in ("pinned", "external"):
        raise UnsafeSelfPruneError(
            f"Refusing relevance eviction: scoring anchor '{scoring_anchor}' is mutable "
            f"and lies inside the eviction blast radius. Anchor hash would change from "
            f"{window.anchor_hash()} to an unknown value. Escalate to external compaction."
        )

    candidates = [s for s in window.spans if not s.pinned]
    candidates.sort(key=lambda s: s.score)
    n_evict = int(len(candidates) * evict_fraction)

    # Disambiguator-closure check: every entity referenced in the summary must
    # retain at least one supporting span after eviction.
    evicted_ids = {s.span_id for s in candidates[:n_evict]}
    retained = [s for s in window.spans if s.span_id not in evicted_ids]
    retained_text = " ".join(s.text for s in retained).lower()
    for token in _entities(window.intent_summary):
        if token.lower() not in retained_text:
            raise UnsafeSelfPruneError(
                f"Refusing eviction: entity '{token}' referenced in intent summary has no "
                f"surviving binding after eviction. Cascade rewrite would silently drop "
                f"a hard constraint."
            )

    # Witness: copy evicted spans to the non-editable audit log with score + anchor hash.
    for s in candidates[:n_evict]:
        window.audit_log.append({
            "evicted": s.span_id,
            "text": s.text,
            "score": s.score,
            "anchor_hash": window.anchor_hash(),
        })

    window.spans = retained
    return window


def _entities(summary: str) -> list[str]:
    # Toy extraction: quoted or backticked identifiers.
    import re
    return re.findall(r"[`\"]([^`\"]+)[`\"]", summary)
