/**
 * AI Usage Tracker — logs every LLM call with token counts + cost.
 * Fire-and-forget (non-blocking) so it never slows down AI calls.
 */

import { prisma } from "@/lib/prisma";

// Cost per 1K tokens (Claude Sonnet 4 pricing as of 2026)
const COST_TABLE: Record<string, { input: number; output: number }> = {
  "claude-sonnet-4-20250514": { input: 0.003, output: 0.015 },
  "claude-opus-4-20250514": { input: 0.015, output: 0.075 },
  "claude-haiku-4-5-20251001": { input: 0.001, output: 0.005 },
  default: { input: 0.003, output: 0.015 },
};

export interface AiUsageParams {
  brandId?: string;
  userId?: string;
  feature: string;
  provider: string;
  model: string;
  inputTokens: number;
  outputTokens: number;
  duration?: number;
}

export function trackAiUsage(params: AiUsageParams): void {
  const costs = COST_TABLE[params.model] || COST_TABLE.default;
  const estimatedCost = (params.inputTokens / 1000) * costs.input + (params.outputTokens / 1000) * costs.output;

  // Fire-and-forget — don't await, don't block the caller
  prisma.aiUsageLog.create({
    data: {
      brandId: params.brandId ?? null,
      userId: params.userId ?? null,
      provider: params.provider,
      model: params.model,
      feature: params.feature,
      inputTokens: params.inputTokens,
      outputTokens: params.outputTokens,
      estimatedCost,
      duration: params.duration ?? null,
    },
  }).catch((err) => {
    console.error("[ai-usage-tracker] failed to log", err);
  });
}
