#!/usr/bin/env node

const axios = require('axios');

console.log('🚨 EMERGENCY STOP - Halting all automation processes');

async function emergencyStop() {
  try {
    // Check current automation status
    console.log('📊 Checking automation status...');
    const statusResponse = await axios.get('http://localhost:9001/api/automation/status');
    console.log('Current status:', statusResponse.data);

    // Stop any running automation
    console.log('⛔ Sending stop signal...');
    try {
      const stopResponse = await axios.post('http://localhost:9001/api/automation/stop');
      console.log('Stop response:', stopResponse.data);
    } catch (stopError) {
      console.log('Stop request failed (automation may not be running):', stopError.response?.data || stopError.message);
    }

    // Check for any running Chromium processes
    console.log('🔍 Checking for Chromium processes...');
    const { execSync } = require('child_process');
    
    try {
      const chromeProcesses = execSync('pgrep -f "chrome|chromium" 2>/dev/null || echo "0"', { encoding: 'utf8' }).trim();
      if (chromeProcesses !== '0') {
        console.log(`⚠️  Found ${chromeProcesses.split('\n').length} Chromium processes`);
        
        // Force kill Chromium processes
        console.log('💀 Force killing Chromium processes...');
        execSync('pkill -f "chrome|chromium" 2>/dev/null || true');
        console.log('✅ Chromium processes terminated');
      } else {
        console.log('✅ No Chromium processes found');
      }
    } catch (processError) {
      console.log('Process check failed:', processError.message);
    }

    // Final status check
    console.log('📊 Final status check...');
    const finalStatusResponse = await axios.get('http://localhost:9001/api/automation/status');
    console.log('Final status:', finalStatusResponse.data);

    console.log('\n✅ EMERGENCY STOP COMPLETED');
    console.log('🔄 To restart automation safely, use the web interface with proper rate limiting');

  } catch (error) {
    console.error('❌ Emergency stop failed:', error.message);
    
    // Fallback: restart container
    console.log('🔄 Fallback: Restarting container...');
    try {
      const { execSync } = require('child_process');
      execSync('docker restart trader_dev');
      console.log('✅ Container restarted');
    } catch (restartError) {
      console.error('❌ Container restart failed:', restartError.message);
    }
  }
}

emergencyStop();
