# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-orphaned-tool-call-spans-when-genai-semantic-conventions-split-a-single-agent-turn-across-parent-child-trace-contexts.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-orphaned-tool-call-spans-when-genai-semantic-conventions-split-a-single-agent-turn-across-parent-child-trace-contexts.warrant.json
# Markdown SHA-256:   f2b37a73fbcc1efe3117c412461fb0e041f6b5e3577b62d0ee59f24fcf04648a
# Code AST SHA-256:   a50d050b5bc2421014927f7cabcf5e692d069ca0c8493a183be12c6f34b14242
# Verified Classes:   OrphanedToolSpanError, SpanContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class OrphanedToolSpanError(RuntimeError):
    """Raised when a GenAI tool-call span would be emitted without a resolvable parent context."""
    pass


@dataclass
class SpanContext:
    trace_id: Optional[str]
    span_id: Optional[str]
    ended: bool = False

    @property
    def is_valid(self) -> bool:
        return bool(self.trace_id) and bool(self.span_id) and not self.ended


def emit_tool_span(
    parent: SpanContext,
    turn_id: Optional[str],
    tool_name: str,
    input_tokens: int,
    output_tokens: int,
) -> dict:
    """
    Emit a gen_ai.operation.name='execute_tool' span only if the parent context
    is valid and open, or if a turn_id is present for downstream reconciliation.
    """
    if not parent.is_valid and not turn_id:
        # Fresh worker / stale parent / no business key: refuse to emit a
        # silently-unattributable span that would corrupt cost aggregation.
        raise OrphanedToolSpanError(
            f"cannot emit execute_tool span for tool={tool_name!r}: "
            f"parent context invalid (trace_id={parent.trace_id!r}, "
            f"span_id={parent.span_id!r}, ended={parent.ended}) and no turn_id "
            f"for reconciliation; token cost ({input_tokens}+{output_tokens}) "
            f"would be lost from per-turn attribution"
        )

    span = {
        "gen_ai.operation.name": "execute_tool",
        "gen_ai.tool.name": tool_name,
        "gen_ai.usage.input_tokens": input_tokens,
        "gen_ai.usage.output_tokens": output_tokens,
    }
    if parent.is_valid:
        span["trace_id"] = parent.trace_id
        span["parent_span_id"] = parent.span_id
        span["attribution.status"] = "linked"
    else:
        # Parent gone but turn_id present: emit as linked-by-business-key,
        # flagged so the collector quarantines rather than sums on trace_id.
        span["attribution.status"] = "orphaned"
        span["gen_ai.agent.turn_id"] = turn_id
    return span


def close_parent(parent: SpanContext, open_children: int) -> None:
    if open_children > 0:
        raise OrphanedToolSpanError(
            f"refusing to end parent span {parent.span_id!r}: "
            f"{open_children} child tool spans still open; closing now would "
            f"orphan their gen_ai.usage.* attributes"
        )
    parent.ended = True
