const fs = require('fs');
const translate = require('google-translate-api-x');

const INPUT_FILE = 'son_fixed.json';
const OUTPUT_FILE = 'son_fixed.json'; // Overwriting based on workflow

async function main() {
  try {
    const data = JSON.parse(fs.readFileSync(INPUT_FILE, 'utf8'));
    let itemsToTranslate = data.filter(
      (item) =>
        item.mean === '' || item.mean === null || item.mean === undefined
    );

    console.log(`Total items: ${data.length}`);
    console.log(`Items to translate: ${itemsToTranslate.length}`);

    if (itemsToTranslate.length === 0) {
      console.log('Nothing to translate.');
      return;
    }

    let count = 0;
    // Process in chunks to avoid overwhelming or losing all progress
    for (const item of itemsToTranslate) {
      if (!item.phrase) continue;

      try {
        // Google Translate API X usually returns an object with 'text'
        const res = await translate(item.phrase, {
          to: 'tr',
          autoCorrect: true,
        });
        item.mean = res.text;
        count++;

        if (count % 50 === 0) {
          console.log(
            `Translated ${count}/${itemsToTranslate.length}: ${item.phrase} -> ${item.mean}`
          );
          // Save progress periodically
          fs.writeFileSync(OUTPUT_FILE, JSON.stringify(data, null, 2));
        }

        // Small delay to be polite to the service
        await new Promise((resolve) => setTimeout(resolve, 100));
      } catch (err) {
        console.error(`Failed to translate '${item.phrase}':`, err.message);
      }
    }

    console.log(`Translation complete. Translated ${count} items.`);
    fs.writeFileSync(OUTPUT_FILE, JSON.stringify(data, null, 2));
  } catch (err) {
    console.error('Error:', err);
  }
}

main();
