# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-safety-verdict-detach-from-its-otel-trace-when-the-trace-exporter-samples-the-span-that-carried-the-taint.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-safety-verdict-detach-from-its-otel-trace-when-the-trace-exporter-samples-the-span-that-carried-the-taint.warrant.json
# Markdown SHA-256:   ab08abf81cfb12744f4d511b92fc1576fcadaac62908adf2b3663a3e5277a230
# Code AST SHA-256:   69071277c6f8adb7458e9087153aa3af4a7bce25a61c252bd932b5b13f4124aa
# Verified Classes:   TaintJoinError, SpanRef, Verdict, TaintGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class TaintJoinError(RuntimeError):
    """Raised when a safety verdict cannot be joined to a taint-graph node."""


@dataclass(frozen=True)
class SpanRef:
    trace_id: str
    span_id: str


@dataclass
class Verdict:
    verdict_id: str
    severity: str
    # Primary anchor: physical span identity captured at emission time.
    evidence_span: Optional[SpanRef]
    # Secondary anchor: content hash, scoped by trace.
    evidence_hash: Optional[str]
    # The anchor that must NOT be used alone.
    logical_step: int


@dataclass
class TaintGraph:
    nodes: dict[SpanRef, str] = field(default_factory=dict)
    unresolved: list[SpanRef] = field(default_factory=list)

    def resolve(self, ref: SpanRef) -> Optional[str]:
        return self.nodes.get(ref)


def join_verdict_to_graph(verdict: Verdict, graph: TaintGraph) -> str:
    """
    Join a verdict to the taint graph using the identity anchor first,
    content hash second, and refuse to fall back to logical_step alone.

    Returns the taint category of the resolved node, or raises TaintJoinError
    if the verdict cannot be attributed to a physical span.
    """
    if verdict.severity not in {"HIGH", "CRITICAL"}:
        return "SKIP"

    if verdict.evidence_span is not None:
        category = graph.resolve(verdict.evidence_span)
        if category is not None:
            return category
        # Span existed in-process but is unresolved in the graph:
        # this is a sampler drop or strict-builder discard, not a benign result.
        if verdict.evidence_span in graph.unresolved:
            raise TaintJoinError(
                f"verdict {verdict.verdict_id} anchors on span "
                f"{verdict.evidence_span.trace_id}/{verdict.evidence_span.span_id} "
                f"which is present but unresolved (sentinel node); "
                f"treat as coverage gap, not as clean"
            )

    if verdict.evidence_hash is not None and verdict.evidence_span is not None:
        for ref, category in graph.nodes.items():
            if ref.trace_id == verdict.evidence_span.trace_id:
                if graph.nodes.get(ref) == verdict.evidence_hash:
                    return category

    raise TaintJoinError(
        f"verdict {verdict.verdict_id} (severity={verdict.severity}, "
        f"step={verdict.logical_step}) has no resolvable physical span anchor; "
        f"refusing to key on logical_step alone — this is the detach condition"
    )


def coverage_report(verdicts: list[Verdict], graph: TaintGraph) -> dict[str, int]:
    report = {"resolved": 0, "coverage_gap": 0, "detached": 0}
    for v in verdicts:
        try:
            result = join_verdict_to_graph(v, graph)
            if result == "SKIP":
                continue
            report["resolved"] += 1
        except TaintJoinError as exc:
            if "unresolved (sentinel node)" in str(exc):
                report["coverage_gap"] += 1
            else:
                report["detached"] += 1
    return report
