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

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

const betterTranslations = {
    navAgent: { zh: "智能体", en: "Agent", ja: "エージェント" },
    navNotebook: { zh: "笔记本", en: "Notebook", ja: "ノートブック" },
    navPlugin: { zh: "插件", en: "Plugins", ja: "プラグイン" },
    navTenants: { zh: "租户管理", en: "Tenants", ja: "テナント管理" },
    noNotesFound: { zh: "未找到笔记", en: "No notes found", ja: "ノートが見つかりません" },
    notebookDesc: { zh: "笔记本功能可以帮助您整理和归纳知识。", en: "Notebooks help you organize and summarize knowledge.", ja: "ノートブックは知識の整理と要約に役立ちます。" },
    personalNotebook: { zh: "个人笔记本", en: "Personal Notebook", ja: "個人用ノートブック" },
    pluginBy: { zh: "作者", en: "By", ja: "作者" },
    pluginCommunity: { zh: "社区插件", en: "Community Plugins", ja: "コミュニティプラグイン" },
    pluginConfig: { zh: "插件配置", en: "Plugin Config", ja: "プラグイン設定" },
    pluginDesc: { zh: "扩展系统功能。", en: "Extend system capabilities.", ja: "システム機能を拡張します。" },
    pluginOfficial: { zh: "官方插件", en: "Official Plugins", ja: "公式プラグイン" },
    pluginTitle: { zh: "插件", en: "Plugins", ja: "プラグイン" },
    searchAgent: { zh: "搜索智能体", en: "Search Agents", ja: "エージェントを検索" },
    searchPlugin: { zh: "搜索插件", en: "Search Plugins", ja: "プラグインを検索" },
    statusRunning: { zh: "运行中", en: "Running", ja: "実行中" },
    statusStopped: { zh: "已停止", en: "Stopped", ja: "停止中" },
    success: { zh: "成功", en: "Success", ja: "成功" },
    updatedAtPrefix: { zh: "最后更新于", en: "Last updated at", ja: "最終更新日:" },
    visualVision: { zh: "视觉分析", en: "Visual Analysis", ja: "視覚分析" },
    warning: { zh: "警告", en: "Warning", ja: "警告" },
    "x-api-key": { zh: "API 密钥", en: "API Key", ja: "APIキー" },
    "x-tenant-id": { zh: "租户 ID", en: "Tenant ID", ja: "テナントID" },
    "x-user-language": { zh: "用户语言", en: "User Language", ja: "ユーザー言語" },
    unknown: { zh: "未知", en: "Unknown", ja: "不明" }
};

let content = fs.readFileSync(translationsPath, 'utf8');

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

// Simple parser to extract blocks
const langBlocks = content.split(/(\w+): \{/);
let header = langBlocks[0];
let newContent = header;

for (let i = 1; i < langBlocks.length; i += 2) {
    const lang = langBlocks[i];
    let block = langBlocks[i + 1];

    // Find the end of this block
    let endIdx = block.lastIndexOf('},');
    if (endIdx === -1) endIdx = block.lastIndexOf('}'); // last block

    let footer = block.substring(endIdx);
    let itemsStr = block.substring(0, endIdx);

    let items = itemsStr.split('\n');
    let seenKeys = new Set();
    let resultItems = [];

    for (let line of items) {
        let match = line.match(/^(\s+)(['"]?[a-zA-Z0-9_-]+['"]?):(.*)/);
        if (match) {
            let indent = match[1];
            let keyStr = match[2];
            let rest = match[3];

            let actualKey = keyStr.replace(/['"]/g, '');
            if (seenKeys.has(actualKey)) continue;
            seenKeys.add(actualKey);

            let val = rest.trim().replace(/,$/, '');
            // If it's a placeholder (same as key) or empty, use better translation if available
            if ((val === `"${actualKey}"` || val === `'${actualKey}'`) && betterTranslations[actualKey]) {
                val = JSON.stringify(betterTranslations[actualKey][lang] || betterTranslations[actualKey].en || actualKey);
            }

            const quotedKey = isValidIdentifier(actualKey) ? actualKey : `"${actualKey}"`;
            resultItems.push(`${indent}${quotedKey}: ${val},`);
        } else if (line.trim().startsWith('//') || line.trim() === '') {
            resultItems.push(line);
        }
    }

    newContent += `${lang}: {` + resultItems.join('\n') + footer;
}

fs.writeFileSync(translationsPath, newContent, 'utf8');
console.log('Final cleanup and translation improvement complete!');
