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

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

/**
 * STRICTLY fixes Mermaid node labels.
 * 
 * Goal:
 * 1. Find all content inside [...] in Mermaid blocks.
 * 2. Strip ALL outer quotes (single or double).
 * 3. Sanitize the inner text:
 *    - Remove/Replace internal double quotes
 *    - Remove/Replace internal single quotes (to avoid any ambiguity)
 * 4. Wrap strictly in ["..."].
 */
function fixMermaidLabels(content: string): string {
    // Find Mermaid blocks
    return content.replace(/(<Mermaid[^>]*>)([\s\S]*?)(<\/Mermaid>)/g, (match, open, body, close) => {

        // Process the body line by line to be safe, or just regex the labels.
        // Regex for labels: \[ followed by anything until \]
        // Note: We assume labels don't contain nested brackets for now (Mermaid usually doesn't).
        const fixedBody = body.replace(/\[([^\]]+)\]/g, (labelMatch, innerContent) => {
            let text = innerContent.trim();

            // Check if it looks like a quoted label
            const hasOuterQuotes = /^['"]|['"]$/.test(text);
            if (hasOuterQuotes) {
                // Remove ALL starting/ending quotes (handling multiple if messed up)
                text = text.replace(/^['"]+|['"]+$/g, '');
            }

            // Sanitize internal text
            // Replace " with ' to avoid breaking the outer double quotes
            text = text.replace(/"/g, "'");

            // Verify parsing safety: 
            // Replace ' with space or nothing if we want to be super safe, 
            // but "Text with 'quotes'" SHOULD be valid in Mermaid.
            // However, the previous error might have been due to MDX interference.
            // Let's keep single quotes inside, but ensure outer are double.

            // WAIT: The specific error was `B['Server ... 'inner' ...']`.
            // If we convert to `B["Server ... 'inner' ..."]`, it should work.

            return `["${text}"]`;
        });

        return open + fixedBody + close;
    });
}

const files = fs.readdirSync(MDX_DIR).filter(f => f.endsWith('.mdx'));
let fixedCount = 0;

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

    if (content !== fixed) {
        fs.writeFileSync(filePath, fixed);
        console.log(`✅ Fixed labels in: ${file}`);
        fixedCount++;
    }
}

console.log(`\nFixed ${fixedCount} files.`);
