# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-anchor-a-hallucination-score-when-otel-span-linkage-is-only-causally-complete-not-referentially-complete.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-anchor-a-hallucination-score-when-otel-span-linkage-is-only-causally-complete-not-referentially-complete.warrant.json
# Markdown SHA-256:   4a7f317673329c8385f2909e6d4bdcadd89da00a5e8a80a3cded156419702cca
# Code AST SHA-256:   0cbe697333ca41791e94b8a21c60ae124a181bbceb326d5a663b7b0a9d3a7c34
# Verified Classes:   EvidenceIncompleteError, Span, Trace
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class EvidenceIncompleteError(RuntimeError):
    """Raised when a generation span's declared evidence set cannot be fully
    resolved within its trace. This is a telemetry-plumbing failure, NOT a
    model-quality signal, and must never be reported as a hallucination label."""


@dataclass
class Span:
    span_id: str
    trace_id: str
    name: str
    attrs: dict = field(default_factory=dict)


@dataclass
class Trace:
    trace_id: str
    spans: dict[str, Span]  # span_id -> Span

    def find_by_name(self, name: str) -> list[Span]:
        return [s for s in self.spans.values() if s.name == name]


def score_hallucination(trace: Trace, generation_span_id: str) -> dict:
    gen = trace.spans.get(generation_span_id)
    if gen is None:
        raise EvidenceIncompleteError(
            f"generation span {generation_span_id} not in trace {trace.trace_id}"
        )

    declared = gen.attrs.get("gen.evidence_span_ids")
    if not declared:
        # Fail closed: do not guess an evidence set from whatever spans exist.
        return {
            "label": "UNSCORABLE",
            "reason": "evidence_undeclared",
            "trace_id": trace.trace_id,
        }

    missing = [sid for sid in declared if sid not in trace.spans]
    if missing:
        # A declared evidence span is absent from the trace: the trace is
        # causally complete but referentially incomplete.
        raise EvidenceIncompleteError(
            f"trace {trace.trace_id} gen {generation_span_id} declares evidence "
            f"{declared} but spans {missing} are missing; refusing to score"
        )

    evidence_texts = []
    for sid in declared:
        ev = trace.spans[sid]
        text = ev.attrs.get("retrieval.context_text", "")
        if not text:
            raise EvidenceIncompleteError(
                f"evidence span {sid} has empty payload; truncated or mis-instrumented"
            )
        evidence_texts.append(text)

    premise = "\n".join(evidence_texts)
    completion = gen.attrs.get("llm.completion", "")
    grounded = _entails(premise, completion)
    return {
        "label": "grounded" if grounded else "hallucinated",
        "evidence_complete": True,
        "trace_id": trace.trace_id,
    }


def _entails(premise: str, completion: str) -> bool:
    # Placeholder for the entailment model; empty premise is impossible here
    # because score_hallucination raises before reaching this point.
    return bool(premise) and completion.strip()[:32] in premise


def run_scorer(traces: list[Trace], gen_span_ids: list[str]) -> dict:
    scorable = 0
    hallucinated = 0
    unscorable = 0
    for trace, gid in zip(traces, gen_span_ids):
        try:
            result = score_hallucination(trace, gid)
        except EvidenceIncompleteError:
            unscorable += 1
            continue
        if result["label"] == "UNSCORABLE":
            unscorable += 1
            continue
        scorable += 1
        if result["label"] == "hallucinated":
            hallucinated += 1

    rate = (hallucinated / scorable) if scorable else None
    return {
        "scorable": scorable,
        "unscorable": unscorable,
        "hallucination_rate_over_scorable": rate,
    }
