# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-genai-token-accounting-silently-double-count-when-a-tool-call-span-is-retried-under-opentelemetry-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-genai-token-accounting-silently-double-count-when-a-tool-call-span-is-retried-under-opentelemetry-semantic-conventions.warrant.json
# Markdown SHA-256:   4fc36908849bbae50868659cdd0e42443b9864b942553ba785f9bef0e1e760b6
# Code AST SHA-256:   f7247f1247aa04966736be01818e709979993e4b468d3e328fffef7bd9edfb80
# Verified Classes:   AmbiguousUsageSpanError, GenAISpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import uuid
from dataclasses import dataclass, field


class AmbiguousUsageSpanError(RuntimeError):
    """Raised when a GenAI span cannot be unambiguously attributed for token accounting."""


@dataclass
class GenAISpan:
    span_id: str
    gen_ai_operation: str          # "chat" | "execute_tool"
    gen_ai_tool_call_id: str | None
    gen_ai_usage_input_tokens: int
    gen_ai_request_retry: bool = False
    gen_ai_usage_cumulative: bool = False
    attributes: dict = field(default_factory=dict)


def emit_chat_span(
    *,
    operation: str,
    input_tokens: int,
    tool_call_id: str | None,
    is_retry: bool,
    includes_prior_context: bool,
) -> GenAISpan:
    # Invariant 1: tool call IDs must be per-invocation, never derived from tool name.
    if tool_call_id is not None and not _looks_like_uuid(tool_call_id):
        raise AmbiguousUsageSpanError(
            f"gen_ai.tool.call.id={tool_call_id!r} is not a per-invocation UUID; "
            "de-duplication across retries will collapse distinct invocations."
        )

    # Invariant 2: a retry that re-sends prior context MUST be marked cumulative,
    # otherwise summing usage across the trace double-counts the replayed prompt.
    if includes_prior_context and not is_retry:
        raise AmbiguousUsageSpanError(
            "Span reports cumulative input tokens but is not marked as a retry; "
            "billing-regime and task-regime sums will diverge silently."
        )

    # Invariant 3: every retry span must be explicitly flagged so consumers can
    # choose to exclude it from task attribution.
    if is_retry and not includes_prior_context:
        raise AmbiguousUsageSpanError(
            "Retry span reports non-cumulative usage; provider will bill the full "
            "prompt, so the reported figure understates cost."
        )

    return GenAISpan(
        span_id=str(uuid.uuid4()),
        gen_ai_operation=operation,
        gen_ai_tool_call_id=tool_call_id,
        gen_ai_usage_input_tokens=input_tokens,
        gen_ai_request_retry=is_retry,
        gen_ai_usage_cumulative=includes_prior_context,
    )


def _looks_like_uuid(value: str) -> bool:
    try:
        uuid.UUID(value)
        return True
    except ValueError:
        return False
