/**
 * Image Generation Pricing Constants & Calculator
 *
 * Provides cost estimation for AI image generation across providers.
 * Prices are in USD per image for generation, and per 1M tokens for prompt enhancement.
 */

// ============================================
// IMAGE GENERATION PRICING (per image)
// ============================================

export const IMAGE_GEN_PRICING: Record<string, Record<string, { standard: number; hd: number }>> = {
  openai: {
    'gpt-image-2': { standard: 0.053, hd: 0.211 },
    'gpt-image-1': { standard: 0.011, hd: 0.040 },
    'dall-e-3': { standard: 0.040, hd: 0.080 },
  },
  zhipu: {
    'cogview-3': { standard: 0.002, hd: 0.002 },
  },
  ollama: {
    'llava': { standard: 0, hd: 0 },
    'default': { standard: 0, hd: 0 },
  },
  flux: {
    'flux-pro': { standard: 0.05, hd: 0.05 },
    'flux-schnell': { standard: 0.01, hd: 0.01 },
    'flux-dev': { standard: 0.025, hd: 0.025 },
    'default': { standard: 0.05, hd: 0.05 },
  },
  midjourney: {
    'midjourney-v6': { standard: 0.10, hd: 0.10 },
    'midjourney-v7': { standard: 0.10, hd: 0.10 },
    'default': { standard: 0.10, hd: 0.10 },
  },
  ideogram: {
    'ideogram-v2': { standard: 0.08, hd: 0.08 },
    'ideogram-v3': { standard: 0.08, hd: 0.08 },
    'default': { standard: 0.08, hd: 0.08 },
  },
  nano: {
    'nano-v1': { standard: 0.01, hd: 0.01 },
    'default': { standard: 0.01, hd: 0.01 },
  },
};

// ============================================
// PROMPT ENHANCEMENT PRICING (per 1M tokens)
// ============================================

export const PROMPT_ENHANCEMENT_PRICING: Record<string, { inputPerMillion: number; outputPerMillion: number }> = {
  ollama: { inputPerMillion: 0, outputPerMillion: 0 },
  openai: { inputPerMillion: 0.15, outputPerMillion: 0.60 },
  zhipu: { inputPerMillion: 0.10, outputPerMillion: 0.40 },
  claude: { inputPerMillion: 0.25, outputPerMillion: 1.25 },
};

// ============================================
// CALCULATOR FUNCTIONS
// ============================================

/**
 * Calculate the estimated cost for an image generation.
 */
export function calculateImageCost(
  provider: string,
  model: string,
  quality: 'standard' | 'hd' = 'standard',
): number {
  const providerPricing = IMAGE_GEN_PRICING[provider];
  if (!providerPricing) return 0;

  const modelPricing = providerPricing[model] || providerPricing['default'];
  if (!modelPricing) return 0;

  return modelPricing[quality] || modelPricing.standard;
}

/**
 * Calculate the estimated cost for prompt enhancement (token-based).
 */
export function calculatePromptCost(
  provider: string,
  inputTokens: number,
  outputTokens: number,
): number {
  const pricing = PROMPT_ENHANCEMENT_PRICING[provider];
  if (!pricing) return 0;

  const inputCost = (inputTokens / 1_000_000) * pricing.inputPerMillion;
  const outputCost = (outputTokens / 1_000_000) * pricing.outputPerMillion;

  return inputCost + outputCost;
}

/**
 * Calculate total cost for a generation record including all versions.
 * Returns the total estimated cost in USD.
 */
export function calculateTotalGenerationCost(generation: {
  generationProvider?: string;
  generationModel?: string;
  versions: Array<{
    quality?: string;
    generationProvider?: string;
    generationModel?: string;
    tokenUsage?: { inputTokens?: number; outputTokens?: number; totalTokens?: number };
  }>;
  ollamaEnhancedPrompt?: string;
}): number {
  let totalCost = 0;

  for (const version of generation.versions) {
    // Image generation cost
    const provider = version.generationProvider || generation.generationProvider || 'openai';
    const model = version.generationModel || generation.generationModel || 'gpt-image-1';
    const quality = (version.quality as 'standard' | 'hd') || 'standard';

    totalCost += calculateImageCost(provider, model, quality);

    // Prompt enhancement token cost (if token usage was tracked)
    if (version.tokenUsage) {
      const enhancerProvider = provider === 'ollama' ? 'ollama' : 'openai';
      totalCost += calculatePromptCost(
        enhancerProvider,
        version.tokenUsage.inputTokens || 0,
        version.tokenUsage.outputTokens || 0,
      );
    }
  }

  return totalCost;
}

/**
 * Format a cost in USD for display.
 */
export function formatCost(costUSD: number): string {
  if (costUSD < 0.001) return '$0.000';
  if (costUSD < 0.01) return `$${costUSD.toFixed(4)}`;
  if (costUSD < 1) return `$${costUSD.toFixed(3)}`;
  return `$${costUSD.toFixed(2)}`;
}

/**
 * Format latency in milliseconds for display.
 */
export function formatLatency(ms: number | undefined): string {
  if (ms === undefined || ms === null) return '—';
  if (ms < 1000) return `${Math.round(ms)}ms`;
  return `${(ms / 1000).toFixed(1)}s`;
}

/**
 * Format token count for display.
 */
export function formatTokens(count: number | undefined): string {
  if (count === undefined || count === null) return '—';
  if (count < 1000) return String(count);
  if (count < 1_000_000) return `${(count / 1000).toFixed(1)}K`;
  return `${(count / 1_000_000).toFixed(1)}M`;
}