import { createHighlighter } from 'shiki';
let highlighterPromise = null;
const THEMES = ['github-dark', 'github-light', 'dracula', 'nord', 'one-dark-pro', 'vitesse-dark'];
const LANGUAGES = [
    'javascript', 'typescript', 'python', 'rust', 'go', 'java', 'cpp', 'c',
    'csharp', 'php', 'ruby', 'swift', 'kotlin', 'html', 'css', 'scss',
    'json', 'yaml', 'markdown', 'sql', 'bash', 'shell', 'dockerfile', 'svelte', 'vue', 'jsx', 'tsx'
];
export async function getHighlighter() {
    if (!highlighterPromise) {
        highlighterPromise = createHighlighter({ themes: THEMES, langs: LANGUAGES });
    }
    return highlighterPromise;
}
export async function highlightCode(code, language, theme = 'github-dark', options = {}) {
    try {
        const highlighter = await getHighlighter();
        const loadedLangs = highlighter.getLoadedLanguages();
        if (!loadedLangs.includes(language)) {
            language = 'javascript';
        }
        const html = highlighter.codeToHtml(code, { lang: language, theme });
        if (options.showLineNumbers)
            return addLineNumbers(html);
        return html;
    }
    catch (e) {
        console.error('Highlighting error:', e);
        return `<pre><code>${escapeHtml(code)}</code></pre>`;
    }
}
function addLineNumbers(html) {
    const codeMatch = html.match(/<code[^>]*>([\s\S]*)<\/code>/);
    if (!codeMatch)
        return html;
    const codeContent = codeMatch[1];
    const codeLines = codeContent.split('\n');
    const numberedLines = codeLines.map((line, i) => {
        return `<span class="line-number">${i + 1}</span>${line}`;
    }).join('\n');
    return html.replace(codeMatch[1], numberedLines);
}
function escapeHtml(str) {
    return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
}
