# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-compaction-summary-as-a-cache-not-as-ground-truth-when-the-retrieval-fallback-can-silently-return-the-lossy-summary-its.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-compaction-summary-as-a-cache-not-as-ground-truth-when-the-retrieval-fallback-can-silently-return-the-lossy-summary-its.warrant.json
# Markdown SHA-256:   01b621f2659b99aaa4a2b510a1b929e9cb8dccfa285f10cbb261b735e8d02574
# Code AST SHA-256:   24417f84eda08fddb814a2078057d7bbf7d366ec361ce6ebf074806a13edc413
# Verified Classes:   Fidelity, RecordType, LossyRecallError, RetrievedRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class Fidelity(str, Enum):
    EXACT = "exact"
    LOSSY = "lossy"


class RecordType(str, Enum):
    RAW = "raw"
    SUMMARY = "summary"


class LossyRecallError(RuntimeError):
    """Raised when a slot requiring exact specification is matched only by a lossy summary."""


@dataclass(frozen=True)
class RetrievedRecord:
    record_type: RecordType
    fidelity: Fidelity
    source_turn: int
    compaction_id: str | None
    content: str
    score: float


# Slots that demand exact literals: identifiers, numeric specs, type signatures, hashes.
EXACT_SPEC_SLOTS = frozenset({"column_type", "table_name", "api_field", "hash", "numeric_literal"})


def resolve_slot(
    slot: str,
    candidates: list[RetrievedRecord],
    raw_fetcher,
) -> RetrievedRecord:
    """Resolve a slot from retrieval candidates, refusing to launder summaries into facts."""
    if not candidates:
        raise LossyRecallError(f"no candidates for slot={slot!r}")

    ranked = sorted(candidates, key=lambda r: r.score, reverse=True)
    top = ranked[0]

    if slot in EXACT_SPEC_SLOTS:
        # Exact-spec slots must be served by a raw, exact record.
        exact_raw = [r for r in ranked
                     if r.record_type is RecordType.RAW and r.fidelity is Fidelity.EXACT]
        if exact_raw:
            return exact_raw[0]
        # Only lossy summary matched: fail closed and force a raw re-fetch.
        if top.record_type is RecordType.SUMMARY or top.fidelity is Fidelity.LOSSY:
            raw = raw_fetcher(slot)  # synchronous cold fetch from raw tier
            if raw is None or raw.fidelity is not Fidelity.EXACT:
                raise LossyRecallError(
                    f"slot={slot!r} matched only lossy summary "
                    f"(compaction_id={top.compaction_id}, score={top.score:.2f}); "
                    f"raw re-fetch failed to recover exact value"
                )
            return raw
        raise LossyRecallError(
            f"slot={slot!r} requires EXACT fidelity but best match was "
            f"{top.record_type.value}/{top.fidelity.value}"
        )

    # Non-exact slots may accept a summary, but provenance is preserved on the record.
    return top
