# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-compact-when-the-summarizer-s-own-provenance-tokens-are-the-only-surviving-reference-to-a-still-open-obligation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-compact-when-the-summarizer-s-own-provenance-tokens-are-the-only-surviving-reference-to-a-still-open-obligation.warrant.json
# Markdown SHA-256:   a2100f4636c7aa00c036931152c873edf2a69cce6473573a0e44ed474a485ac3
# Code AST SHA-256:   fb87a70499c6feb128b87b3a92fc2eaea2d1bd3c33c46d3b67285fcc9c8c4200
# Verified Classes:   ObligationStatus, ProvenanceLossError, Obligation, CompactionPlan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ObligationStatus(Enum):
    OPEN = "open"
    CLOSED = "closed"
    AMBIGUOUS = "ambiguous"  # PARTIAL with no recorded discharge -> treat as OPEN


class ProvenanceLossError(RuntimeError):
    """Raised when a lossy compaction would destroy the only surviving
    reference to an open obligation's discharge condition."""


@dataclass
class Obligation:
    obligation_id: str
    discharge_condition: str          # e.g. "backfill orders.customer_ref before ALTER"
    provenance_tokens: list[str]      # e.g. ["chk_orders_fk", "orders.customer_ref", "before"]
    status: ObligationStatus
    source_span_tokens: int


@dataclass
class CompactionPlan:
    lossy_region_tokens: int
    verbatim_region_tokens: int
    carried_obligations: list[Obligation] = field(default_factory=list)


def plan_compaction(
    obligations: list[Obligation],
    summarizer_has_obligation_channel: bool,
    token_pressure: float,
) -> CompactionPlan:
    """Decide the safe compaction plan. Refuses lossy compaction when an open
    obligation's discharge condition would be paraphrased by the summarizer."""

    open_obligations = [
        o for o in obligations
        if o.status in (ObligationStatus.OPEN, ObligationStatus.AMBIGUOUS)
    ]

    if open_obligations and not summarizer_has_obligation_channel:
        # The summarizer sees a flat transcript; it cannot distinguish open
        # from closed. Any lossy pass risks paraphrasing a discharge condition.
        raise ProvenanceLossError(
            f"Cannot run lossy compaction: {len(open_obligations)} open "
            f"obligation(s) with no structured carry-through channel. "
            f"Offending obligations: "
            f"{[o.obligation_id for o in open_obligations]}. "
            f"Fall back to truncation-with-loss-marker or lift obligations "
            f"into a verbatim side-channel before summarizing."
        )

    if token_pressure < 0.0 or token_pressure > 1.0:
        raise ProvenanceLossError(
            f"token_pressure out of range: {token_pressure}"
        )

    # Safe path: obligations are lifted verbatim, summarizer only touches
    # closed history. Compaction ratio is reduced by the carried cost.
    carried = open_obligations
    carried_cost = sum(o.source_span_tokens for o in carried)
    lossy_budget = max(0, int(60_000 * token_pressure) - carried_cost)

    return CompactionPlan(
        lossy_region_tokens=lossy_budget,
        verbatim_region_tokens=carried_cost,
        carried_obligations=carried,
    )


def verify_post_compaction(
    plan: CompactionPlan,
    summary_text: str,
) -> None:
    """Post-condition: every carried obligation's provenance tokens must
    still be resolvable from the compacted state (summary + channel)."""
    for ob in plan.carried_obligations:
        missing = [t for t in ob.provenance_tokens if t not in summary_text]
        if missing:
            raise ProvenanceLossError(
                f"Post-compaction provenance loss on {ob.obligation_id}: "
                f"tokens {missing} no longer resolvable. The discharge "
                f"condition '{ob.discharge_condition}' is now unfalsifiable."
            )
