import { codeToHtml } from '@pierre/highlights';
import type { Lang, Theme, ThemeSyntaxSettings } from '@pierre/highlights';
import { monoDark, monoLight } from './theme';
import { raw } from './raw';

export type Options = {
    file: string;
    lang?: Lang | (string & {});
    themes?: {
        light?: Theme;
        dark?: Theme;
    };
};

export function html({ file, lang, themes }: Options) {
    const text = raw(file);

    const bytes = codeToHtml(text, {
        lang: lang || 'tsx',
        themes: {
            light: themes?.light || monoLight,
            dark: themes?.dark || monoDark,
        },
        defaultColor: 'light-dark()',
    });

    let output = new TextDecoder().decode(bytes);

    if (lang === 'markdown' || lang === 'md') {
        const lightColor = (themes?.light?.style?.syntax?.punctuation as ThemeSyntaxSettings)?.color || '#aaaaaa';
        const darkColor = (themes?.dark?.style?.syntax?.punctuation as ThemeSyntaxSettings)?.color || '#666666';
        const style = `color:light-dark(${lightColor}, ${darkColor})`;

        // style table header bottom border hyphens/colons between edge pipes
        output = output.replace(
            /(<span[^>]*>\|<\/span>)(\s*:?-{2,}:?\s*)(?=<span[^>]*>\|<\/span>)/g,
            `$1<span style="${style}">$2</span>`,
        );

        // style divider lines (---, -----, ──────, ***, ___, ===)
        // match lines between > or newline and < or newline that only contain rule characters
        output = output.replace(
            /(^|>|\n)([ \t]*[-*_=\u2500-\u257F\u2013\u2014]{3,}[ \t]*)(?=$|<|\r?\n)/g,
            `$1<span style="${style}">$2</span>`,
        );
    }

    return (
        output
            // External links
            .replace(/(https?:\/\/[^\s<"')]+)/g, '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>')
            // Internal routes
            .replace(/(['"])((?:<[^>]+>)*)(\/[a-zA-Z0-9/_.-]*)((?:<[^>]+>)*)\1/g, '$1$2<a href="$3">$3</a>$4$1')
    );
}