const fs = require('fs');

const files = require('./files_to_translate.json');
const translationMap = require('./translation_map.json');

let totalReplaced = 0;

files.forEach(file => {
    let content = fs.readFileSync(file, 'utf8');
    let originalContent = content;

    // Replace simple strings
    const simpleStringRegex = /((?:console|logger|Logger|this\.logger)\.(?:log|error|warn|info|debug|verbose)\(\s*)(['"])(.*?[\u4e00-\u9fa5]+.*?)\2/g;
    content = content.replace(simpleStringRegex, (match, prefix, quote, innerString) => {
        if (translationMap[innerString]) {
            totalReplaced++;
            return prefix + quote + translationMap[innerString] + quote;
        }
        return match;
    });

    // Replace template literals
    const templateRegex = /((?:console|logger|Logger|this\.logger)\.(?:log|error|warn|info|debug|verbose)\(\s*)\`([\s\S]*?)\`/g;
    content = content.replace(templateRegex, (match, prefix, innerString) => {
        if (/[\\u4e00-\\u9fa5]/.test(innerString) && translationMap[innerString]) {
            totalReplaced++;
            return prefix + '`' + translationMap[innerString] + '`';
        }
        // If no direct match, check if there's an exact match in the map
        if (translationMap[innerString]) {
            totalReplaced++;
            return prefix + '`' + translationMap[innerString] + '`';
        }
        return match;
    });

    if (content !== originalContent) {
        fs.writeFileSync(file, content, 'utf8');
        console.log('Updated ' + file);
    }
});

console.log('Total replacements made: ' + totalReplaced);
