# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-an-opentelemetry-genai-span-before-tool-call-resolution-attribute-set-divergence-across-parent-child-spans-and-t.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-an-opentelemetry-genai-span-before-tool-call-resolution-attribute-set-divergence-across-parent-child-spans-and-t.warrant.json
# Markdown SHA-256:   3a6d5bdf4a024075cd46bccd7bc28c0a8a801148b47e51a7038496d097fda648
# Code AST SHA-256:   0240b030a6550000dac29ea9e543d5ef711f7510eb88db72454a0bd3c1061079
# Verified Classes:   SpanFinalizationError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class SpanFinalizationError(RuntimeError):
    """Raised when a GenAI agent span is ended before its contributing
    child spans (chat/tool) have resolved and been folded into the
    parent's aggregate attributes."""


@dataclass
class GenAISpan:
    name: str
    operation: str  # "invoke_agent" | "chat" | "execute_tool"
    start_time: float = field(default_factory=time.monotonic)
    end_time: float | None = None
    parent: "GenAISpan | None" = None
    children: list["GenAISpan"] = field(default_factory=list)
    attributes: dict = field(default_factory=dict)

    def end(self):
        self.end_time = time.monotonic()
        self.attributes["_frozen_at"] = self.end_time

    def add_child(self, child: "GenAISpan"):
        child.parent = self
        self.children.append(child)


def finalize_agent_span(agent: GenAISpan, aggregate_usage: dict, tool_inventory: list[str]):
    """Enforce the parent-span finalization barrier before freezing the
    agent span's aggregate GenAI attributes."""
    if agent.operation != "invoke_agent":
        raise SpanFinalizationError(
            f"finalize_agent_span called on non-agent span operation={agent.operation!r}"
        )

    # Barrier check: every contributing child must have ended, and the
    # parent's freeze time must be >= the max child end time.
    unresolved = [c.name for c in agent.children if c.end_time is None]
    if unresolved:
        raise SpanFinalizationError(
            f"agent span {agent.name!r} attempted to end with unresolved "
            f"children {unresolved}; aggregate gen_ai.usage.* would describe "
            f"a prefix of the turn, not the full turn"
        )

    max_child_end = max((c.end_time for c in agent.children), default=agent.start_time)
    freeze_time = time.monotonic()
    if freeze_time < max_child_end:
        raise SpanFinalizationError(
            f"agent span {agent.name!r} freeze_time {freeze_time:.6f} precedes "
            f"max child end_time {max_child_end:.6f}; token aggregate would "
            f"double-count or under-count against child chat spans"
        )

    # Fold child contributions into the parent, then freeze.
    agent.attributes["gen_ai.usage.input_tokens"] = aggregate_usage.get("input_tokens", 0)
    agent.attributes["gen_ai.usage.output_tokens"] = aggregate_usage.get("output_tokens", 0)
    agent.attributes["gen_ai.tool_names"] = sorted(set(tool_inventory))
    agent.end()

    # Post-condition: parent must end at or after every child.
    for c in agent.children:
        if agent.end_time < c.end_time:
            raise SpanFinalizationError(
                f"post-condition violated: child {c.name!r} ended after parent "
                f"{agent.name!r}; trace is structurally valid but semantically false"
            )
    return agent
