const fs = require('fs');
const path = require('path');

const rootDir = 'd:\\gdfhbfgdbnbdfbdf\\typogenie\\src-tauri\\templates';

function walk(dir) {
    const files = fs.readdirSync(dir, { withFileTypes: true });
    files.forEach(dirent => {
        const fullPath = path.join(dir, dirent.name);
        if (dirent.isDirectory()) {
            walk(fullPath);
        } else if (dirent.name.endsWith('.json')) {
            let content = fs.readFileSync(fullPath, 'utf8');
            let changed = false;

            // Fix the literal \n characters from previous run
            if (content.includes('\\n')) {
                content = content.split('\\n').join('\n');
                changed = true;
            }

            // Comprehensive list of all possible keys
            const keys = [
                'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'blockquote', 'code', 'pre',
                'ul', 'ol', 'li', 'strong', 'em', 'a', 'table', 'th', 'td', 'hr', 'img',
                'del', 'sup', 'sub', 'mark', 'footnote', 'footnoteRef', 'page'
            ];

            keys.forEach(key => {
                const brokenSequenceRegex = new RegExp(`("border(?:Top|Bottom|Left|Right)":\\s*{[^}]*}\\s*),\\s*"(${key})":`, 'g');
                if (brokenSequenceRegex.test(content)) {
                    // Use actual newline characters here
                    content = content.replace(brokenSequenceRegex, `$1\n        },\n        "$2":`);
                    changed = true;
                }
            });

            if (changed) {
                fs.writeFileSync(fullPath, content, { encoding: 'utf8' });
                console.log(`Final Corrective Surgery: ${fullPath}`);
            }
        }
    });
}

walk(rootDir);
console.log('Finished final corrective surgery.');
