# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-genai-agent-span-until-its-parent-tool-call-span-has-been-closed-by-the-transport-layer.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-genai-agent-span-until-its-parent-tool-call-span-has-been-closed-by-the-transport-layer.warrant.json
# Markdown SHA-256:   ce9909e4cf4f87429de1413d928fde7292473ecb3c5c938df97b07b727a9148f
# Code AST SHA-256:   d27fe20e7eb7757aa7b96c4e1da7f0d614f37b4201f42e34c1eaabde86a3da49
# Verified Classes:   SpanExportOrderError, GenAISpan, SpanTreeGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class SpanExportOrderError(RuntimeError):
    """Raised when a GenAI parent span is exported before its tool-call children close."""


@dataclass
class GenAISpan:
    span_id: str
    operation: str                      # "chat" | "invoke_agent" | "execute_tool"
    parent_span_id: Optional[str] = None
    tool_call_id: Optional[str] = None  # only on execute_tool children
    start_time: float = field(default_factory=time.monotonic)
    end_time: Optional[float] = None
    attributes: dict = field(default_factory=dict)
    open_tool_calls: set = field(default_factory=set)  # expected child call ids
    closed_tool_calls: set = field(default_factory=set)
    exported: bool = False


class SpanTreeGuard:
    """Enforces: a GenAI parent may not export until all tool-call children close."""

    def __init__(self, resolution_deadline_s: float = 30.0):
        self.deadline = resolution_deadline_s

    def register_parent(self, span: GenAISpan, tool_calls: list) -> None:
        # tool_calls: list of {"id": ..., "name": ...} from the completion
        span.open_tool_calls = {tc["id"] for tc in tool_calls}
        for tc in tool_calls:
            span.attributes.setdefault("gen_ai.tool.call.id", []).append(tc["id"])

    def register_child(self, parent: GenAISpan, child: GenAISpan) -> None:
        if child.tool_call_id is None:
            raise SpanExportOrderError(
                f"execute_tool child {child.span_id} missing gen_ai.tool.call.id"
            )
        if "gen_ai.usage.input_tokens" in child.attributes:
            raise SpanExportOrderError(
                f"child {child.span_id} illegally carries gen_ai.usage; "
                "usage is owned by the parent span only"
            )
        if child.tool_call_id not in parent.open_tool_calls:
            raise SpanExportOrderError(
                f"child call id {child.tool_call_id} not declared in parent tool_calls"
            )

    def close_child(self, parent: GenAISpan, child: GenAISpan) -> None:
        child.end_time = child.end_time or time.monotonic()
        parent.closed_tool_calls.add(child.tool_call_id)

    def try_export_parent(self, parent: GenAISpan) -> bool:
        now = time.monotonic()
        unresolved = parent.open_tool_calls - parent.closed_tool_calls
        if unresolved:
            if now - parent.start_time < self.deadline:
                return False  # defer, do not export
            # deadline exceeded: synthesize error children, never drop silently
            for call_id in unresolved:
                parent.attributes.setdefault("error.type", []).append(
                    "tool_resolution_deadline_exceeded"
                )
                parent.closed_tool_calls.add(call_id)
            raise SpanExportOrderError(
                f"parent {parent.span_id} force-closed at deadline with "
                f"{len(unresolved)} unresolved tool calls: {sorted(unresolved)}"
            )
        parent.end_time = max(
            [parent.start_time] + [parent.end_time or 0.0]
        )
        parent.exported = True
        return True
