/**
 * Shared usage report builder — constructs a `WakeCycleUsageReport` from
 * a stored `WakeCycleRecord` row in `transcript_memory.db`.
 *
 * Used by:
 *  - `UsageReporter` (background scan → enqueue into usage.db)
 *  - `usage-backfill-handler` (direct server upload)
 */
import { USAGE_REPORT_SCHEMA_VERSION, } from "./usage-report-types.js";
function getCurrentVersionSafe() {
    try {
        return process.env.npm_package_version;
    }
    catch {
        return undefined;
    }
}
function durationSeconds(start, end) {
    const startMs = new Date(start).getTime();
    const endMs = new Date(end).getTime();
    if (Number.isNaN(startMs) || Number.isNaN(endMs) || endMs < startMs)
        return 0;
    return Math.max(0, Math.round((endMs - startMs) / 1000));
}
/**
 * Parse `tool_calls_json` from a wake cycle record.
 *
 * Returns an empty array if the JSON is null, empty, or invalid.
 */
function parseToolCallsJson(json) {
    if (!json)
        return [];
    try {
        const parsed = JSON.parse(json);
        if (!Array.isArray(parsed))
            return [];
        return parsed;
    }
    catch {
        return [];
    }
}
/**
 * Build a `WakeCycleUsageReport` from a stored wake cycle record.
 *
 * If `tool_calls_json` is missing or invalid, the report is built with
 * empty tool calls — the server will mark coverage as `missing_tool_calls`.
 *
 * If `overrideToolCalls` is provided, it takes precedence over the stored
 * JSON (used when backfill reconstructs tool calls from archived transcripts).
 */
export function buildWakeCycleUsageReportFromRecord(input) {
    const { row, config, overrideToolCalls } = input;
    const toolCalls = overrideToolCalls ?? parseToolCallsJson(row.tool_calls_json);
    const toolCallCount = overrideToolCalls
        ? overrideToolCalls.length
        : (row.tool_call_count || toolCalls.length);
    return {
        schemaVersion: USAGE_REPORT_SCHEMA_VERSION,
        wakeCycleId: row.wake_cycle_id,
        sessionType: row.session_type,
        startedAt: row.timestamp_start,
        endedAt: row.timestamp_end,
        durationSeconds: durationSeconds(row.timestamp_start, row.timestamp_end),
        triggerType: row.trigger_type ?? undefined,
        triggerChannel: row.trigger_channel ?? undefined,
        toolCalls,
        toolCallCount,
        ...(row.tool_calls_truncated
            ? {
                toolCallsTruncated: true,
                reportedToolCallCount: row.reported_tool_call_count ?? toolCalls.length,
            }
            : {}),
        outcome: row.outcome ?? "completed",
        agentVersion: getCurrentVersionSafe(),
        modelId: config.model,
    };
}
//# sourceMappingURL=usage-report-builder.js.map