# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-opentelemetry-genai-spans-for-a-retried-tool-call-without-resetting-the-span-s-token-and-attempt-attributes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-opentelemetry-genai-spans-for-a-retried-tool-call-without-resetting-the-span-s-token-and-attempt-attributes.warrant.json
# Markdown SHA-256:   80f857194a6bec4478748ff9ba4e4dc1224500f2d020aa52f86542a83b9fd611
# Code AST SHA-256:   1762691e5111c2a9ae47713e2b4ac9a41ce67eb1bccc3d49cd5a4713151b6c0b
# Verified Classes:   GenAISpanInvariantError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any


class GenAISpanInvariantError(RuntimeError):
    """Raised when a GenAI span is mutated in a way that breaks the
    one-span-per-physical-invocation invariant."""


# Attributes that are attempt-specific and therefore write-once per span.
WRITE_ONCE_ATTRIBUTES = frozenset(
    {
        "gen_ai.usage.input_tokens",
        "gen_ai.usage.output_tokens",
        "gen_ai.response.id",
        "gen_ai.response.model",
        "gen_ai.tool.call.id",
        "error.type",
        "status",
    }
)


@dataclass
class GenAISpan:
    name: str
    attributes: dict[str, Any] = field(default_factory=dict)
    _finished: bool = False

    def set_attribute(self, key: str, value: Any) -> None:
        if self._finished:
            raise GenAISpanInvariantError(
                f"span {self.name!r} is finished; refusing to set {key!r}. "
                "Retries must open a new span, not mutate this one."
            )
        if key in WRITE_ONCE_ATTRIBUTES and key in self.attributes:
            raise GenAISpanInvariantError(
                f"attempt-specific attribute {key!r} already set to "
                f"{self.attributes[key]!r}; overwriting with {value!r} would "
                "collapse two physical attempts into one span."
            )
        self.attributes[key] = value

    def set_status(self, status: str, error_type: str | None = None) -> None:
        if status == "OK" and "error.type" in self.attributes:
            raise GenAISpanInvariantError(
                f"span {self.name!r} has error.type={self.attributes['error.type']!r} "
                "but is being marked OK; a successful retry belongs on a sibling span."
            )
        self.set_attribute("status", status)
        if error_type is not None:
            self.set_attribute("error.type", error_type)

    def finish(self) -> None:
        self._finished = True


def retried_tool_call(
    logical_span: GenAISpan,
    tool_name: str,
    attempts: list[dict[str, Any]],
) -> GenAISpan:
    """Execute a logical tool step across N physical attempts.

    Each attempt gets its own span. Usage is accumulated only on the
    parent logical span, never by overwriting a child's attributes.
    """
    total_in = 0
    total_out = 0
    successful_span: GenAISpan | None = None

    for index, attempt in enumerate(attempts):
        span = GenAISpan(name=f"execute_tool {tool_name} [attempt {index}]")
        span.set_attribute("gen_ai.operation.name", "execute_tool")
        span.set_attribute("gen_ai.tool.name", tool_name)
        span.set_attribute("gen_ai.attempt.index", index)

        if attempt.get("ok"):
            span.set_attribute("gen_ai.tool.call.id", attempt["call_id"])
            span.set_attribute("gen_ai.usage.input_tokens", attempt["in_tokens"])
            span.set_attribute("gen_ai.usage.output_tokens", attempt["out_tokens"])
            span.set_status("OK")
            successful_span = span
        else:
            span.set_attribute("gen_ai.tool.call.id", attempt["call_id"])
            span.set_attribute("gen_ai.usage.input_tokens", attempt["in_tokens"])
            span.set_attribute("gen_ai.usage.output_tokens", attempt["out_tokens"])
            span.set_status("ERROR", error_type=attempt.get("error", "unknown"))

        total_in += attempt["in_tokens"]
        total_out += attempt["out_tokens"]
        span.finish()

    if successful_span is None:
        raise GenAISpanInvariantError(
            f"tool {tool_name!r} exhausted all {len(attempts)} attempts without "
            "success; logical span must be closed as ERROR with accumulated usage."
        )

    # Accumulate on the parent only after children are finalized.
    logical_span.set_attribute("gen_ai.usage.input_tokens", total_in)
    logical_span.set_attribute("gen_ai.usage.output_tokens", total_out)
    logical_span.set_attribute("gen_ai.attempt.count", len(attempts))
    return successful_span
