import fs from 'fs';
import path from 'path';

const LANGS = ['de', 'fr', 'it', 'es', 'pt', 'hi', 'bn', 'id', 'zh', 'ja'];

function escapeString(str) {
  return str
    .replace(/\\/g, '\\\\')
    .replace(/"/g, '\\"')
    .replace(/\n/g, '\\n')
    .replace(/\r/g, '\\r')
    .replace(/\t/g, '\\t');
}

function unescapeString(str) {
  return str.replace(/\\"/g, '"').replace(/\\n/g, '\n').replace(/\\\\/g, '\\');
}

function parseEntries(content) {
  const regex = /(['"])([^'"]+)\1:\s*\{\s*ru:\s*(['"])((?:\\.|(?!\3)[^\\])*)\3\s*,\s*en:\s*(['"])((?:\\.|(?!\5)[^\\])*)\5\s*(?:,\s*)?\}\s*,/g;
  const entries = [];
  let m;
  while ((m = regex.exec(content)) !== null) {
    entries.push({
      key: m[2],
      quote: m[1],
      ru: unescapeString(m[4]),
      en: unescapeString(m[6]),
      ruQuote: m[3],
      enQuote: m[5],
      start: m.index,
      end: m.index + m[0].length,
    });
  }
  return entries;
}

function formatEntry(key, quote, ru, en, extra) {
  const lines = [
    `${quote}${key}${quote}: {`,
    `        ru: "${escapeString(ru)}",`,
    `        en: "${escapeString(en)}",`,
  ];
  for (const lang of LANGS) {
    lines.push(`        ${lang}: "${escapeString(extra[lang])}",`);
  }
  lines.push('    },');
  return lines.join('\n');
}

function updateTypes(content) {
  content = content.replace(
    "export type LangType = 'ru' | 'en';",
    "export type LangType = 'ru' | 'en' | 'de' | 'fr' | 'it' | 'es' | 'pt' | 'hi' | 'bn' | 'id' | 'zh' | 'ja';"
  );
  content = content.replace(
    /export type LocalItemType = \{\s*ru: string;\s*en: string;\s*\}/,
    `export type LocalItemType = {\n    ru: string;\n    en: string;\n    de: string;\n    fr: string;\n    it: string;\n    es: string;\n    pt: string;\n    hi: string;\n    bn: string;\n    id: string;\n    zh: string;\n    ja: string;\n}`
  );
  return content;
}

function applyTranslations(filePath, cache) {
  let content = fs.readFileSync(filePath, 'utf8');
  const entries = parseEntries(content);
  for (let i = entries.length - 1; i >= 0; i--) {
    const entry = entries[i];
    const extra = {};
    for (const lang of LANGS) {
      extra[lang] = cache[`${lang}::${entry.en}`] ?? entry.en;
    }
    const replacement = formatEntry(entry.key, entry.quote, entry.ru, entry.en, extra);
    content = content.slice(0, entry.start) + replacement + content.slice(entry.end);
  }
  if (filePath.endsWith('local.ts')) {
    content = updateTypes(content);
  } else if (filePath.endsWith('vizRfmLocal.ts')) {
    content = content.replace(
      /type VizRfmLocalItem = \{\s*ru: string;\s*en: string;\s*\};/,
      `type VizRfmLocalItem = {\n    ru: string;\n    en: string;\n    de: string;\n    fr: string;\n    it: string;\n    es: string;\n    pt: string;\n    hi: string;\n    bn: string;\n    id: string;\n    zh: string;\n    ja: string;\n};`
    );
  }
  fs.writeFileSync(filePath, content);
  console.log(`Updated ${filePath} (${entries.length} entries)`);
}

const cache = JSON.parse(fs.readFileSync('scripts/translation-cache.json', 'utf8'));
applyTranslations(path.resolve('src/lang/local.ts'), cache);
applyTranslations(path.resolve('src/lang/vizRfmLocal.ts'), cache);
