# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-an-agent-span-misattribute-child-tool-call-tokens-under-opentelemetry-genai-semantic-conventions-when-the-parent-span-closes-b.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-an-agent-span-misattribute-child-tool-call-tokens-under-opentelemetry-genai-semantic-conventions-when-the-parent-span-closes-b.warrant.json
# Markdown SHA-256:   5df5c61ebc9efdee6fe644eff21b9d1926c10f234f900db62947f9340db2cf81
# Code AST SHA-256:   c7e1ddd9f9fb7abbbf0e3b1a40798087f68cbeb9a9190f9d7dbff3aae9213b86
# Verified Classes:   UsageEmissionAfterEndError, ToolUsageBuffer
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from opentelemetry import trace
from opentelemetry.trace import Span, Status, StatusCode


class UsageEmissionAfterEndError(RuntimeError):
    """Raised when gen_ai.usage.* attributes are written to a non-recording span."""


class ToolUsageBuffer:
    """Buffers GenAI usage for a tool span and flushes before end().

    Enforces the invariant: usage attributes are set while the span is
    RECORDING, addressed by a captured handle, never by ambient context.
    """

    def __init__(self, span: Span):
        self._span = span
        self._pending: dict[str, int] = {}
        self._flushed = False

    def record_input(self, tokens: int) -> None:
        if self._flushed:
            raise UsageEmissionAfterEndError(
                "input tokens recorded after flush; span already ended"
            )
        self._pending["gen_ai.usage.input_tokens"] = (
            self._pending.get("gen_ai.usage.input_tokens", 0) + tokens
        )

    def record_output(self, tokens: int) -> None:
        if self._flushed:
            raise UsageEmissionAfterEndError(
                "output tokens recorded after flush; span already ended"
            )
        self._pending["gen_ai.usage.output_tokens"] = (
            self._pending.get("gen_ai.usage.output_tokens", 0) + tokens
        )

    def flush_and_end(self) -> None:
        if self._flushed:
            return
        if not self._span.is_recording():
            # The span was ended elsewhere; writing now would silently drop
            # or land on the ambient current span. Refuse.
            raise UsageEmissionAfterEndError(
                f"cannot flush usage to span {self._span.get_span_context().span_id:#x}: "
                "span is not recording (ended before usage emission)"
            )
        for key, value in self._pending.items():
            self._span.set_attribute(key, value)
        self._span.set_status(Status(StatusCode.OK))
        self._flushed = True
        self._span.end()


def execute_tool(tracer: trace.Tracer, name: str, fn, *args):
    """Run a tool with usage buffered and flushed before span end."""
    with tracer.start_as_current_span(f"execute_tool {name}") as span:
        span.set_attribute("gen_ai.operation.name", "execute_tool")
        span.set_attribute("gen_ai.tool.name", name)
        buffer = ToolUsageBuffer(span)
        try:
            result, input_tokens, output_tokens = fn(*args)
            buffer.record_input(input_tokens)
            buffer.record_output(output_tokens)
        except Exception as exc:
            span.record_exception(exc)
            span.set_status(Status(StatusCode.ERROR, str(exc)))
            raise
        finally:
            # Flush inside the `with` block, while span is still RECORDING.
            buffer.flush_and_end()
        return result
