/**
 * Tarification OpenAI (avril 2026, USD par 1M tokens).
 * À mettre à jour si OpenAI ajuste ses prix.
 */
const TEXT_PRICING: Record<string, { input: number; cachedInput: number; output: number }> = {
  'gpt-4o-mini': { input: 0.15, cachedInput: 0.075, output: 0.6 },
  'gpt-4o': { input: 2.5, cachedInput: 1.25, output: 10 },
  'gpt-4.1-mini': { input: 0.4, cachedInput: 0.1, output: 1.6 },
  'gpt-4.1': { input: 2.0, cachedInput: 0.5, output: 8.0 },
};

const TRANSCRIBE_PRICING_PER_MIN: Record<string, number> = {
  'whisper-1': 0.006,
  'gpt-4o-mini-transcribe': 0.003,
  'gpt-4o-transcribe': 0.006,
};

const IMAGE_PRICING: Record<string, Record<string, number>> = {
  'dall-e-3': {
    '1024x1024': 0.04,
    '1024x1792': 0.08,
    '1792x1024': 0.08,
  },
  'gpt-image-1': {
    'low_1024x1024': 0.011,
    'medium_1024x1024': 0.042,
    'high_1024x1024': 0.167,
  },
};

export interface UsageBreakdown {
  promptTokens?: number;
  cachedTokens?: number;
  completionTokens?: number;
  audioMinutes?: number;
  imageQuality?: 'low' | 'medium' | 'high' | 'standard' | 'hd';
  imageSize?: string;
}

/**
 * Calcule le coût USD d'un appel OpenAI.
 * Retourne 0 si le modèle est inconnu (on évite de faire échouer l'appel
 * pour un manquement de tarification).
 */
export function computeTextCost(model: string, usage: UsageBreakdown): number {
  const pricing = TEXT_PRICING[model];
  if (!pricing) return 0;

  const promptTokens = usage.promptTokens ?? 0;
  const cachedTokens = usage.cachedTokens ?? 0;
  const completionTokens = usage.completionTokens ?? 0;

  const billedPromptTokens = Math.max(0, promptTokens - cachedTokens);

  return (
    (billedPromptTokens * pricing.input) / 1_000_000 +
    (cachedTokens * pricing.cachedInput) / 1_000_000 +
    (completionTokens * pricing.output) / 1_000_000
  );
}

export function computeTranscribeCost(model: string, audioMinutes: number): number {
  const rate = TRANSCRIBE_PRICING_PER_MIN[model];
  if (!rate) return 0;
  return rate * audioMinutes;
}

export function computeImageCost(
  model: string,
  size: string,
  quality: string = 'medium'
): number {
  const modelPricing = IMAGE_PRICING[model];
  if (!modelPricing) return 0;
  if (model === 'gpt-image-1') {
    return modelPricing[`${quality}_${size}`] ?? 0;
  }
  return modelPricing[size] ?? 0;
}

export interface CallLog {
  userId?: string;
  operation: 'transcription' | 'recipe_generation' | 'image_generation';
  model: string;
  durationMs: number;
  costUsd: number;
  usage?: UsageBreakdown;
  cacheHit?: boolean;
}
