/**
 * Test Suite for Enhanced Terminal Service
 * Demonstrates usage of the modular tool system
 */

const { EnhancedTerminalService } = require('./enhanced-terminal-service.cjs');

// ANSI color codes for terminal output
const colors = {
  reset: '\x1b[0m',
  green: '\x1b[32m',
  red: '\x1b[31m',
  blue: '\x1b[34m',
  yellow: '\x1b[33m',
  gray: '\x1b[90m'
};

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

function separator() {
  log('─'.repeat(60), 'gray');
}

async function runTests() {
  log('\n🚀 Enhanced Terminal Service - Test Suite', 'blue');
  separator();

  // Create service instance
  const terminal = new EnhancedTerminalService({
    defaultTimeout: 5000,
    enableTelemetry: true
  });

  try {
    // Test 1: Basic shell command
    log('\n📋 Test 1: Basic Shell Command', 'yellow');
    separator();
    const test1 = await terminal.execute('echo "Hello, World!"');
    log(`Command: echo "Hello, World!"`, 'blue');
    log(`Result: ${test1.success ? '✅ PASS' : '❌ FAIL'}`, test1.success ? 'green' : 'red');
    log(`Output: ${test1.output}`, 'gray');

    // Test 2: Intent analysis - list directory
    log('\n📋 Test 2: Intent Analysis - Directory Listing', 'yellow');
    separator();
    const test2 = await terminal.execute('ls -la');
    log(`Command: ls -la`, 'blue');
    log(`Intent: ${test2.intent.intent} (confidence: ${test2.intent.confidence})`, 'gray');
    log(`Result: ${test2.success ? '✅ PASS' : '❌ FAIL'}`, test2.success ? 'green' : 'red');
    log(`Output lines: ${test2.output.split('\n').length}`, 'gray');

    // Test 3: File operations - write and read
    log('\n📋 Test 3: File Operations (via Tool)', 'yellow');
    separator();
    const testFile = '/tmp/enhanced-terminal-test.txt';

    // Write file using shell (echo with redirect)
    log(`Writing file: ${testFile}`, 'blue');
    const test3a = await terminal.executeShell(`echo "test content" > ${testFile}`);
    log(`Write result: ${test3a.success ? '✅ PASS' : '❌ FAIL'}`, test3a.success ? 'green' : 'red');

    // Read file using shell
    log(`Reading file: ${testFile}`, 'blue');
    const test3b = await terminal.executeShell(`cat ${testFile}`);
    log(`Read result: ${test3b.success ? '✅ PASS' : '❌ FAIL'}`, test3b.success ? 'green' : 'red');

    // Cleanup test file
    await terminal.executeShell(`rm ${testFile}`);

    // Test 4: Command suggestions
    log('\n📋 Test 4: Command Suggestions', 'yellow');
    separator();
    const suggestions = terminal.getSuggestions('ls');
    log(`Input: "ls"`, 'blue');
    log(`Suggestions: ${suggestions.length} found`, 'gray');
    suggestions.forEach(s => log(`  - ${s}`, 'gray'));

    // Test 5: Multiple command types
    log('\n📋 Test 5: Various Command Types', 'yellow');
    separator();

    const commands = [
      'pwd',
      'node --version',
      'npm --version 2>/dev/null || echo "npm not found"'
    ];

    for (const cmd of commands) {
      const result = await terminal.execute(cmd);
      const icon = result.success ? '✅' : '❌';
      log(`${icon} ${cmd}`, result.success ? 'green' : 'red');
    }

    // Test 6: Get statistics
    log('\n📋 Test 6: Service Statistics', 'yellow');
    separator();
    const stats = terminal.getStats();
    log(`Total commands: ${stats.totalCommands}`, 'blue');
    log(`Successful: ${stats.successfulCommands}`, 'green');
    log(`Failed: ${stats.failedCommands}`, 'red');
    log(`Avg response time: ${stats.avgResponseTime.toFixed(2)}ms`, 'blue');
    log(`Commands by type:`, 'blue');
    for (const [type, count] of Object.entries(stats.commandByType)) {
      log(`  - ${type}: ${count}`, 'gray');
    }

    // Test 7: Available tools
    log('\n📋 Test 7: Available Tools', 'yellow');
    separator();
    const tools = terminal.getAvailableTools();
    log(`Registered tools: ${tools.length}`, 'blue');
    tools.forEach(tool => {
      log(`  - ${tool.name}: ${tool.description}`, 'gray');
    });

    // Test 8: Health check
    log('\n📋 Test 8: Health Check', 'yellow');
    separator();
    const health = terminal.healthCheck();
    log(`Status: ${health.status}`, 'green');
    log(`Uptime: ${health.uptime.toFixed(2)}s`, 'blue');
    log(`Memory used: ${(health.memory.heapUsed / 1024 / 1024).toFixed(2)} MB`, 'blue');

    // Test 9: Execution history
    log('\n📋 Test 9: Execution History', 'yellow');
    separator();
    const history = terminal.getHistory({ limit: 3 });
    log(`Recent executions (last 3):`, 'blue');
    history.forEach((record, index) => {
      log(`  ${index + 1}. ${record.tool} - ${record.result.success ? '✅' : '❌'} (${record.duration}ms)`, 'gray');
    });

    // Summary
    separator();
    log('\n🎉 All Tests Complete!', 'green');
    separator();

    const successRate = (stats.successfulCommands / stats.totalCommands * 100).toFixed(1);
    log(`Success Rate: ${successRate}%`, successRate > 80 ? 'green' : 'yellow');
    log(`Total Executions: ${stats.totalCommands}`, 'blue');

  } catch (error) {
    log(`\n❌ Test Error: ${error.message}`, 'red');
    console.error(error);
  } finally {
    // Cleanup
    await terminal.cleanup();
  }
}

// Run tests if executed directly
if (require.main === module) {
  runTests().catch(console.error);
}

module.exports = { runTests };
