import type { BundledLanguage, BundledTheme, HighlighterGeneric } from 'shiki';
import { createHighlighter } from 'shiki';

const THEME = 'github-dark-default' as const;

let instance: Promise<HighlighterGeneric<BundledLanguage, BundledTheme>> | null = null;

function getHighlighter() {
  if (!instance) {
    instance = createHighlighter({ themes: [THEME], langs: [] });
  }
  return instance;
}

export async function highlight(code: string, lang: string): Promise<string | null> {
  try {
    const highlighter = await getHighlighter();
    if (lang && !highlighter.getLoadedLanguages().includes(lang)) {
      await highlighter.loadLanguage(lang as BundledLanguage);
    }
    return highlighter.codeToHtml(code, { lang: lang || 'text', theme: THEME });
  } catch {
    return null;
  }
}
