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

const translationsPath = path.join('d:', 'workspace', 'AuraK', 'web', 'utils', 'translations.ts');
const usedKeysPath = path.join('d:', 'workspace', 'AuraK', 'all_used_keys.txt');

const usedKeys = fs.readFileSync(usedKeysPath, 'utf8').split('\n').filter(Boolean);
const translationsContent = fs.readFileSync(translationsPath, 'utf8');

const lines = translationsContent.split('\n');
let currentLang = null;
let resultLines = [];
let keysSeen = new Set();

const langStartRegex = /^\s+(\w+): \{/;
const keyRegex = /^(\s+)([a-zA-Z0-9_-]+):(.*)/;

function isValidIdentifier(id) {
    return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(id);
}

for (let i = 0; i < lines.length; i++) {
    const line = lines[i];

    const langMatch = line.match(langStartRegex);
    if (langMatch) {
        if (currentLang) {
            addMissingUsedKeys(currentLang, resultLines, keysSeen);
        }
        currentLang = langMatch[1];
        keysSeen = new Set();
        resultLines.push(line);
        continue;
    }

    if (currentLang) {
        const keyMatch = line.match(keyRegex);
        if (keyMatch) {
            const indent = keyMatch[1];
            let key = keyMatch[2];
            const rest = keyMatch[3];

            // Note: keyMatch[2] might already be quoted if it was fixed in a previous run
            const actualKey = (key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))
                ? key.slice(1, -1)
                : key;

            keysSeen.add(actualKey);

            if (!isValidIdentifier(actualKey)) {
                resultLines.push(`${indent}"${actualKey}":${rest}`);
                continue;
            }
        }

        if (line.trim() === '},' || (line.trim() === '}' && i > lines.length - 5)) {
            addMissingUsedKeys(currentLang, resultLines, keysSeen);
            currentLang = null;
            resultLines.push(line);
            continue;
        }
    }

    resultLines.push(line);
}

function addMissingUsedKeys(lang, targetLines, seen) {
    for (const key of usedKeys) {
        if (!seen.has(key)) {
            const val = key;
            const quotedKey = isValidIdentifier(key) ? key : `"${key}"`;
            targetLines.push(`    ${quotedKey}: ${JSON.stringify(val)},`);
            seen.add(key);
        }
    }
}

fs.writeFileSync(translationsPath, resultLines.join('\n'), 'utf8');
console.log('Final sync (with proper identifier quoting) complete!');
