# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-opentelemetry-genai-span-attributes-against-tool-call-events-before-emitting-a-terminal-agent-span.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-opentelemetry-genai-span-attributes-against-tool-call-events-before-emitting-a-terminal-agent-span.warrant.json
# Markdown SHA-256:   cb07a16599ecdee7c06e342444ef74ccf4ebadf3c5bd4eaea637dc92a6d46b06
# Code AST SHA-256:   bd4468259d8bed0f02d7b505832cd688f3fe7492f4e8dc40e4fdefb13bacbd20
# Verified Classes:   GenAISpanReconciliationError, ToolCallEvent, ModelCallUsage, AgentRunTelemetry
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class GenAISpanReconciliationError(RuntimeError):
    """Raised when a terminal agent span's attributes contradict its tool-call events."""
    pass


@dataclass
class ToolCallEvent:
    call_id: str
    tool_name: str
    attempt: int = 1
    retry: bool = False


@dataclass
class ModelCallUsage:
    call_id: str
    input_tokens: int
    output_tokens: int
    result_consumed: bool  # False if this call was retried/discarded


@dataclass
class AgentRunTelemetry:
    model_calls: list[ModelCallUsage] = field(default_factory=list)
    tool_events: list[ToolCallEvent] = field(default_factory=list)
    # What the span will actually be closed with:
    span_input_tokens: Optional[int] = None
    span_output_tokens: Optional[int] = None
    span_operation: str = "chat"


def reconcile_terminal_span(run: AgentRunTelemetry, token_tolerance: int = 0) -> None:
    """
    Assert the GenAI terminal-span invariant before close.
    Raises if the span's attributes cannot be certified against the event stream.
    """
    # 1. Token attribution completeness: span usage must equal sum over ALL model calls,
    #    including retried ones (which still spent tokens).
    expected_in = sum(c.input_tokens for c in run.model_calls)
    expected_out = sum(c.output_tokens for c in run.model_calls)

    if run.span_input_tokens is None or run.span_output_tokens is None:
        raise GenAISpanReconciliationError(
            "terminal span missing gen_ai.usage.* attributes; cannot certify"
        )

    if abs(run.span_input_tokens - expected_in) > token_tolerance:
        raise GenAISpanReconciliationError(
            f"input token divergence: span={run.span_input_tokens} "
            f"expected_sum={expected_in} (likely counter reset or last-call-only)"
        )
    if abs(run.span_output_tokens - expected_out) > token_tolerance:
        raise GenAISpanReconciliationError(
            f"output token divergence: span={run.span_output_tokens} "
            f"expected_sum={expected_out} (likely counter reset or last-call-only)"
        )

    # 2. Event/attribute cardinality: every tool event must have a stable call_id,
    #    and internal retries must be marked retry=True so loop-detectors can exclude them.
    seen_ids: set[str] = set()
    for ev in run.tool_events:
        if not ev.call_id:
            raise GenAISpanReconciliationError(
                f"tool event for {ev.tool_name!r} lacks stable call_id; "
                "retries cannot be deduplicated"
            )
        if ev.attempt > 1 and not ev.retry:
            raise GenAISpanReconciliationError(
                f"tool call {ev.call_id} attempt={ev.attempt} not marked retry=True; "
                "would be miscounted as a reasoning step"
            )
        seen_ids.add(ev.call_id)

    # 3. Every consumed model result must correspond to a tool invocation that reached it,
    #    and every token-spending discarded call must be represented.
    consumed_calls = [c for c in run.model_calls if c.result_consumed]
    discarded_calls = [c for c in run.model_calls if not c.result_consumed]
    if discarded_calls and not any(ev.retry for ev in run.tool_events):
        raise GenAISpanReconciliationError(
            f"{len(discarded_calls)} model call(s) discarded without retry-marked tool events; "
            "token spend has no traceable cause"
        )

    # 4. Operation-name stability: terminal op must be a known terminal value.
    if run.span_operation not in {"chat", "invoke_agent", "execute_tool"}:
        raise GenAISpanReconciliationError(
            f"unrecognized terminal gen_ai.operation.name={run.span_operation!r}"
        )


def close_agent_span(run: AgentRunTelemetry) -> str:
    """Close the span as terminal only if reconciliation passes; else mark provisional."""
    try:
        reconcile_terminal_span(run)
        return "terminal"
    except GenAISpanReconciliationError as exc:
        # Do NOT silently pick a canonical value. Mark provisional and emit divergence event.
        run.span_operation = run.span_operation  # unchanged
        # In a real emitter: span.set_attribute("gen_ai.agent.incomplete", True)
        # span.add_event("gen_ai.reconciliation.divergence", {"reason": str(exc)})
        return "provisional"
