#!/usr/bin/env node

const fs = require('fs-extra');
const path = require('path');
const readline = require('readline');

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

const projects = {
  '1': { name: 'ECMS', fullName: 'market', folder: 'ecms' },
  '2': { name: 'EPMS', fullName: 'worker', folder: 'epms' },
  '3': { name: 'HSMS', fullName: 'doctor', folder: 'hsms' },
  '4': { name: 'LMS', fullName: 'author', folder: 'LMS' },
  '5': { name: 'SFP', fullName: 'DOS', folder: 'sfms' }
};

function showBanner() {
  console.log('\n🐍 Welcome to Mangoose XEMPP Installer\n');
}

function showMenu() {
  console.log('Select a package to install:\n');
  
  Object.entries(projects).forEach(([key, project]) => {
    console.log(`  [${key}] ${project.name} — ${project.fullName}`);
  });
  
  console.log('');
  rl.question('Pick (1-5): ', handleSelection);
}

async function handleSelection(choice) {
  const project = projects[choice];
  
  if (!project) {
    console.log('\n⚠ Invalid choice. Please pick 1-5\n');
    showMenu();
    return;
  }

  console.log(`\n📦 Installing ${project.name} — ${project.fullName}...\n`);
  
  const steps = [
    'Preparing installation...',
    'Copying project files...',
    'Setting up project structure...'
  ];
  
  for (const step of steps) {
    await sleep(500);
    console.log(`  ⚡ ${step}`);
  }

  try {
    const sourcePath = path.join(__dirname, '..', 'templates', project.folder);
    const targetPath = path.join(process.cwd(), `mangoose-${project.folder}`);
    
    await fs.copy(sourcePath, targetPath);
    
    await sleep(300);
    
    console.log(`\n✅ ${project.name} installed successfully!`);
    console.log(`📍 Location: ${targetPath}`);
    console.log('\nNext steps:');
    console.log(`  cd mangoose-${project.folder}`);
    console.log('  npm install');
    console.log('  npm start\n');
    
  } catch (error) {
    console.error(`\n❌ Error: Template not found for ${project.name}`);
    console.log('Make sure templates are in the package\n');
  }
  
  rl.close();
}

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

showBanner();
showMenu();