import { createHighlighter, type Highlighter } from "shiki";

export type HighlightLang = "json" | "bash" | "typescript" | "http" | "html";

let highlighterPromise: Promise<Highlighter> | null = null;

function getHighlighter(): Promise<Highlighter> {
  if (!highlighterPromise) {
    highlighterPromise = createHighlighter({
      themes: ["github-light"],
      langs: ["json", "bash", "typescript", "http", "html"],
    });
  }

  return highlighterPromise;
}

export async function highlightCode(code: string, lang: HighlightLang = "json"): Promise<string> {
  const highlighter = await getHighlighter();

  return highlighter.codeToHtml(code.trimEnd(), {
    lang,
    theme: "github-light",
  });
}
