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

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

/**
 * Convert ugly single-line graph="..." props to clean multi-line children.
 * 
 * FROM:
 *   <Mermaid graph="graph TD\n  A-->B\n  B-->C" id="..." title="..." />
 * 
 * TO:
 *   <Mermaid id="..." title="...">
 *   graph TD
 *     A-->B
 *     B-->C
 *   </Mermaid>
 */
function convertToChildren(content: string): string {
    // Match <Mermaid graph="..." ... />
    const mermaidRegex = /<Mermaid\s+graph="([^"]*)"([^>]*?)\/>/g;

    return content.replace(mermaidRegex, (match, graphValue, otherProps) => {
        // Unescape \n to real newlines
        const cleanGraph = graphValue.replace(/\\n/g, '\n');

        // Clean up other props
        const cleanProps = otherProps.trim();

        // Build the new format with children
        return `<Mermaid${cleanProps ? ' ' + cleanProps : ''}>\n${cleanGraph}\n</Mermaid>`;
    });
}

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

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

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

processFiles();
