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

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

/**
 * Fix ALL quote variations in Mermaid labels to use consistent double quotes.
 * 
 * Handles:
 * - ['Label']  → ["Label"]
 * - ["Label']  → ["Label"]
 * - ['Label"]  → ["Label"]
 * - ["Label"]  → ["Label"] (already correct)
 */
function fixMermaidQuotes(content: string): string {
    // Find all Mermaid blocks (between <Mermaid> and </Mermaid>)
    const mermaidBlockRegex = /(<Mermaid[^>]*>)([\s\S]*?)(<\/Mermaid>)/g;

    return content.replace(mermaidBlockRegex, (match, openTag, mermaidContent, closeTag) => {
        // Replace all variations: [' or [" at start, '] or "] at end
        // Match pattern: [ followed by ' or ", then content, then ' or ", then ]
        const fixed = mermaidContent.replace(/\[['"]([^'"]*)['"]\]/g, '["$1"]');

        return openTag + fixed + closeTag;
    });
}

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

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

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

    console.log(`\nTotal fixed: ${fixCount}`);
}

processFiles();
