# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-pruning-policy-has-silently-orphaned-a-live-reasoning-dependency.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-pruning-policy-has-silently-orphaned-a-live-reasoning-dependency.warrant.json
# Markdown SHA-256:   b8c9af435956fc65588ea92793614e15e467a6fe2d73f3b14007bffcb484cb84
# Code AST SHA-256:   169e9d8c0914d70da109984995db6d76b81b6b808d4b9515eea7ea5502e0b19c
# Verified Classes:   PruneSafetyError, Reconstructibility, Segment, PruneDecision
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class PruneSafetyError(RuntimeError):
    """Raised when a prune would orphan a live reasoning dependency."""
    pass


class Reconstructibility(Enum):
    DETERMINISTIC = "deterministic"   # re-fetch is idempotent + affordable
    HANDLED = "handled"               # content-addressed pointer retained
    ORPHAN_RISK = "orphan_risk"       # neither; must compress, not delete


@dataclass
class Segment:
    seg_id: str
    body: str
    reconstructibility: Reconstructibility
    out_degree: int = 0               # assertions citing this segment
    future_read_set: frozenset = field(default_factory=frozenset)


@dataclass
class PruneDecision:
    seg_id: str
    action: str                       # "delete" | "compress" | "retain"
    reason: str


def decide_prune(seg: Segment, relevance: float, threshold: float) -> PruneDecision:
    """
    Relevance alone may NOT authorize deletion. Deletion requires
    reconstructibility closure; otherwise downgrade to compression.
    """
    if relevance >= threshold:
        return PruneDecision(seg.seg_id, "retain", "above relevance threshold")

    if seg.reconstructibility is Reconstructibility.DETERMINISTIC:
        return PruneDecision(seg.seg_id, "delete", "reconstructible via idempotent tool")

    if seg.reconstructibility is Reconstructibility.HANDLED:
        return PruneDecision(seg.seg_id, "delete", "body dropped, handle retained")

    # ORPHAN_RISK: relevance is low but the fact is load-bearing.
    if seg.out_degree > 0 or seg.future_read_set:
        return PruneDecision(
            seg.seg_id, "compress",
            f"orphan-risk with out_degree={seg.out_degree}; "
            f"future_read_set={sorted(seg.future_read_set)}",
        )

    # No current or anticipated reader, but still not reconstructible:
    # we cannot prove safety, so we must not delete silently.
    raise PruneSafetyError(
        f"segment {seg.seg_id!r} is orphan-risk with no known reader; "
        f"deletion cannot be proven safe — retain or compress explicitly"
    )


def commit_prune(seg: Segment, decision: PruneDecision) -> None:
    if decision.action == "delete" and seg.reconstructibility is Reconstructibility.ORPHAN_RISK:
        raise PruneSafetyError(
            f"refusing to delete {seg.seg_id!r}: would orphan a live dependency"
        )
    # ... apply deletion/compression, rewrite provenance tags to stub/handle
