import fs from 'fs';
import path from 'path';
import { translate } from '@vitalets/google-translate-api';

const LANGS = ['de', 'fr', 'it', 'es', 'pt', 'hi', 'bn', 'id', 'zh', 'ja'];
const CACHE_PATH = path.resolve('scripts/translation-cache.json');
const DELAY_MS = 1200;

function sleep(ms) {
  return new Promise((r) => setTimeout(r, ms));
}

async function translateText(text, lang) {
  if (!text.trim()) return text;
  for (let attempt = 0; attempt < 10; attempt++) {
    try {
      const result = await translate(text, { from: 'en', to: lang });
      return result.text;
    } catch (err) {
      const wait = 3000 * Math.pow(1.5, attempt);
      console.warn(`  retry ${attempt + 1}/10 ${lang}: ${err.message?.slice(0, 80)}`);
      await sleep(wait);
    }
  }
  return null;
}

async function main() {
  const enStrings = JSON.parse(fs.readFileSync('scripts/en-strings.json', 'utf8'));
  const cache = fs.existsSync(CACHE_PATH)
    ? JSON.parse(fs.readFileSync(CACHE_PATH, 'utf8'))
    : {};

  const total = enStrings.length * LANGS.length;
  let done = 0;
  let newCount = 0;

  for (const en of enStrings) {
    for (const lang of LANGS) {
      done++;
      const key = `${lang}::${en}`;
      if (cache[key]) continue;
      newCount++;
      process.stdout.write(`\r[${done}/${total}] new:${newCount} ${lang}: ${en.slice(0, 50)}...`);
      const result = await translateText(en, lang);
      cache[key] = result ?? en;
      if (newCount % 3 === 0) {
        fs.writeFileSync(CACHE_PATH, JSON.stringify(cache, null, 2));
      }
      await sleep(DELAY_MS);
    }
  }

  fs.writeFileSync(CACHE_PATH, JSON.stringify(cache, null, 2));
  console.log(`\nFinished. New translations: ${newCount}`);
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
