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;

            // 1. Fix orphaned sides: "bottom": { ... } -> "borderBottom": { ... }
            // Only if it looks like a border object (color, width, style)
            const sides = ['top', 'bottom', 'left', 'right'];
            sides.forEach(side => {
                const capitalizedSide = side.charAt(0).toUpperCase() + side.slice(1);
                // Look for "side": { ... } that isn't already "borderSide"
                // and has border-like properties
                const orphanRegex = new RegExp(`(?<!"border)${side}":\\s*{([^}]*"color"[^}]*)}`, 'g');
                if (orphanRegex.test(content)) {
                    content = content.replace(orphanRegex, `"border${capitalizedSide}": {${'$1'}}`);
                    changed = true;
                }
            });

            // 2. Fix trailing braces: "borderSide": { ... } } -> "borderSide": { ... }
            // We repeat this several times to catch cases where multiple borders were nested
            let braceChanged = true;
            while (braceChanged) {
                braceChanged = false;
                const trailingBraceRegex = /("border(?:Top|Bottom|Left|Right)":\s*{[^}]*})\s*}/g;
                if (trailingBraceRegex.test(content)) {
                    content = content.replace(trailingBraceRegex, '$1');
                    braceChanged = true;
                    changed = true;
                }
            }

            if (changed) {
                // Try to validate
                try {
                    JSON.parse(content);
                } catch (e) {
                    // If still broken, let's try a last ditch effort to remove any double closing braces in elements
                    // that follow a border side and a comma or newline
                    content = content.replace(/("border(?:Top|Bottom|Left|Right)":\s*{[^}]*})\s*},\s*}/g, '$1\n        },');
                    try { JSON.parse(content); } catch (e2) { }
                }
                fs.writeFileSync(fullPath, content, { encoding: 'utf8' });
                console.log(`Deep Cleaned: ${fullPath}`);
            }
        }
    });
}

walk(rootDir);
console.log('Finished deep template cleanup.');
