/**
 * AEM Asset Upload Sample - Main Entry Point
 * 
 * This is an interactive CLI to run different upload examples
 */

const readline = require('readline');
const chalk = require('chalk');
const filesystemUpload = require('./examples/filesystem-upload');
const directBinaryUpload = require('./examples/direct-binary-upload');
const batchUpload = require('./examples/batch-upload');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

/**
 * Displays the main menu
 */
function displayMenu() {
  // Clear screen on supported terminals, but don't fail if not supported
  if (process.stdout.isTTY) {
    console.clear();
  } else {
    console.log('\n');
  }
  
  console.log(chalk.bold.cyan('╔════════════════════════════════════════════════════════════╗'));
  console.log(chalk.bold.cyan('║      AEM Asset Upload Sample Application                  ║'));
  console.log(chalk.bold.cyan('║      Demonstrating @adobe/aem-upload library               ║'));
  console.log(chalk.bold.cyan('╚════════════════════════════════════════════════════════════╝\n'));

  console.log(chalk.bold('Choose an upload method:\n'));
  console.log(chalk.yellow('1.') + ' FileSystemUpload - Upload files from local filesystem with auto-folder creation');
  console.log(chalk.yellow('2.') + ' DirectBinaryUpload - Upload from remote URLs/streams to AEM');
  console.log(chalk.yellow('3.') + ' Batch Upload - Upload multiple files in batches with retry logic');
  console.log(chalk.yellow('4.') + ' Exit\n');
}

/**
 * Prompts user for choice and executes the selected example
 */
function promptUser() {
  rl.question(chalk.bold('Enter your choice (1-4): '), async (answer) => {
    console.log('');

    try {
      switch (answer.trim()) {
        case '1':
          console.log(chalk.bold.green('\n▶ Running FileSystemUpload Example...\n'));
          await filesystemUpload.main();
          break;

        case '2':
          console.log(chalk.bold.green('\n▶ Running DirectBinaryUpload Example...\n'));
          await directBinaryUpload.main();
          break;

        case '3':
          console.log(chalk.bold.green('\n▶ Running Batch Upload Example...\n'));
          await batchUpload.main();
          break;

        case '4':
          rl.close();
          return;

        default:
          console.log(chalk.red('\n✗ Invalid choice. Please enter 1, 2, 3, or 4.\n'));
      }

      // After example completes, ask if user wants to continue
      rl.question(chalk.bold('\nPress Enter to return to menu or Ctrl+C to exit...'), () => {
        displayMenu();
        promptUser();
      });

    } catch (error) {
      console.error(chalk.red('\n✗ Error:'), error.message);
      rl.question(chalk.bold('\nPress Enter to return to menu...'), () => {
        displayMenu();
        promptUser();
      });
    }
  });
}

/**
 * Main function
 */
function main() {
  // Check if .env file exists
  const fs = require('fs');
  const path = require('path');
  const envPath = path.join(__dirname, '.env');

  if (!fs.existsSync(envPath)) {
    console.log(chalk.red('\n⚠ WARNING: .env file not found!\n'));
    console.log('Please create a .env file with your AEM configuration.');
    console.log('You can copy env.example to .env and fill in your details:\n');
    console.log(chalk.cyan('  cp env.example .env\n'));
    console.log('Then edit .env with your AEM as a Cloud Service details.\n');
    process.exit(1);
  }

  displayMenu();
  promptUser();
}

// Handle cleanup on exit
rl.on('close', () => {
  console.log(chalk.green('\nGoodbye! 👋\n'));
  process.exit(0);
});

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

module.exports = { main };

