import Prism from "prismjs";

const EXTENSION_MAP: Record<string, string> = {
  js: "javascript",
  jsx: "jsx",
  ts: "typescript",
  tsx: "tsx",
  py: "python",
  md: "markdown",
  markdown: "markdown",
  json: "json",
  yaml: "yaml",
  yml: "yaml",
  html: "html",
  htm: "html",
  xml: "xml",
  css: "css",
  scss: "scss",
  sass: "sass",
  less: "less",
  sh: "bash",
  bash: "bash",
  zsh: "bash",
  dockerfile: "dockerfile",
  sql: "sql",
  rs: "rust",
  go: "go",
  rb: "ruby",
  php: "php",
  java: "java",
  kt: "kotlin",
  scala: "scala",
  c: "c",
  cpp: "cpp",
  cc: "cpp",
  cxx: "cpp",
  h: "c",
  hpp: "cpp",
  cs: "csharp",
  swift: "swift",
  dart: "dart",
  lua: "lua",
  r: "r",
  matlab: "matlab",
  perl: "perl",
  clj: "clojure",
  cljs: "clojure",
  edn: "clojure",
  groovy: "groovy",
  tf: "hcl",
  hcl: "hcl",
  vue: "vue",
  svelte: "svelte",
  graphql: "graphql",
  gql: "graphql",
  toml: "toml",
  ini: "ini",
  cfg: "ini",
  conf: "ini",
  env: "bash",
  gitignore: "gitignore",
  gitattributes: "gitattributes",
  diff: "diff",
  patch: "diff",
  log: "log",
  txt: "plaintext",
};

export const detectLanguage = (filename: string): string => {
  const ext = filename.split(".").pop()?.toLowerCase() || "";
  return EXTENSION_MAP[ext] || "plaintext";
};

export const highlightCode = (code: string, language: string): string => {
  const grammar = Prism.languages[language] || Prism.languages.plaintext;
  return Prism.highlight(code, grammar, language);
};

export const loadLanguage = async (language: string): Promise<void> => {
  if (language === "plaintext" || Prism.languages[language]) {
    return;
  }

  // Dynamic import for language support
  try {
    await import(`prismjs/components/prism-${language}`);
  } catch {
    // Language not available, use plaintext
  }
};
