import { unified, type Processor } from "unified";
import type { Root } from 'hast';
import RemarkParse from "remark-parse";

import RemarkRehype from 'remark-rehype';
import RemarkOfm from 'remark-ofm';
import RemarkGfm from 'remark-gfm';
import RemarkBreaks from 'remark-breaks';
import RemarkFrontmatter from 'remark-frontmatter';

interface Parser
{
    parse: (md: string) => Promise<Root>;
    parseSync: (md: string) => Root
}
export default function useMarkdown(): Parser
{
    let processor: Processor, processorSync: Processor;

    const parse = (markdown: string) => {
        if (!processor) 
        {
            processor = unified().use([RemarkParse, RemarkGfm, RemarkOfm, RemarkBreaks, RemarkFrontmatter]);
            processor.use(RemarkRehype);
        }

        const processed = processor.run(processor.parse(markdown)) as Promise<Root>;
        return processed;
    }

    const parseSync = (markdown: string) => {
        if (!processor) 
        {
            processor = unified().use([RemarkParse, RemarkGfm, RemarkOfm, RemarkBreaks, RemarkFrontmatter]);
            processor.use(RemarkRehype);
        }

        const processed = processor.runSync(processor.parse(markdown)) as Root;
        return processed;
    }

    return { parse, parseSync };
}