# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-otel-genai-span-nesting-when-a-tool-call-span-outlives-its-parent-agent-turn.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-otel-genai-span-nesting-when-a-tool-call-span-outlives-its-parent-agent-turn.warrant.json
# Markdown SHA-256:   f1bb3cd832ff27da5403259b8df73090bd0a01462d553e68fcc0a61aa9876848
# Code AST SHA-256:   b0d630a17d31f24dd095a581d4150b7dc9b143ecb3f1953bfa22fd3a20289e3e
# Verified Classes:   SpanParentingViolation, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class SpanParentingViolation(RuntimeError):
    """Raised when a GenAI tool span cannot legally remain a child of an agent turn span."""


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    start_ns: int
    end_ns: Optional[int]  # None => still open
    kind: str  # "gen_ai.invoke_agent" | "gen_ai.chat" | "gen_ai.tool"
    attributes: dict


def close_agent_turn(agent: Span, open_children: list[Span]) -> list[Span]:
    """Close an agent turn span, detaching any tool child that is still open.

    Invariant enforced: for every span S with parent_span_id == agent.span_id,
    S.end_ns must be set and <= agent.end_ns at the moment agent closes.
    Any open tool child violates this and must be re-rooted with a Span Link.
    """
    if agent.kind != "gen_ai.invoke_agent":
        raise SpanParentingViolation(
            f"close_agent_turn called on non-agent span kind={agent.kind!r}"
        )
    if agent.end_ns is not None:
        raise SpanParentingViolation(
            f"agent span {agent.span_id} already closed at {agent.end_ns}"
        )

    detached: list[Span] = []
    for child in open_children:
        if child.parent_span_id != agent.span_id:
            # Not our child; leave it to its own owner.
            continue
        if child.kind != "gen_ai.tool":
            raise SpanParentingViolation(
                f"open non-tool child {child.span_id} kind={child.kind!r} "
                f"under agent {agent.span_id}; cannot detach non-tool spans"
            )
        if child.end_ns is None:
            # Open child at parent close: re-root and record a link.
            child.parent_span_id = None
            child.attributes["gen_ai.link.parent_span_id"] = agent.span_id
            child.attributes["gen_ai.link.reason"] = "tool_outlived_turn"
            detached.append(child)
        elif child.end_ns > (agent.end_ns or 0):
            # Defensive: closed child that still violates containment.
            raise SpanParentingViolation(
                f"tool span {child.span_id} end_ns={child.end_ns} exceeds "
                f"agent {agent.span_id} end_ns={agent.end_ns}"
            )

    # Token-accounting guardrail: usage attributes belong on gen_ai.chat only.
    for child in open_children:
        if child.kind == "gen_ai.tool" and (
            "gen_ai.usage.input_tokens" in child.attributes
            or "gen_ai.usage.output_tokens" in child.attributes
        ):
            raise SpanParentingViolation(
                f"gen_ai.tool span {child.span_id} carries gen_ai.usage.* "
                f"attributes; token attribution must live on the gen_ai.chat span"
            )

    agent.end_ns = max(
        [agent.start_ns] + [c.end_ns for c in open_children if c.end_ns is not None]
    )
    return detached
