# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-genai-span-tree-as-a-trajectory-rather-than-a-request-and-what-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-genai-span-tree-as-a-trajectory-rather-than-a-request-and-what-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   16e733daaaebcedca9856ea672b3a9d7b27e91c3ca59ce0822adb6bc5720fde8
# Code AST SHA-256:   a2d49679c7ee8415b166297647d4720f9bff646ddceac14dfdfb50c1c3075a02
# Verified Classes:   TrajectoryModelError, ToolSpan, ChatSpan
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TrajectoryModelError(RuntimeError):
    """Raised when a GenAI span tree cannot be safely interpreted as a trajectory."""


@dataclass
class ToolSpan:
    span_id: str
    parent_chat_span_id: str
    tool_call_id: Optional[str]
    turn_index: Optional[int]
    completion_ns: int


@dataclass
class ChatSpan:
    span_id: str
    turn_index: Optional[int]
    declared_tool_call_ids: list[str]


def assert_replayable_trajectory(
    chat_spans: list[ChatSpan],
    tool_spans: list[ToolSpan],
) -> None:
    if not chat_spans:
        raise TrajectoryModelError("empty trace: no gen_ai.chat spans to model")

    turn_indices = [c.turn_index for c in chat_spans]
    if any(t is None for t in turn_indices):
        raise TrajectoryModelError(
            "missing gen_ai.turn.index on one or more chat spans; "
            "tree encodes containment, not turn order"
        )
    if turn_indices != sorted(turn_indices):
        raise TrajectoryModelError(
            f"turn indices not monotonic: {turn_indices}; "
            "cannot establish causal turn ordering"
        )

    declared: dict[str, int] = {}
    for chat in chat_spans:
        for call_id in chat.declared_tool_call_ids:
            if call_id in declared:
                raise TrajectoryModelError(
                    f"tool_call_id {call_id!r} declared by multiple turns; "
                    "cannot attribute tool output to a unique reasoning step"
                )
            declared[call_id] = chat.turn_index  # type: ignore[assignment]

    seen: dict[str, ToolSpan] = {}
    for tool in tool_spans:
        if tool.tool_call_id is None:
            raise TrajectoryModelError(
                f"tool span {tool.span_id} has no gen_ai.tool.call.id; "
                "ordering would fall back to completion timestamps"
            )
        if tool.tool_call_id not in declared:
            raise TrajectoryModelError(
                f"tool span {tool.span_id} references unknown tool_call_id "
                f"{tool.tool_call_id!r}; output cannot be placed in the trajectory"
            )
        if tool.turn_index is None or tool.turn_index != declared[tool.tool_call_id]:
            raise TrajectoryModelError(
                f"tool span {tool.span_id} turn_index {tool.turn_index} disagrees "
                f"with declaring chat turn {declared[tool.tool_call_id]}; "
                "causal edge is inconsistent with containment edge"
            )
        seen[tool.tool_call_id] = tool

    # Parallel fan-out check: within a turn, issue order (declared) must be
    # distinguishable from completion order (timestamp). If the two orders
    # differ and no explicit call id exists, replay will diverge.
    by_turn: dict[int, list[ToolSpan]] = {}
    for tool in tool_spans:
        by_turn.setdefault(tool.turn_index, []).append(tool)  # type: ignore[arg-type]
    for turn, tools in by_turn.items():
        if len(tools) > 1:
            completion_order = [t.tool_call_id for t in sorted(tools, key=lambda t: t.completion_ns)]
            declared_order = [
                cid for cid in next(
                    c.declared_tool_call_ids for c in chat_spans if c.turn_index == turn
                )
            ]
            if completion_order != declared_order:
                # Acceptable ONLY because every tool carries a call id; the
                # guard here documents the hazard rather than rejecting.
                pass
