import * as fs from 'fs';
import * as path from 'path';

const MDX_DIR = path.join(process.cwd(), 'content/blog');

/**
 * Fix apostrophes in Mermaid labels by removing them.
 * 
 * Mermaid parser treats ' as a quote delimiter even inside ["..."].
 * Replace ' with nothing or use HTML entity &#39; (but simpler to just remove).
 */
function fixMermaidApostrophes(content: string): string {
    // Find all Mermaid blocks
    const mermaidBlockRegex = /(<Mermaid[^>]*>)([\s\S]*?)(<\/Mermaid>)/g;

    return content.replace(mermaidBlockRegex, (match, openTag, mermaidContent, closeTag) => {
        // Within Mermaid content, find all ["..."] labels and remove apostrophes
        const fixed = mermaidContent.replace(/\["([^"]*)"\]/g, (m: string, label: string) => {
            // Remove all apostrophes from the label
            const cleanLabel = label.replace(/'/g, '');
            return `["${cleanLabel}"]`;
        });

        return openTag + fixed + closeTag;
    });
}

function processFiles() {
    const files = fs.readdirSync(MDX_DIR).filter(f => f.endsWith('.mdx'));
    let fixCount = 0;
    let totalApostrophes = 0;

    for (const file of files) {
        const filePath = path.join(MDX_DIR, file);
        const content = fs.readFileSync(filePath, 'utf8');

        // Count apostrophes in Mermaid blocks before fixing
        const mermaidBlocks = content.match(/<Mermaid[^>]*>[\s\S]*?<\/Mermaid>/g) || [];
        for (const block of mermaidBlocks) {
            const apostrophes = (block.match(/\["[^"]*'[^"]*"\]/g) || []).length;
            if (apostrophes > 0) {
                totalApostrophes += apostrophes;
            }
        }

        const fixed = fixMermaidApostrophes(content);

        if (content !== fixed) {
            fs.writeFileSync(filePath, fixed);
            fixCount++;
            console.log(`✅ Fixed apostrophes: ${file}`);
        } else {
            console.log(`- ${file} (no apostrophes found)`);
        }
    }

    console.log(`\nTotal files fixed: ${fixCount}`);
    console.log(`Total apostrophes removed: ${totalApostrophes}`);
}

processFiles();
