import { AiTokenUsageRepository } from "../data/repositories/AiTokenUsageRepository.js";
import { emitAiAssistantEvent } from "../events.js";
async function recordTokenUsage(input, container) {
  const tenantId = input.authContext.tenantId;
  if (!tenantId) return;
  try {
    const em = container.resolve("em");
    const repo = new AiTokenUsageRepository(em.fork());
    const inputTokens = input.usage.inputTokens ?? 0;
    const outputTokens = input.usage.outputTokens ?? 0;
    const cachedInputTokens = input.usage.cachedInputTokens ?? 0;
    const reasoningTokens = input.usage.reasoningTokens ?? 0;
    const now = /* @__PURE__ */ new Date();
    const day = now.toISOString().slice(0, 10);
    await repo.createEvent({
      tenantId,
      organizationId: input.authContext.organizationId ?? null,
      userId: input.authContext.userId,
      agentId: input.agentId,
      moduleId: input.moduleId,
      sessionId: input.sessionId,
      turnId: input.turnId,
      stepIndex: input.stepIndex,
      providerId: input.providerId,
      modelId: input.modelId,
      inputTokens,
      outputTokens,
      cachedInputTokens: input.usage.cachedInputTokens ?? null,
      reasoningTokens: input.usage.reasoningTokens ?? null,
      finishReason: input.finishReason ?? null,
      loopAbortReason: input.loopAbortReason ?? null
    });
    await repo.upsertDaily({
      tenantId,
      organizationId: input.authContext.organizationId ?? null,
      day,
      agentId: input.agentId,
      modelId: input.modelId,
      providerId: input.providerId,
      sessionId: input.sessionId,
      inputTokens,
      outputTokens,
      cachedInputTokens,
      reasoningTokens
    });
  } catch (error) {
    console.warn(
      "[AI token-usage] recordTokenUsage failed (turn continues unaffected):",
      error instanceof Error ? error.message : error
    );
    return;
  }
  try {
    await emitAiAssistantEvent(
      "ai.token_usage.recorded",
      {
        tenantId,
        agentId: input.agentId,
        sessionId: input.sessionId,
        turnId: input.turnId,
        stepIndex: input.stepIndex,
        modelId: input.modelId,
        inputTokens: input.usage.inputTokens ?? 0,
        outputTokens: input.usage.outputTokens ?? 0
      },
      { persistent: false }
    );
  } catch (emitError) {
    console.warn(
      "[AI token-usage] Event emit failed (non-fatal):",
      emitError instanceof Error ? emitError.message : emitError
    );
  }
}
export {
  recordTokenUsage
};
//# sourceMappingURL=token-usage-recorder.js.map
