#!/usr/bin/env node

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

// Load the translation dictionary
function loadDictionary() {
  try {
    const dictPath = path.join(__dirname, 'dict.json');
    const dictData = fs.readFileSync(dictPath, 'utf8');
    return JSON.parse(dictData);
  } catch (error) {
    console.error('Error loading dictionary:', error.message);
    process.exit(1);
  }
}

// Parse command line arguments
function parseArguments() {
  const args = process.argv.slice(2);
  const options = {
    inputLang: null,
    outputLang: null,
    text: null
  };

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

    switch (arg) {
      case '-i':
      case '--input':
        if (i + 1 < args.length) {
          options.inputLang = args[i + 1];
          i++; // Skip next argument as it's the value
        } else {
          console.error('Error: -i flag requires a language value');
          process.exit(1);
        }
        break;

      case '-o':
      case '--output':
        if (i + 1 < args.length) {
          options.outputLang = args[i + 1];
          i++; // Skip next argument as it's the value
        } else {
          console.error('Error: -o flag requires a language value');
          process.exit(1);
        }
        break;

      case '-t':
      case '--text':
        if (i + 1 < args.length) {
          options.text = args[i + 1];
          i++; // Skip next argument as it's the value
        } else {
          console.error('Error: -t flag requires text to translate');
          process.exit(1);
        }
        break;

      case '-h':
      case '--help':
        showHelp();
        process.exit(0);

      default:
        // If argument doesn't start with -, treat it as text if we don't have text yet
        if (!options.text && !arg.startsWith('-')) {
          options.text = arg;
        }
        break;
    }
  }

  return options;
}

// Show help information
function showHelp() {
  console.log(`
Node.js CLI Translator

Usage: node translate.js [options]

Options:
  -i, --input <lang>    Input language (en, ru)
  -o, --output <lang>   Output language (en, ru)
  -t, --text <text>     Text to translate
  -h, --help           Show this help message

Examples:
  node translate.js -i en -o ru -t "hello world"
  node translate.js -i ru -o en -t "привет мир"
  node translate.js --input en --output ru --text "goodbye"

Supported languages: en (English), ru (Russian)
`);
}

// Validate arguments
function validateArguments(options) {
  const errors = [];

  if (!options.inputLang) {
    errors.push('Input language (-i) is required');
  }

  if (!options.outputLang) {
    errors.push('Output language (-o) is required');
  }

  if (!options.text) {
    errors.push('Text to translate (-t) is required');
  }

  if (options.inputLang && !['en', 'ru'].includes(options.inputLang)) {
    errors.push('Input language must be "en" or "ru"');
  }

  if (options.outputLang && !['en', 'ru'].includes(options.outputLang)) {
    errors.push('Output language must be "en" or "ru"');
  }

  if (options.inputLang === options.outputLang) {
    errors.push('Input and output languages must be different');
  }

  if (errors.length > 0) {
    console.error('Validation errors:');
    errors.forEach(error => console.error(`  - ${error}`));
    console.error('\nUse -h or --help for usage information');
    process.exit(1);
  }
}

// Translate text
function translateText(text, inputLang, outputLang, dictionary) {
  // Split text into words for better translation
  const words = text.toLowerCase().split(/\s+/);
  const translatedWords = [];

  for (const word of words) {
    let translated = false;

    // Try to find exact match first
    if (dictionary[inputLang] && dictionary[inputLang][outputLang] && dictionary[inputLang][outputLang][word]) {
      translatedWords.push(dictionary[inputLang][outputLang][word]);
      translated = true;
    }

    // If no exact match found, try partial matches for compound words
    if (!translated) {
      let foundTranslation = false;
      for (const [key, value] of Object.entries(dictionary[inputLang][outputLang] || {})) {
        if (word.includes(key) || key.includes(word)) {
          translatedWords.push(value);
          foundTranslation = true;
          break;
        }
      }

      // If still no translation found, keep original word
      if (!foundTranslation) {
        translatedWords.push(word);
      }
    }
  }

  // Capitalize first letter if original text started with capital
  const firstWord = translatedWords[0];
  if (firstWord && text.charAt(0) === text.charAt(0).toUpperCase()) {
    translatedWords[0] = firstWord.charAt(0).toUpperCase() + firstWord.slice(1);
  }

  return translatedWords.join(' ');
}

// Main function
function main() {
  const dictionary = loadDictionary();
  const options = parseArguments();
  validateArguments(options);

  const { inputLang, outputLang, text } = options;

  console.log(`Translating from ${inputLang.toUpperCase()} to ${outputLang.toUpperCase()}:`);
  console.log(`Original: "${text}"`);

  const translatedText = translateText(text, inputLang, outputLang, dictionary);

  console.log(`Translated: "${translatedText}"`);
}

// Run the translator
if (require.main === module) {
  main();
}

module.exports = {
  loadDictionary,
  parseArguments,
  validateArguments,
  translateText,
  main
};
