/**
 * `tool_calls`, one row per tool call (D0091).
 *
 * The finest-grain agent-behavior table: every tool the agent invoked, in
 * order, with its normalized category, provenance, latency, and error flag.
 * Answers "which tools does each model lean on, how long do they take, how
 * often do they error" across modes and areas.
 *
 * Grain is one `toolCalls[i]` inside one `traces` entry (`EvalTrace`, per
 * run × mode × task × model × trial). A run with no traces (April runs
 * predate trace capture) yields zero rows, absence is normal.
 *
 * Derives from the canonical `EvalTrace` / `ToolCallRecord` core types
 * (D0045, derive, don't redeclare).
 *
 * @see packages/core/src/types/trace.ts, EvalTrace, ToolCallRecord
 * @see docs/design-docs/bigquery-analytics-fact-loader.md
 */
import { z } from "zod";
import { defineFactTable, } from "../descriptor.js";
import { axisString, LOADED_AT_COLUMN, nonNegIntOrNull, runFactBase, runFactBaseShape, RUN_FACT_BASE_COLUMNS, strOrNull, } from "./common.js";
import { trialNumber } from "./trace-common.js";
const rowSchema = z.object({
    ...runFactBaseShape,
    mode: z.string(),
    task: z.string(),
    model_id: z.string(),
    trial: z.number(),
    trace_id: z.string(),
    sequence: z.number(),
    tool_name: z.string(),
    category: z.string(),
    source: z.string(),
    duration_ms: z.number().nullable(),
    is_error: z.boolean(),
});
const schema = [
    ...RUN_FACT_BASE_COLUMNS,
    { name: "mode", type: "STRING" },
    { name: "task", type: "STRING" },
    { name: "model_id", type: "STRING" },
    { name: "trial", type: "INT64", mode: "REQUIRED" },
    { name: "trace_id", type: "STRING", description: "Owning trace id." },
    {
        name: "sequence",
        type: "INT64",
        mode: "REQUIRED",
        description: "Call order within the trace.",
    },
    { name: "tool_name", type: "STRING", description: "Provider tool name." },
    {
        name: "category",
        type: "STRING",
        description: "Normalized tool category.",
    },
    {
        name: "source",
        type: "STRING",
        description: "Where the call was observed.",
    },
    { name: "duration_ms", type: "INT64", description: "Call wall-clock (ms)." },
    {
        name: "is_error",
        type: "BOOL",
        mode: "REQUIRED",
        description: "Call reported an error.",
    },
    LOADED_AT_COLUMN,
];
// ---------------------------------------------------------------------------
// Extractor
// ---------------------------------------------------------------------------
function extract(ctx) {
    const rows = [];
    for (const entry of ctx.artifacts.entries("traces")) {
        const trace = entry.payload;
        const calls = Array.isArray(trace.toolCalls) ? trace.toolCalls : [];
        const base = runFactBase(ctx, entry.sourceUri);
        const mode = axisString(entry.association.mode);
        const task = axisString(entry.association.task);
        const modelId = axisString(entry.association.model);
        const trial = trialNumber(entry.association.trial);
        const traceId = strOrNull(trace.traceId) ?? "";
        calls.forEach((raw, sequence) => {
            rows.push({
                ...base,
                mode,
                task,
                model_id: modelId,
                trial,
                trace_id: traceId,
                sequence,
                tool_name: strOrNull(raw.name) ?? "unknown",
                category: strOrNull(raw.category) ?? "unknown",
                source: strOrNull(raw.source) ?? "unknown",
                duration_ms: nonNegIntOrNull(raw.durationMs),
                is_error: strOrNull(raw.error) !== null,
            });
        });
    }
    return rows;
}
export const toolCalls = defineFactTable({
    table: "tool_calls",
    dataset: "ailf_facts",
    sourceArtifacts: ["traces"],
    schema,
    rowSchema,
    partitionField: "completed_at",
    clusterFields: ["mode", "model_id", "category"],
    mergeKey: ["run_id", "mode", "task", "model_id", "trial", "sequence"],
    extract,
});
export { rowSchema as toolCallFactRowSchema };
