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

function walkDir(dir) {
    let results = [];
    const list = fs.readdirSync(dir);
    list.forEach((file) => {
        file = path.join(dir, file);
        const stat = fs.statSync(file);
        if (stat && stat.isDirectory()) {
            results = results.concat(walkDir(file));
        } else {
            if (file.endsWith('.html') || file.endsWith('.css')) {
                results.push(file);
            }
        }
    });
    return results;
}

const files = walkDir(path.join(__dirname, 'site'));

files.forEach(file => {
    let content = fs.readFileSync(file, 'utf8');
    
    // Fix mojibake
    content = content.replace(/â€¦/g, '...');
    content = content.replace(/â†’/g, '&rarr;');
    content = content.replace(/â€"/g, '&mdash;');
    content = content.replace(/â€“/g, '&ndash;');
    content = content.replace(/â€¢/g, '&bull;');
    content = content.replace(/Â·/g, '&middot;');
    content = content.replace(/â€™/g, "'");
    content = content.replace(/â€˜/g, "'");
    content = content.replace(/â€œ/g, '"');
    content = content.replace(/â€/g, '"'); // careful with this one, might be a partial match, but good enough
    content = content.replace(/Â /g, ' ');

    fs.writeFileSync(file, content, 'utf8');
});
console.log('Fixed mojibake in HTML files.');
