# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-the-orphaned-tool-call-span-in-opentelemetry-genai-agent-hierarchies.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-the-orphaned-tool-call-span-in-opentelemetry-genai-agent-hierarchies.warrant.json
# Markdown SHA-256:   4701efdb0697227317e266b1c477168b2dfa84e0e0fb08a2a6dde09d8cf276d7
# Code AST SHA-256:   e2e5b0802b8f8c96dfed4befba4e9196dddcce54fa9a0e86af8a09522735b731
# Verified Classes:   MisparentedToolSpanError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class MisparentedToolSpanError(RuntimeError):
    """Raised when a tool span with token-bearing descendants is parented
    under the agent span instead of the issuing model span."""
    pass


@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    operation: str            # "agent" | "chat" | "execute_tool"
    tool_call_id: Optional[str] = None
    input_tokens: int = 0
    output_tokens: int = 0
    children: list = field(default_factory=list)


def _has_model_descendants(span: Span) -> bool:
    stack = list(span.children)
    while stack:
        s = stack.pop()
        if s.operation == "chat" and (s.input_tokens + s.output_tokens) > 0:
            return True
        stack.extend(s.children)
    return False


def assert_tool_parent_invariant(
    tool_span: Span,
    issuing_model_span_id: str,
    strict: bool = True,
) -> None:
    """
    Verify the tool span is parented under the model span that issued it.

    - If parent == issuing model span: OK.
    - If parent != issuing model span but tool has NO model descendants:
      ambiguous (fire-and-forget or harmless misparent) -> warn only.
    - If parent != issuing model span AND tool HAS model descendants:
      hard failure; tokens would be double-counted.
    """
    if tool_span.parent_id == issuing_model_span_id:
        return

    if not _has_model_descendants(tool_span):
        # Ambiguous: do not raise. Caller should log a warning and
        # route to reconciliation, not span rejection.
        return

    if strict:
        raise MisparentedToolSpanError(
            f"tool span {tool_span.span_id} (call_id={tool_span.tool_call_id}) "
            f"is parented under {tool_span.parent_id!r} but was issued by "
            f"model span {issuing_model_span_id!r}; tool has token-bearing "
            f"model descendants and would be double-counted in agent totals."
        )


def aggregate_agent_tokens(
    agent_span: Span,
    issuing_index: dict,  # tool_call_id -> issuing model span_id
    strict: bool = True,
) -> int:
    """
    Sum tokens attributable to the agent without double-counting
    reparented tool sub-trees.
    """
    total = 0
    for model_span in agent_span.children:
        if model_span.operation != "chat":
            continue
        total += model_span.input_tokens + model_span.output_tokens
        for tool_span in model_span.children:
            if tool_span.operation != "execute_tool":
                continue
            issuing = issuing_index.get(tool_span.tool_call_id)
            assert_tool_parent_invariant(tool_span, issuing, strict=strict)
            # tool descendants are already counted via model_span path;
            # do not re-add here.

    # Agent-parented tools: count only if they carry no model descendants.
    for tool_span in agent_span.children:
        if tool_span.operation != "execute_tool":
            continue
        if not _has_model_descendants(tool_span):
            total += tool_span.input_tokens + tool_span.output_tokens
        # else: excluded from both terms; reported via warning.

    return total
