#!/usr/bin/env node

/**
 * Lelu Init - One-command setup for Lelu
 * 
 * This script:
 * 1. Checks if Docker is installed
 * 2. Downloads docker-compose.yml
 * 3. Starts all services
 * 4. Creates .env file
 * 5. Opens browser to UI
 */

import { execSync } from 'child_process';
import { existsSync, writeFileSync } from 'fs';
import { createInterface } from 'readline';
import https from 'https';

// Colors for terminal output
const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  green: '\x1b[32m',
  red: '\x1b[31m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  cyan: '\x1b[36m',
};

function log(message, color = 'reset') {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

function checkDocker() {
  try {
    execSync('docker --version', { stdio: 'ignore' });
    execSync('docker-compose --version', { stdio: 'ignore' });
    return true;
  } catch {
    return false;
  }
}

function downloadFile(url, dest) {
  return new Promise((resolve, reject) => {
    const file = require('fs').createWriteStream(dest);
    https.get(url, (response) => {
      response.pipe(file);
      file.on('finish', () => {
        file.close();
        resolve();
      });
    }).on('error', (err) => {
      require('fs').unlink(dest, () => {});
      reject(err);
    });
  });
}

async function askQuestion(question) {
  const rl = createInterface({
    input: process.stdin,
    output: process.stdout
  });
  
  return new Promise((resolve) => {
    rl.question(question, (answer) => {
      rl.close();
      resolve(answer);
    });
  });
}

async function main() {
  console.log('');
  log('🚀 Lelu Initialization', 'bright');
  console.log('');
  
  // Check Docker
  log('Checking for Docker...', 'cyan');
  const hasDocker = checkDocker();
  
  if (!hasDocker) {
    console.log('');
    log('❌ Docker not found', 'red');
    console.log('');
    log('Lelu requires Docker to run the full stack with UI.', 'yellow');
    console.log('');
    log('Install Docker:', 'bright');
    log('  • Mac:     https://docs.docker.com/desktop/install/mac-install/');
    log('  • Windows: https://docs.docker.com/desktop/install/windows-install/');
    log('  • Linux:   https://docs.docker.com/engine/install/');
    console.log('');
    log('Or use CLI-only mode:', 'bright');
    log('  npx @lelu-auth/lelu audit-log', 'cyan');
    log('  npx @lelu-auth/lelu policies list', 'cyan');
    console.log('');
    process.exit(1);
  }
  
  log('✅ Docker found', 'green');
  console.log('');
  
  // Ask user preference
  const answer = await askQuestion('Start Lelu with Docker? (Y/n): ');
  
  if (answer.toLowerCase() === 'n') {
    console.log('');
    log('📝 CLI-only mode selected', 'yellow');
    console.log('');
    log('Available commands:', 'bright');
    log('  npx @lelu-auth/lelu audit-log       # View audit logs', 'cyan');
    log('  npx @lelu-auth/lelu policies list   # List policies', 'cyan');
    log('  npx @lelu-auth/lelu policies get    # Get policy', 'cyan');
    log('  npx @lelu-auth/lelu policies set    # Set policy', 'cyan');
    console.log('');
    log('Run "npx @lelu-auth/lelu init" again to start with Docker', 'yellow');
    console.log('');
    return;
  }
  
  console.log('');
  
  // Download docker-compose.yml
  log('📦 Downloading Lelu stack...', 'cyan');
  try {
    if (!existsSync('docker-compose.yml')) {
      await downloadFile(
        'https://raw.githubusercontent.com/lelu-auth/lelu/main/docker-compose.yml',
        'docker-compose.yml'
      );
      log('✅ Downloaded docker-compose.yml', 'green');
    } else {
      log('✅ docker-compose.yml already exists', 'green');
    }
  } catch (error) {
    log(`❌ Failed to download: ${error.message}`, 'red');
    log('Please download manually from:', 'yellow');
    log('https://raw.githubusercontent.com/lelu-auth/lelu/main/docker-compose.yml');
    process.exit(1);
  }
  
  console.log('');
  
  // Create .env file
  if (!existsSync('.env')) {
    log('📝 Creating .env file...', 'cyan');
    const envContent = `# Lelu Configuration
# Generated by: npx @lelu-auth/lelu init

# Engine Configuration
API_KEY=lelu-dev-key
JWT_SIGNING_KEY=change-me-in-production
LELU_MODE=enforce

# Platform Configuration
PLATFORM_API_KEY=platform-dev-key
POSTGRES_PASSWORD=lelu-dev-secret

# Client Configuration (for your app)
LELU_ENGINE_URL=http://localhost:8083
LELU_PLATFORM_URL=http://localhost:9091
LELU_API_KEY=lelu-dev-key
`;
    writeFileSync('.env', envContent);
    log('✅ Created .env file', 'green');
  } else {
    log('✅ .env file already exists', 'green');
  }
  
  console.log('');
  
  // Start services
  log('🔧 Starting Lelu services...', 'cyan');
  log('This may take a minute on first run...', 'yellow');
  console.log('');
  
  try {
    execSync('docker-compose up -d', { stdio: 'inherit' });
  } catch (error) {
    log('❌ Failed to start services', 'red');
    log('Try running manually: docker-compose up -d', 'yellow');
    process.exit(1);
  }
  
  console.log('');
  log('⏳ Waiting for services to be ready...', 'cyan');
  
  // Wait for services
  await new Promise(resolve => setTimeout(resolve, 5000));
  
  console.log('');
  log('✨ Lelu is ready!', 'green');
  console.log('');
  log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', 'bright');
  console.log('');
  log('📊 Web UI:        http://localhost:3002', 'bright');
  log('🔧 Engine API:    http://localhost:8083', 'bright');
  log('📝 Platform API:  http://localhost:9091', 'bright');
  console.log('');
  log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', 'bright');
  console.log('');
  log('Next steps:', 'bright');
  log('  1. Open http://localhost:3002 in your browser', 'cyan');
  log('  2. View the quickstart guide', 'cyan');
  log('  3. Make your first authorization request', 'cyan');
  console.log('');
  log('Useful commands:', 'bright');
  log('  docker-compose ps        # Check service status', 'cyan');
  log('  docker-compose logs -f   # View logs', 'cyan');
  log('  docker-compose down      # Stop services', 'cyan');
  console.log('');
  
  // Open browser
  const shouldOpen = await askQuestion('Open browser now? (Y/n): ');
  if (shouldOpen.toLowerCase() !== 'n') {
    console.log('');
    log('🌐 Opening browser...', 'cyan');
    try {
      const open = (await import('open')).default;
      await open('http://localhost:3002');
    } catch {
      log('Could not open browser automatically', 'yellow');
      log('Please open http://localhost:3002 manually', 'yellow');
    }
  }
  
  console.log('');
}

main().catch((error) => {
  console.error('');
  log(`❌ Error: ${error.message}`, 'red');
  console.error('');
  process.exit(1);
});
