# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-the-exact-token-it-was-compacted-to-preserve-the-summarization-floor-collision-in-hierarchical-compaction-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-the-exact-token-it-was-compacted-to-preserve-the-summarization-floor-collision-in-hierarchical-compaction-handoff.warrant.json
# Markdown SHA-256:   e2fb4cd19bbb0dc473a9b6e7c558ccaeccb45cca42fca714332cf0256417cb2f
# Code AST SHA-256:   ea4b5c10300267f4b211235c0c3c334ee3e197d36d83fdc807692c9f4622ac53
# Verified Classes:   CoverageFidelityMismatch, Span, Handoff
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CoverageFidelityMismatch(RuntimeError):
    """Raised when a handoff marks a span covered but cannot attest its literals."""
    pass


@dataclass
class Span:
    span_id: str
    raw_text: str
    literals: list[str] = field(default_factory=list)  # exact tokens requiring reproduction


@dataclass
class Handoff:
    coverage: dict[str, bool]                 # span_id -> covered
    literal_index: dict[str, tuple[str, int, int]]  # literal -> (span_id, start, end)
    consumer_requires_reproduction: bool


def build_handoff(
    spans: list[Span],
    summarized_span_ids: set[str],
    consumer_requires_reproduction: bool,
) -> Handoff:
    coverage = {s.span_id: True for s in spans}
    literal_index: dict[str, tuple[str, int, int]] = {}

    # Populate literal index from RAW spans, never from summarizer prose.
    for s in spans:
        if s.span_id not in summarized_span_ids:
            continue
        for lit in s.literals:
            start = s.raw_text.find(lit)
            if start < 0:
                raise CoverageFidelityMismatch(
                    f"literal {lit!r} declared for span {s.span_id} not found in raw text"
                )
            literal_index[lit] = (s.span_id, start, start + len(lit))

    # Invariant: a covered span that the consumer must reproduce
    # requires literal attestation for every declared literal.
    if consumer_requires_reproduction:
        for s in spans:
            if not coverage.get(s.span_id, False):
                continue
            for lit in s.literals:
                if lit not in literal_index:
                    raise CoverageFidelityMismatch(
                        f"span {s.span_id} marked covered but literal {lit!r} "
                        f"is unattested; coverage != fidelity at summarization floor"
                    )

    return Handoff(
        coverage=coverage,
        literal_index=literal_index,
        consumer_requires_reproduction=consumer_requires_reproduction,
    )


def resolve_literal(handoff: Handoff, literal: str, raw_store: dict[str, str]) -> str:
    """Recall path: must re-fetch raw span when attestation is present."""
    entry: Optional[tuple[str, int, int]] = handoff.literal_index.get(literal)
    if entry is None:
        if handoff.consumer_requires_reproduction:
            raise CoverageFidelityMismatch(
                f"literal {literal!r} not attested and consumer requires reproduction"
            )
        raise CoverageFidelityMismatch(
            f"literal {literal!r} unresolved; refusing to hallucinate from summary"
        )
    span_id, start, end = entry
    raw = raw_store.get(span_id)
    if raw is None:
        raise CoverageFidelityMismatch(
            f"attested span {span_id} missing from raw store; lossy handoff cannot recover"
        )
    return raw[start:end]
