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

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

/**
 * Fix escaped double quotes in Mermaid graph props.
 * 
 * The graph prop contains \" which is invalid in MDX attribute syntax.
 * Replace \" with ' (single quote) - Mermaid supports both.
 * 
 * Also fix \\n to just \n (single backslash) - the MDX parser 
 * will treat \n as literal characters, and the Mermaid component
 * will unescape them.
 */
function fixGraphQuotes(content: string): string {
    // Match graph="..." prop (the entire value including escaped content)
    // This is tricky because the value can contain escaped quotes
    // We need to match from graph=" to the closing " that ends the prop value

    // Strategy: Find graph=" then scan forward, tracking escape sequences
    const graphPropStart = 'graph="';
    let result = '';
    let i = 0;

    while (i < content.length) {
        const idx = content.indexOf(graphPropStart, i);
        if (idx === -1) {
            result += content.slice(i);
            break;
        }

        // Copy everything up to and including graph="
        result += content.slice(i, idx + graphPropStart.length);

        // Now scan the value, replacing \" with '
        let j = idx + graphPropStart.length;
        let graphValue = '';

        while (j < content.length) {
            if (content[j] === '\\' && content[j + 1] === '"') {
                // Replace \" with '
                graphValue += "'";
                j += 2;
            } else if (content[j] === '\\' && content[j + 1] === '\\') {
                // Keep \\ as is
                graphValue += '\\\\';
                j += 2;
            } else if (content[j] === '"') {
                // End of attribute value
                break;
            } else {
                graphValue += content[j];
                j++;
            }
        }

        result += graphValue;
        i = j; // Continue from the closing quote (will be added in next iteration)
    }

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

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

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

processFiles();
