# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-quarantine-provenance-degraded-memories-before-retrieval-poisons-a-long-horizon-plan.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-quarantine-provenance-degraded-memories-before-retrieval-poisons-a-long-horizon-plan.warrant.json
# Markdown SHA-256:   8a2627282dd3850ee05409e4747785ea75c5ebf326d7726bcc79130dbacffaed
# Code AST SHA-256:   436894b55583242e570f6aa1176659c16b5fe7e1090cf2f195d3a52c58fa6d63
# Verified Classes:   WarrantState, ProvenanceGateError, Provenance, Memory, Action, RetrievalResult
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class WarrantState(str, Enum):
    VALID = "valid"
    DEGRADED = "degraded"          # origin call was partial / timed out / sampled
    REPLAY_DIVERGENT = "replay_divergent"  # same call_id, different content_hash


class ProvenanceGateError(RuntimeError):
    """Raised when a memory is asked to ground an action it cannot legally ground."""


@dataclass(frozen=True)
class Provenance:
    origin_tool: str
    origin_call_id: str
    content_hash: str
    warrant_state: WarrantState
    corroboration_count: int = 0


@dataclass(frozen=True)
class Memory:
    text: str
    similarity: float
    provenance: Provenance


@dataclass(frozen=True)
class Action:
    name: str
    irreversible: bool


@dataclass
class RetrievalResult:
    eligible: list[Memory] = field(default_factory=list)
    quarantined: list[Memory] = field(default_factory=list)
    underflow: bool = False


def gate_candidates(
    candidates: Iterable[Memory],
    action: Action,
    min_viable: int = 1,
) -> RetrievalResult:
    """
    Pre-retrieval provenance gate. Must run BEFORE top-k similarity selection so
    that ineligible memories never consume retrieval slots.
    """
    result = RetrievalResult()
    for mem in candidates:
        p = mem.provenance
        if p.warrant_state is WarrantState.VALID:
            result.eligible.append(mem)
            continue
        # Non-VALID warrant may ground reversible actions only.
        if not action.irreversible:
            result.eligible.append(mem)
            continue
        # Irreversible action requires corroboration from an independent origin.
        if p.corroboration_count >= 2:
            result.eligible.append(mem)
            continue
        result.quarantined.append(mem)

    if len(result.eligible) < min_viable:
        result.underflow = True
    return result


def select_top_k(
    result: RetrievalResult,
    k: int,
    action: Action,
) -> list[Memory]:
    if result.underflow:
        # Do NOT backfill with quarantined memories. Force re-observation.
        raise ProvenanceGateError(
            f"retrieval underflow for irreversible action {action.name!r}: "
            f"{len(result.eligible)} eligible < min_viable; re-observe instead of backfilling"
        )
    return sorted(result.eligible, key=lambda m: m.similarity, reverse=True)[:k]


def dedup_replay_divergence(memories: Iterable[Memory]) -> list[Memory]:
    """
    Same origin_call_id with different content_hash must be flagged
    REPLAY_DIVERGENT and demoted, never co-retrieved as independent evidence.
    """
    by_call: dict[str, list[Memory]] = {}
    for m in memories:
        by_call.setdefault(m.provenance.origin_call_id, []).append(m)

    out: list[Memory] = []
    for call_id, group in by_call.items():
        hashes = {m.provenance.content_hash for m in group}
        if len(hashes) > 1:
            for m in group:
                demoted = Provenance(
                    origin_tool=m.provenance.origin_tool,
                    origin_call_id=m.provenance.origin_call_id,
                    content_hash=m.provenance.content_hash,
                    warrant_state=WarrantState.REPLAY_DIVERGENT,
                    corroboration_count=m.provenance.corroboration_count,
                )
                out.append(Memory(m.text, m.similarity, demoted))
        else:
            out.extend(group)
    return out
