import type { TokenUsage } from '@/modules/token-accounting/entities/tokenUsage/tokenUsage.schema.js';

interface ModelRates {
  inputPerMillion: number;
  outputPerMillion: number;
  cacheCreationPerMillion: number;
  cacheReadPerMillion: number;
}

/**
 * Anthropic public pricing per 1M tokens.
 * Last updated: 2026-05-23 - source: https://www.anthropic.com/pricing
 * Refresh on Claude model family bumps.
 */
export const MODEL_PRICING_USD_PER_MILLION: Record<string, ModelRates> = {
  'claude-opus-4': {
    inputPerMillion: 15,
    outputPerMillion: 75,
    cacheCreationPerMillion: 18.75,
    cacheReadPerMillion: 1.5,
  },
  'claude-sonnet-4': {
    inputPerMillion: 3,
    outputPerMillion: 15,
    cacheCreationPerMillion: 3.75,
    cacheReadPerMillion: 0.3,
  },
  'claude-haiku-4-5': {
    inputPerMillion: 1,
    outputPerMillion: 5,
    cacheCreationPerMillion: 1.25,
    cacheReadPerMillion: 0.1,
  },
};

const FALLBACK_RATES: ModelRates = MODEL_PRICING_USD_PER_MILLION['claude-opus-4'];

function resolveRates(model: string): ModelRates {
  for (const prefix of Object.keys(MODEL_PRICING_USD_PER_MILLION)) {
    if (model.startsWith(prefix)) {
      return MODEL_PRICING_USD_PER_MILLION[prefix];
    }
  }
  return FALLBACK_RATES;
}

export function computeCostUsd(model: string, tokens: TokenUsage): number {
  const rates = resolveRates(model);
  const million = 1_000_000;
  const inputCost = (tokens.inputTokens / million) * rates.inputPerMillion;
  const outputCost = (tokens.outputTokens / million) * rates.outputPerMillion;
  const cacheCreationCost =
    (tokens.cacheCreationInputTokens / million) * rates.cacheCreationPerMillion;
  const cacheReadCost = (tokens.cacheReadInputTokens / million) * rates.cacheReadPerMillion;
  return inputCost + outputCost + cacheCreationCost + cacheReadCost;
}
