import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]): string {
  return twMerge(clsx(inputs))
}

/**
 * Get Monaco editor language identifier from file path
 */
export function getMonacoLanguage(filePath: string): string {
  const ext = filePath.split(".").pop()?.toLowerCase() || ""
  const languageMap: Record<string, string> = {
    py: "python",
    js: "javascript",
    jsx: "javascript",
    ts: "typescript",
    tsx: "typescript",
    java: "java",
    html: "html",
    css: "css",
  }
  return languageMap[ext] || "python"
}

/**
 * Round optimization attempts to nearest 0.5 by dividing by 100 and rounding to half increments
 * (e.g., 4000 -> 40, 450 -> 4.5, 550 -> 5.5)
 */
export function roundCredits(credits: number): number {
  const value = credits / 100
  return Math.round(value * 2) / 2
}

/**
 * Format optimization attempts for display (rounds to 0.5 increments and formats with commas)
 */
export function formatCredits(credits: number): string {
  const rounded = roundCredits(credits)
  // Format with up to 1 decimal place (for 0.5 increments)
  return new Intl.NumberFormat("en-US", {
    minimumFractionDigits: rounded % 1 === 0 ? 0 : 1,
    maximumFractionDigits: 1,
  }).format(rounded)
}

/**
 * Calculate usage percentage based on rounded optimization attempts
 * Ensures percentage is calculated correctly after rounding to 0.5 increments
 */
export function calculateCreditsPercentage(used: number, limit: number): number {
  if (limit === 0) return 0
  const roundedUsed = roundCredits(used)
  const roundedLimit = roundCredits(limit)
  if (roundedLimit === 0) return 0
  return Math.min(100, Math.round((roundedUsed / roundedLimit) * 100))
}

/**
 * Get progress bar className based on percentage
 */
export function getProgressBarClassName(percentage: number): string {
  if (percentage < 80) {
    return "[&>div]:bg-gradient-to-r [&>div]:from-emerald-500 [&>div]:to-primary"
  }
  if (percentage < 95) {
    return "[&>div]:bg-primary"
  }
  return "[&>div]:bg-gradient-to-r [&>div]:from-orange-500 [&>div]:to-red-500"
}
