#!/usr/bin/env node

/**
 * Immediate Stop Script - Disable automation to prevent triggers on position close
 */

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

async function immediateStop() {
  console.log('🚨 IMMEDIATE AUTOMATION STOP\n');

  try {
    // 1. Check current position
    console.log('📈 Checking Active Position:');
    const positionsResponse = await fetch(`${baseUrl}/api/drift/positions`);
    const positionsData = await positionsResponse.json();
    
    if (positionsData.success && positionsData.positions?.length > 0) {
      console.log(`   ⚠️  ACTIVE POSITION DETECTED: ${positionsData.positions.length} position(s)`);
      positionsData.positions.forEach((pos, i) => {
        console.log(`   - Position ${i+1}: ${pos.symbol} ${pos.side.toUpperCase()}`);
        console.log(`     Size: ${pos.size}, PnL: $${pos.unrealizedPnl?.toFixed(2)}`);
      });
      console.log('   🚨 Position close could trigger automation - STOPPING NOW!\n');
    }

    // 2. Stop automation immediately
    console.log('🛑 Stopping Automation:');
    const stopResponse = await fetch(`${baseUrl}/api/automation/stop`, {
      method: 'POST'
    });
    const stopResult = await stopResponse.json();
    console.log(`   - Regular Stop: ${stopResult.success ? '✅ SUCCESS' : '❌ FAILED'}`);
    console.log(`   - Message: ${stopResult.message}`);

    // 3. Emergency stop for extra safety
    console.log('\n🚨 Emergency Stop (Extra Safety):');
    const emergencyResponse = await fetch(`${baseUrl}/api/automation/emergency-stop`, {
      method: 'POST'
    });
    const emergencyResult = await emergencyResponse.json();
    console.log(`   - Emergency Stop: ${emergencyResult.success ? '✅ SUCCESS' : '❌ FAILED'}`);
    
    // 4. Verify automation is stopped
    console.log('\n✅ Verification:');
    const statusResponse = await fetch(`${baseUrl}/api/automation/status`);
    const statusData = await statusResponse.json();
    console.log(`   - Automation Active: ${statusData.isActive ? '⚠️  STILL ACTIVE' : '✅ STOPPED'}`);
    
    console.log('\n🎯 RESULT:');
    if (!statusData.isActive) {
      console.log('   ✅ AUTOMATION DISABLED - Safe to close position manually');
      console.log('   ✅ No automation will trigger when position closes');
      console.log('   💡 You can now close your position safely in Drift');
    } else {
      console.log('   ⚠️  AUTOMATION STILL ACTIVE - May need manual intervention');
    }

  } catch (error) {
    console.error('❌ Stop script failed:', error.message);
    console.log('\n🆘 MANUAL STOP COMMANDS:');
    console.log('   curl -X POST http://localhost:9001/api/automation/stop');
    console.log('   curl -X POST http://localhost:9001/api/automation/emergency-stop');
  }
}

immediateStop().catch(console.error);
