export function formatNumber(n: number): string {
  if (n >= 1_000_000_000) return (n / 1_000_000_000).toFixed(1) + 'B'
  if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + 'M'
  if (n >= 1_000) return (n / 1_000).toFixed(1) + 'K'
  return n.toFixed(0)
}

export function formatTokens(n: number): string {
  if (n >= 1_000_000_000) return (n / 1_000_000_000).toFixed(2) + 'B'
  if (n >= 1_000_000) return (n / 1_000_000).toFixed(2) + 'M'
  if (n >= 1_000) return (n / 1_000).toFixed(1) + 'K'
  return n.toString()
}

export function formatDuration(minutes: number): string {
  if (minutes < 1) return '< 1m'
  if (minutes < 60) return `${Math.round(minutes)}m`
  const h = Math.floor(minutes / 60)
  const m = Math.round(minutes % 60)
  if (h < 24) return `${h}h ${m}m`
  const d = Math.floor(h / 24)
  const rh = h % 24
  return `${d}d ${rh}h`
}

export function timeAgo(dateStr: string | null): string {
  if (!dateStr) return 'never'
  const diff = Date.now() - new Date(dateStr).getTime()
  const seconds = Math.floor(diff / 1000)
  if (seconds < 10) return 'just now'
  if (seconds < 60) return `${seconds}s ago`
  const minutes = Math.floor(seconds / 60)
  if (minutes < 60) return `${minutes}m ago`
  const hours = Math.floor(minutes / 60)
  if (hours < 24) return `${hours}h ago`
  return `${Math.floor(hours / 24)}d ago`
}

export function estimateCost(input: number, output: number, cached: number): number {
  // Gemini 3 Flash pricing (approximate)
  const inputRate = 0.10 / 1_000_000    // $0.10 per 1M input tokens
  const outputRate = 0.40 / 1_000_000   // $0.40 per 1M output tokens
  const cacheDiscount = 0.25

  const uncachedInput = input - cached
  const cost = (uncachedInput * inputRate) + (cached * inputRate * cacheDiscount) + (output * outputRate)
  return Math.max(0, cost)
}

const LANG_NAMES: Record<string, string> = {
  te: 'Telugu', ml: 'Malayalam', en: 'English', hi: 'Hindi',
  pa: 'Punjabi', ta: 'Tamil', kn: 'Kannada', gu: 'Gujarati',
  bn: 'Bengali', or: 'Odia', mr: 'Marathi', as: 'Assamese',
}

export function langName(code: string): string {
  return LANG_NAMES[code] || code.toUpperCase()
}
