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

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

/**
 * Convert graph={"..."} to graph="..." (plain string prop without JSX expression wrapper).
 * MDXRemote RSC strips JSX expression props but keeps plain string props.
 * 
 * But we also need the escape sequences to go through.
 * The plain string prop `graph="graph TD\nA-->B"` will have the \n treated as
 * literal characters by MDX's parser, not as a newline. The Mermaid component
 * then unescapes them.
 */
function convertToPlainStringProps(content: string): string {
    // Match graph={" ... "} and convert to graph="..."
    // The content inside should already have escaped newlines and quotes
    const pattern = /graph=\{"((?:[^"\\]|\\.)*)"\}/g;

    return content.replace(pattern, (match, graphContent) => {
        return `graph="${graphContent}"`;
    });
}

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

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

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

processFiles();
