# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-a-trace-linked-eval-score-when-token-level-cost-attribution-has-been-reconstructed-rather-than-obser.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-a-trace-linked-eval-score-when-token-level-cost-attribution-has-been-reconstructed-rather-than-obser.warrant.json
# Markdown SHA-256:   671097e6eeb4021a4a60b1f21952be0ebe4e9c9958ccc41496af9f8f72340084
# Code AST SHA-256:   ead892bdcfa10825c5972335dff6642c675a804d092403b28a3ac3cbeeb8261e
# Verified Classes:   ProvenanceError, Provenance, ReconstructMethod, Span, ScoredTrace
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class ProvenanceError(RuntimeError):
    """Raised when an eval score is requested over inadmissible token provenance."""
    pass


class Provenance(Enum):
    OBSERVED = "observed"
    RECONSTRUCTED = "reconstructed"


class ReconstructMethod(Enum):
    NONE = "none"
    RETOKENIZE_PRETTY_JSON = "retokenize_pretty_json"   # over-counts vs wire
    RETOKENIZE_TRUNCATED = "retokenize_truncated"       # under-counts at max_tokens
    SUM_OF_RETRIES = "sum_of_retries"                   # over-counts billed tokens
    CHAR_ESTIMATE = "char_estimate"


# Methods whose error direction is known to correlate with the outcome label.
OUTCOME_CORRELATED = {
    ReconstructMethod.RETOKENIZE_TRUNCATED,
    ReconstructMethod.SUM_OF_RETRIES,
    ReconstructMethod.RETOKENIZE_PRETTY_JSON,
}


@dataclass
class Span:
    span_id: str
    tokens: int
    provenance: Provenance
    method: ReconstructMethod = ReconstructMethod.NONE
    children: list["Span"] = field(default_factory=list)


@dataclass
class ScoredTrace:
    trace_id: str
    root: Span
    correct: bool


def _walk(span: Span):
    yield span
    for c in span.children:
        yield from _walk(c)


def emit_gating_score(trace: ScoredTrace) -> dict:
    spans = list(_walk(trace.root))
    total_tokens = sum(s.tokens for s in spans)
    reconstructed = [s for s in spans if s.provenance is Provenance.RECONSTRUCTED]

    if not reconstructed:
        return {
            "trace_id": trace.trace_id,
            "score": (1.0 if trace.correct else 0.0) / max(total_tokens, 1),
            "confidence": "exact",
            "reconstructed_fraction": 0.0,
        }

    # Any reconstructed node whose method is outcome-correlated makes the
    # trace inadmissible for gating — regardless of how small the fraction.
    poisoned = [s for s in reconstructed if s.method in OUTCOME_CORRELATED]
    if poisoned:
        methods = sorted({s.method.value for s in poisoned})
        raise ProvenanceError(
            f"trace {trace.trace_id}: {len(poisoned)} span(s) reconstructed via "
            f"outcome-correlated methods {methods}; refusing to emit gating-eligible "
            f"score. Route to review queue or re-run with usage capture enabled."
        )

    frac = sum(s.tokens for s in reconstructed) / max(total_tokens, 1)
    return {
        "trace_id": trace.trace_id,
        "score": (1.0 if trace.correct else 0.0) / max(total_tokens, 1),
        "confidence": "degraded",
        "reconstructed_fraction": frac,
    }


def gate(week: list[ScoredTrace], tolerance: float = 0.02) -> dict:
    admitted, refused = [], []
    for t in week:
        try:
            admitted.append(emit_gating_score(t))
        except ProvenanceError:
            refused.append(t.trace_id)
    if refused:
        # Refusal is not a crash — it is the invariant firing.
        return {"admitted": len(admitted), "refused": refused,
                "note": "refused traces excluded from gating cohort"}
    return {"admitted": len(admitted), "refused": []}
