# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-span-tree-silently-fork-when-opentelemetry-genai-semconv-attributes-are-emitted-from-a-resumed-agent-after-a-mid-task-checkpoin.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-span-tree-silently-fork-when-opentelemetry-genai-semconv-attributes-are-emitted-from-a-resumed-agent-after-a-mid-task-checkpoin.warrant.json
# Markdown SHA-256:   e67149e181a787b18350131820f426eb7719a45668b492bae2cf4da8865b2dff
# Code AST SHA-256:   a641cd6339725974e7933a1c3e8b096615e8030dbe56016ede75a3803f18130d
# Verified Classes:   TraceContextForkError, SpanContext, Checkpoint, EmittedSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TraceContextForkError(RuntimeError):
    """Raised when a resumed agent emits a root span with no bridge to its checkpoint span."""
    pass


@dataclass
class SpanContext:
    trace_id: str
    span_id: str
    trace_flags: int = 1


@dataclass
class Checkpoint:
    checkpoint_id: str
    resume_seq: int
    # The field whose absence causes the silent fork:
    span_context: Optional[SpanContext] = None
    accumulated_input_tokens: int = 0
    accumulated_output_tokens: int = 0


@dataclass
class EmittedSpan:
    name: str
    trace_id: str
    parent_span_id: Optional[str]
    links: list = field(default_factory=list)
    gen_ai_input_tokens: int = 0
    gen_ai_output_tokens: int = 0
    attributes: dict = field(default_factory=dict)


def resume_agent_span(checkpoint: Checkpoint, new_trace_id: str, replayed_prompt_tokens: int) -> EmittedSpan:
    """
    Emit the resumed invoke_agent span, enforcing the continuity invariant:
    either restore the parent SpanContext, or declare a Link to the checkpoint span.
    Also forbid re-measuring replayed prompt tokens into gen_ai.usage.
    """
    has_parent = checkpoint.span_context is not None
    has_link = bool(checkpoint.span_context) and checkpoint.attributes_link_declared() if hasattr(checkpoint, "attributes_link_declared") else False

    span = EmittedSpan(
        name="invoke_agent",
        trace_id=new_trace_id,
        parent_span_id=checkpoint.span_context.span_id if has_parent else None,
        links=[checkpoint.span_context] if (not has_parent and checkpoint.span_context) else [],
        attributes={"gen_ai.agent.resume_of": checkpoint.checkpoint_id},
    )

    if not has_parent and not span.links:
        raise TraceContextForkError(
            f"resume of checkpoint {checkpoint.checkpoint_id!r} emitted a root span "
            f"with no restored parent SpanContext and no Link to the checkpoint span; "
            f"trace tree will silently fork (expected parent trace, got {new_trace_id})"
        )

    # Token accounting: do NOT re-emit replayed prompt tokens as new usage.
    if replayed_prompt_tokens > 0:
        raise TraceContextForkError(
            f"resume re-measured {replayed_prompt_tokens} replayed prompt tokens into "
            f"gen_ai.usage.input_tokens; carry accumulated counters as a delta instead "
            f"(checkpoint already recorded {checkpoint.accumulated_input_tokens})"
        )

    span.gen_ai_input_tokens = checkpoint.accumulated_input_tokens
    span.gen_ai_output_tokens = checkpoint.accumulated_output_tokens
    return span
