"""Span builder for CLI agent hook integrations.

Defines the canonical span dict structure sent to the Staso ingest API.
All agent modules import ``base_span`` from here.
"""
from __future__ import annotations

from typing import Any

from .helpers import safe_json


def base_span(
    *,
    trace_id: str,
    span_id: str,
    parent_span_id: str | None,
    name: str,
    kind: str,
    timestamp: str,
    duration_ms: float,
    session_id: str,
    agent_id: str,
    status: str = "ok",
    model: str = "",
    input_tokens: int = 0,
    output_tokens: int = 0,
    total_tokens: int = 0,
    input_data: dict[str, Any] | None = None,
    output_data: dict[str, Any] | None = None,
    metadata: dict[str, Any] | None = None,
    error_message: str | None = None,
) -> dict[str, Any]:
    return {
        "trace_id": trace_id,
        "span_id": span_id,
        "parent_span_id": parent_span_id,
        "name": name,
        "kind": kind,
        "timestamp": timestamp,
        "duration_ms": round(duration_ms, 2),
        "status": status,
        "model": model,
        "input_tokens": input_tokens,
        "output_tokens": output_tokens,
        "total_tokens": total_tokens,
        "input": safe_json(input_data) if input_data else "",
        "output": safe_json(output_data) if output_data else "",
        "attributes": safe_json(metadata) if metadata else "{}",
        "error_message": error_message,
        "session_id": session_id,
        "agent_id": agent_id,
        "user_id": "",
    }
