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

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

function cleanMermaidFormatting(content: string): string {
    // Fix: The repair script reformatted <Mermaid> tags badly with extra blank lines
    // Pattern: <Mermaid\n    \n    graph={`...`}\n    \n  />
    // Should be: <Mermaid\n    graph={`...`}\n    id="..."\n    .../>

    // Remove empty lines between <Mermaid and graph=
    let result = content.replace(/<Mermaid\s*\n\s*\n\s*graph=/g, '<Mermaid\n    graph=');

    // Remove trailing empty space before />
    result = result.replace(/`\}\s*\n\s*\n\s*\/>/g, '`}\n    />');

    // Fix: Remove trailing whitespace-only lines before id= or title= or showShare=
    result = result.replace(/`\}\s*\n\s*\n\s*(id=)/g, '`}\n    $1');
    result = result.replace(/`\}\s*\n\s*\n\s*(title=)/g, '`}\n    $1');
    result = result.replace(/`\}\s*\n\s*\n\s*(showShare=)/g, '`}\n    $1');

    return result;
}

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

        if (content !== cleaned) {
            fs.writeFileSync(filePath, cleaned);
            fixCount++;
            console.log(`✅ Cleaned formatting in ${file}`);
        } else {
            console.log(`- ${file} OK`);
        }
    }

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

processFiles();
