"use client";
import { useMemo } from "react";
import { create } from "@bufbuild/protobuf";
import { GetSessionUsageReportInputSchema, } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/io_pb";
import { useStigmer } from "../hooks";
import { useFetch } from "../internal/useFetch";
const EMPTY = {
    totalCostUsd: 0,
    totalTokens: 0,
    inputTokens: 0,
    outputTokens: 0,
    cacheReadTokens: 0,
    cacheCreationTokens: 0,
    llmCallCount: 0,
    modelBreakdown: [],
    primaryModel: "",
    primaryProvider: "",
    hasUsage: false,
};
function microsToUsd(micros) {
    return Number(micros) / 1_000_000;
}
function mapModelUsage(m) {
    return {
        model: m.model,
        provider: m.provider,
        estimatedCostUsd: microsToUsd(m.billableCostMicros),
        inputTokens: Number(m.inputTokens),
        outputTokens: Number(m.outputTokens),
        cacheCreationTokens: Number(m.cacheCreationInputTokens),
        cacheReadTokens: Number(m.cacheReadInputTokens),
        callCount: m.callCount,
    };
}
function mapReport(report) {
    const agg = report.totalUsage;
    if (!agg)
        return EMPTY;
    return {
        totalCostUsd: microsToUsd(agg.billableCostMicros),
        totalTokens: Number(agg.totalTokens),
        inputTokens: Number(agg.inputTokens),
        outputTokens: Number(agg.outputTokens),
        cacheReadTokens: Number(agg.cacheReadInputTokens),
        cacheCreationTokens: Number(agg.cacheCreationInputTokens),
        llmCallCount: agg.llmCallCount,
        modelBreakdown: report.modelBreakdown.map(mapModelUsage),
        primaryModel: agg.primaryModel,
        primaryProvider: agg.primaryProvider,
        hasUsage: true,
    };
}
/**
 * Usage hook for session-level cost and token aggregation.
 *
 * Calls `getSessionUsageReport` to fetch real usage data from the
 * billing domain. Returns zeros while loading or when no session is
 * available.
 *
 * @param executions - All executions for a session (used to derive session ID).
 */
export function useSessionUsage(executions) {
    const stigmer = useStigmer();
    const sessionId = useMemo(() => executions[0]?.spec?.sessionId ?? null, [executions]);
    const { data: report } = useFetch(sessionId
        ? () => stigmer.agentExecution.getSessionUsageReport(create(GetSessionUsageReportInputSchema, { sessionId }))
        : null, [sessionId, stigmer], null, { cacheKey: sessionId ? `session-usage:${sessionId}` : undefined });
    return useMemo(() => {
        if (!report)
            return EMPTY;
        return mapReport(report);
    }, [report]);
}
//# sourceMappingURL=useSessionUsage.js.map