# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-drop-tool-call-spans-when-the-genai-semantic-convention-attribute-set-diverges-mid-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-drop-tool-call-spans-when-the-genai-semantic-convention-attribute-set-diverges-mid-trace.warrant.json
# Markdown SHA-256:   1356a2be55a973019ff9adb31df2e0249edd2e9cff54ae6159345b2d5184100d
# Code AST SHA-256:   281a0fa53fef0596525f4f45478e3e00df63662db44bfedb6a984460a2325a07
# Verified Classes:   SpanSemanticJoinError, ToolSpan, AgentCheckpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpanSemanticJoinError(RuntimeError):
    """Raised when a tool-call span cannot be joined to agent state by call_id."""
    pass


@dataclass
class ToolSpan:
    trace_id: str
    span_id: str
    operation_name: str
    tool_name: Optional[str]
    tool_call_id: Optional[str]
    convention_version: str
    input_tokens_key: str  # "gen_ai.usage.input_tokens" or legacy


@dataclass
class AgentCheckpoint:
    trace_id: str
    recorded_call_ids: list[str] = field(default_factory=list)


def audit_tool_chain(
    spans: list[ToolSpan],
    checkpoint: AgentCheckpoint,
    expected_convention: str,
) -> dict:
    """
    Reconstruct the tool chain by call_id and flag any span that is
    structurally present but semantically unjoinable.
    """
    # Guard 1: convention version must be uniform across the trace.
    versions = {s.convention_version for s in spans}
    if versions != {expected_convention}:
        raise SpanSemanticJoinError(
            f"convention divergence in trace {checkpoint.trace_id}: "
            f"expected {expected_convention!r}, saw {sorted(versions)!r}; "
            f"attribute-keyed joins are invalid for this trace"
        )

    # Guard 2: every recorded call_id must have exactly one execute_tool span
    # carrying it, regardless of operation_name fallback.
    by_call_id: dict[str, list[ToolSpan]] = {}
    misclassified: list[ToolSpan] = []
    for s in spans:
        if s.tool_call_id:
            by_call_id.setdefault(s.tool_call_id, []).append(s)
        elif s.operation_name == "chat" and not _has_usage(s):
            # Signature of the fallback path: a "chat" span with no usage
            # attributes and no call_id is a misclassified tool span.
            misclassified.append(s)

    problems: list[str] = []
    for cid in checkpoint.recorded_call_ids:
        matched = by_call_id.get(cid, [])
        if len(matched) != 1:
            problems.append(f"call_id {cid}: expected 1 span, found {len(matched)}")
        else:
            span = matched[0]
            if span.operation_name != "execute_tool":
                problems.append(
                    f"call_id {cid}: span {span.span_id} has operation_name "
                    f"{span.operation_name!r}, not 'execute_tool'"
                )
            if not span.tool_name:
                problems.append(f"call_id {cid}: span {span.span_id} missing tool.name")

    if misclassified:
        problems.append(
            f"{len(misclassified)} span(s) look like misclassified tool calls "
            f"(operation_name='chat', no usage attrs): "
            f"{[s.span_id for s in misclassified]}"
        )

    if problems:
        raise SpanSemanticJoinError(
            f"tool chain in trace {checkpoint.trace_id} is not joinable: "
            + "; ".join(problems)
        )

    return {
        "trace_id": checkpoint.trace_id,
        "chain": [by_call_id[cid][0].tool_name for cid in checkpoint.recorded_call_ids],
        "join_key": "gen_ai.tool.call_id",
    }


def _has_usage(span: ToolSpan) -> bool:
    # A genuine chat span carries a usage key; the fallback tool span does not.
    return span.input_tokens_key in (
        "gen_ai.usage.input_tokens",
        "gen_ai.usage.prompt_tokens",
    )
