#!/usr/bin/env node

/**
 * Emergency Stop Test - Verifies that trading can be stopped safely
 */

const baseUrl = 'http://localhost:9001';

async function testEmergencyStop() {
  console.log('🚨 Emergency Stop Test - Trading System Safety Check\n');

  try {
    // 1. Check current status
    console.log('📊 Current System Status:');
    const statusResponse = await fetch(`${baseUrl}/api/automation/status`);
    const status = await statusResponse.json();
    console.log(`   - Automation Active: ${status.isActive ? '✅ YES' : '❌ NO'}`);
    if (status.isActive) {
      console.log(`   - Mode: ${status.mode}`);
      console.log(`   - Symbol: ${status.symbol}`);
      console.log(`   - Timeframes: ${status.timeframes?.join(', ') || 'None'}`);
    }

    // 2. Check active positions
    console.log('\n📈 Current Positions:');
    const positionsResponse = await fetch(`${baseUrl}/api/drift/positions`);
    const positionsData = await positionsResponse.json();
    if (positionsData.success && positionsData.positions?.length > 0) {
      console.log(`   - Active Positions: ${positionsData.positions.length}`);
      positionsData.positions.forEach((pos, i) => {
        console.log(`   - Position ${i+1}: ${pos.symbol} ${pos.side.toUpperCase()}`);
        console.log(`     Size: ${pos.size}, Entry: $${pos.entryPrice?.toFixed(4)}`);
        console.log(`     PnL: $${pos.unrealizedPnl?.toFixed(2)}`);
      });
    } else {
      console.log('   - No active positions');
    }

    // 3. Test regular stop function
    console.log('\n🛑 Testing Regular Stop Function:');
    const stopResponse = await fetch(`${baseUrl}/api/automation/stop`, {
      method: 'POST'
    });
    const stopResult = await stopResponse.json();
    console.log(`   - Stop API: ${stopResult.success ? '✅ Working' : '❌ Failed'}`);
    console.log(`   - Message: ${stopResult.message}`);

    // 4. Test emergency stop function
    console.log('\n🚨 Testing Emergency Stop Function:');
    const emergencyResponse = await fetch(`${baseUrl}/api/automation/emergency-stop`, {
      method: 'POST'
    });
    const emergencyResult = await emergencyResponse.json();
    console.log(`   - Emergency Stop API: ${emergencyResult.success ? '✅ Working' : '❌ Failed'}`);
    console.log(`   - Message: ${emergencyResult.message}`);
    if (emergencyResult.results) {
      console.log(`   - Automation Stopped: ${emergencyResult.results.automationStopped ? '✅' : '❌'}`);
      console.log(`   - Processes Killed: ${emergencyResult.results.processesKilled ? '✅' : '❌'}`);
      console.log(`   - Cleanup Completed: ${emergencyResult.results.cleanupCompleted ? '✅' : '❌'}`);
    }

    // 5. Verify dashboard access
    console.log('\n🖥️  Dashboard Accessibility:');
    const dashboardResponse = await fetch(`${baseUrl}/automation-v2`);
    console.log(`   - Dashboard Page: ${dashboardResponse.ok ? '✅ Accessible' : '❌ Not accessible'}`);
    
    console.log('\n🎯 Stop Button Summary:');
    console.log('   ✅ Regular Stop: Available in UI and working via API');
    console.log('   ✅ Emergency Stop: Available in UI and working via API');
    console.log('   ✅ Dashboard Access: Working for manual control');
    console.log('\n💡 To stop trading:');
    console.log('   1. Go to http://localhost:9001/automation-v2');
    console.log('   2. Click the 🛑 STOP button (regular stop)');
    console.log('   3. Or click 🚨 EMERGENCY button (immediate stop + cleanup)');
    console.log('   4. Or run: curl -X POST http://localhost:9001/api/automation/stop');
    console.log('   5. Or run: curl -X POST http://localhost:9001/api/automation/emergency-stop');

  } catch (error) {
    console.error('❌ Emergency Stop Test Failed:', error.message);
  }
}

// Run the test
testEmergencyStop().catch(console.error);
