# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-tool-call-spans-when-a-streamed-tool-invocation-is-truncated-mid-argument-and-the-token-accountin.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-tool-call-spans-when-a-streamed-tool-invocation-is-truncated-mid-argument-and-the-token-accountin.warrant.json
# Markdown SHA-256:   b926bcfaa1786635308d6c25dc2d8641736c582d941c496f61ba2ba49a6c7aeb
# Code AST SHA-256:   13e2a56239911ab7e47d4e9fd40fb96f9559a1fbbe9008b607699c7bd2f0fb67
# Verified Classes:   TruncatedToolCallError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import json
from typing import Any


class TruncatedToolCallError(RuntimeError):
    """Raised when a streamed tool call terminates without a complete, schema-valid argument payload."""


def classify_tool_span(
    argument_buffer: str,
    finish_reason: str | None,
    last_usage: dict[str, Any] | None,
    schema_validator,
) -> dict[str, Any]:
    """Decide whether a streamed tool-call span is complete or abandoned.

    Returns a dict describing how the span must be closed. Raises
    TruncatedToolCallError if the caller attempts to close an abandoned span as OK.
    """
    if finish_reason != "tool_calls":
        raise TruncatedToolCallError(
            f"stream terminated with finish_reason={finish_reason!r}; "
            f"argument buffer length={len(argument_buffer)} is an abandoned prefix"
        )

    try:
        parsed = json.loads(argument_buffer)
    except json.JSONDecodeError as exc:
        raise TruncatedToolCallError(
            f"argument buffer does not parse: {exc.msg} at pos {exc.pos}; "
            f"buffer={argument_buffer[:80]!r}"
        ) from exc

    if not schema_validator(parsed):
        raise TruncatedToolCallError(
            "argument buffer parses but violates tool schema"
        )

    if not last_usage or "completion_tokens" not in last_usage:
        raise TruncatedToolCallError(
            "no final usage chunk; cannot attribute tokens to this span"
        )

    return {
        "status": "OK",
        "arguments": argument_buffer,
        "truncated": False,
        "usage": last_usage,
        "count_toward_parent": True,
    }


def close_abandoned_span(argument_buffer: str, finish_reason: str | None) -> dict[str, Any]:
    """Emit an ERROR span for an abandoned call; contributes no usage to parent."""
    return {
        "status": "ERROR",
        "arguments": argument_buffer,
        "truncated": True,
        "finish_reason": finish_reason,
        "usage": None,
        "count_toward_parent": False,
    }
