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

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

/**
 * Convert all Mermaid children syntax back to graph prop,
 * BUT use a regular double-quoted string with escaped newlines instead of template literals.
 * 
 * MDXRemote RSC strips template literals!
 * 
 * Convert:
 *   <Mermaid id="..." title="..." showShare={true}>
 *   {`graph TD
 *      A --> B`}
 *   </Mermaid>
 * 
 * To:
 *   <Mermaid graph={"graph TD\n      A --> B"} id="..." title="..." showShare={true} />
 */
function convertToPlainStringProp(content: string): string {
    // Match <Mermaid ...>{\`...\`}</Mermaid>
    const mermaidChildrenRegex = /<Mermaid\s+([^>]*?)>\s*\{`([\s\S]*?)`\}\s*<\/Mermaid>/g;

    return content.replace(mermaidChildrenRegex, (match, propsStr, graphContent) => {
        // Escape double quotes in the graph content
        const escapedGraph = graphContent
            .replace(/\\/g, '\\\\')     // escape backslashes first
            .replace(/"/g, '\\"')       // escape double quotes
            .replace(/\n/g, '\\n');     // escape newlines

        // Clean up props string
        const cleanProps = propsStr.trim();

        return `<Mermaid graph={"${escapedGraph}"} ${cleanProps} />`;
    });
}

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 = convertToPlainStringProp(content);

        if (content !== fixed) {
            fs.writeFileSync(filePath, fixed);
            fixCount++;
            console.log(`✅ Converted to plain string: ${file}`);
        } else {
            console.log(`- ${file} (no Mermaid children found)`);
        }
    }

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

processFiles();
