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

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

/**
 * FINAL ATTEMPT: Standardize EVERYTHING in Mermaid blocks to double quotes.
 * 
 * 1. Find all text inside <Mermaid>...</Mermaid>.
 * 2. Replace any ['Label'] or ['Label's'] or ["Label"] patterns.
 * 3. Enforce ["Label"] for all labels.
 * 4. Remove any internal single quotes that break parsing.
 */
function finalMermaidFix(content: string): string {
    const mermaidRegex = /(<Mermaid[^>]*>)([\s\S]*?)(<\/Mermaid>)/g;

    return content.replace(mermaidRegex, (match, open, body, close) => {
        let fixedBody = body;

        // Convert common label syntax to clean double quotes
        // Match: [followed by optional space and any quote, capture content, end with optional quote and space]
        fixedBody = fixedBody.replace(/\[\s*['"]?([^\]'"]+?)['"]?\s*\]/g, (m, label) => {
            // Clean the label: remove any internal quotes that could cause issues
            const cleanLabel = label.replace(/['"]/g, "").trim();
            return `["${cleanLabel}"]`;
        });

        // Also handle Pie charts which use 'Label' : value
        fixedBody = fixedBody.replace(/^\s*'([^']+)'\s*:/gm, (m, label) => {
            const cleanLabel = label.replace(/['"]/g, "").trim();
            return `    "${cleanLabel}" :`;
        });

        return open + fixedBody + close;
    });
}

const files = fs.readdirSync(MDX_DIR).filter(f => f.endsWith('.mdx'));
for (const file of files) {
    const fp = path.join(MDX_DIR, file);
    const content = fs.readFileSync(fp, 'utf8');
    const fixed = finalMermaidFix(content);
    if (content !== fixed) {
        fs.writeFileSync(fp, fixed);
        console.log(`✅ Fixed potentially problematic syntax in: ${file}`);
    }
}
