# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-genai-tool-call-lineage-spans-when-the-parent-generation-span-has-already-been-closed-by-a-token-acc.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-genai-tool-call-lineage-spans-when-the-parent-generation-span-has-already-been-closed-by-a-token-acc.warrant.json
# Markdown SHA-256:   8ecfaf7a9f5ede768fb11947dc68af9e69d42a9d262b17722b6add7682a8fbde
# Code AST SHA-256:   81a1a6173f0a10f206919db57737e270662ae22d35b0511b8f58d6f0053557c2
# Verified Classes:   ToolLineageParentClosedError, Span, GenerationContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class ToolLineageParentClosedError(RuntimeError):
    """Raised when a tool-call span would be parented to an already-ended generation span."""


@dataclass
class Span:
    name: str
    span_id: str
    parent_span_id: str | None = None
    start_time: float = field(default_factory=time.monotonic)
    end_time: float | None = None
    attributes: dict = field(default_factory=dict)

    def end(self) -> None:
        if self.end_time is not None:
            raise RuntimeError(f"span {self.span_id} already ended")
        self.end_time = time.monotonic()

    @property
    def is_ended(self) -> bool:
        return self.end_time is not None


@dataclass
class GenerationContext:
    generation_span: Span
    outstanding_tool_futures: int = 0
    pending_usage: dict = field(default_factory=dict)
    finalizer_span: Span | None = None


def finalize_usage_on_finish(ctx: GenerationContext, usage: dict, finish_reason: str) -> None:
    """Token-accounting finalizer. Must NOT close the generation span if tools are in flight."""
    ctx.pending_usage.update(usage)
    if finish_reason == "tool_calls" and ctx.outstanding_tool_futures > 0:
        # Defer close to the tool-execution join; do not end() here.
        return
    _write_usage_and_close(ctx)


def _write_usage_and_close(ctx: GenerationContext) -> None:
    ctx.generation_span.attributes.update(
        {
            "gen_ai.usage.input_tokens": ctx.pending_usage.get("input_tokens", 0),
            "gen_ai.usage.output_tokens": ctx.pending_usage.get("output_tokens", 0),
        }
    )
    if not ctx.generation_span.is_ended:
        ctx.generation_span.end()


def emit_tool_span(
    ctx: GenerationContext, tool_name: str, call_id: str, start_time: float
) -> Span:
    parent = ctx.generation_span
    if parent.is_ended and start_time > parent.end_time:
        # Lineage would be temporally impossible. Re-parent to finalizer if present.
        if ctx.finalizer_span is not None:
            parent = ctx.finalizer_span
        else:
            raise ToolLineageParentClosedError(
                f"tool span '{tool_name}' ({call_id}) start={start_time:.3f} "
                f"postdates ended parent generation span {parent.span_id} "
                f"end={parent.end_time:.3f}; no finalizer span available to re-parent"
            )
    span = Span(
        name=f"execute_tool {tool_name}",
        span_id=f"tool-{call_id}",
        parent_span_id=parent.span_id,
        start_time=start_time,
    )
    span.attributes["gen_ai.tool.call.id"] = call_id
    span.attributes["gen_ai.tool.name"] = tool_name
    return span


def on_tool_complete(ctx: GenerationContext, span: Span) -> None:
    span.end()
    ctx.outstanding_tool_futures -= 1
    if ctx.outstanding_tool_futures == 0 and ctx.pending_usage:
        # Join reached: now safe to write usage and close the generation span.
        _write_usage_and_close(ctx)
