const { MandatoryRiskManager } = require('./lib/mandatory-risk-manager');

async function emergencyProtectAllPositions() {
  try {
    console.log('🚨 EMERGENCY POSITION PROTECTION SYSTEM ACTIVATED');
    console.log('🔍 Scanning for unprotected positions...');
    
    const riskManager = new MandatoryRiskManager();
    
    // Check current position
    const positionResponse = await fetch('http://localhost:9001/api/automation/position-monitor');
    const positionData = await positionResponse.json();
    
    if (!positionData.monitor.hasPosition) {
      console.log('✅ No active positions found - no emergency protection needed');
      return;
    }
    
    const position = positionData.monitor.position;
    console.log('📊 Active position detected:', {
      symbol: position.symbol,
      side: position.side,
      size: position.size,
      entryPrice: position.entryPrice,
      currentPrice: position.currentPrice,
      unrealizedPnl: position.unrealizedPnl
    });
    
    // Check if position has protective orders
    const ordersResponse = await fetch('http://localhost:9001/api/drift/orders');
    const ordersData = await ordersResponse.json();
    
    const activeOrders = ordersData.orders?.filter(order => order.isActive) || [];
    console.log(`📋 Active protective orders: ${activeOrders.length}`);
    
    if (activeOrders.length === 0) {
      console.log('🚨 UNPROTECTED POSITION DETECTED - CALCULATING EMERGENCY PROTECTION');
      
      const protection = await riskManager.emergencyProtectPosition({
        side: position.side,
        size: position.size,
        entryPrice: position.entryPrice
      });
      
      console.log('⚠️ EMERGENCY PROTECTION REQUIRED:');
      console.log(`   Current Position: ${position.side.toUpperCase()} ${position.size} @ $${position.entryPrice.toFixed(2)}`);
      console.log(`   Current P&L: $${position.unrealizedPnl.toFixed(2)}`);
      console.log(`   Required Stop-Loss: $${protection.stopLoss.toFixed(2)}`);
      console.log(`   Required Take-Profit: $${protection.takeProfit.toFixed(2)}`);
      console.log('');
      console.log('🔧 MANUAL ACTION REQUIRED - Place these orders immediately:');
      
      if (position.side === 'short') {
        console.log(`   1. Stop-Loss: LONG ${position.size} SOL @ $${protection.stopLoss.toFixed(2)} (trigger order, reduceOnly: true)`);
        console.log(`   2. Take-Profit: LONG ${position.size} SOL @ $${protection.takeProfit.toFixed(2)} (limit order, reduceOnly: true)`);
      } else {
        console.log(`   1. Stop-Loss: SHORT ${position.size} SOL @ $${protection.stopLoss.toFixed(2)} (trigger order, reduceOnly: true)`);
        console.log(`   2. Take-Profit: SHORT ${position.size} SOL @ $${protection.takeProfit.toFixed(2)} (limit order, reduceOnly: true)`);
      }
      
      console.log('');
      console.log('⚡ RISK ASSESSMENT:');
      if (position.unrealizedPnl > 0) {
        console.log(`   ✅ Position is currently PROFITABLE (+$${position.unrealizedPnl.toFixed(2)})`);
        console.log('   🎯 Secure profits with take-profit order');
      } else {
        console.log(`   ⚠️ Position is currently at LOSS ($${position.unrealizedPnl.toFixed(2)})`);
        console.log('   🛑 Limit further losses with stop-loss order');
      }
      
      // Calculate potential loss without stop-loss
      const currentPrice = position.currentPrice;
      const worstCasePrice = position.side === 'short' ? currentPrice * 1.10 : currentPrice * 0.90;
      const worstCaseLoss = position.side === 'short' ? 
        (worstCasePrice - position.entryPrice) * position.size :
        (position.entryPrice - worstCasePrice) * position.size;
      
      console.log('');
      console.log('💥 WITHOUT STOP-LOSS PROTECTION:');
      console.log(`   Potential 10% adverse move could cost: $${Math.abs(worstCaseLoss).toFixed(2)}`);
      console.log('   PROTECTION IS CRITICAL!');
      
    } else {
      console.log('✅ Position has protective orders in place:');
      activeOrders.forEach(order => {
        console.log(`   ${order.direction} ${order.size} @ $${order.price} (${order.orderType})`);
      });
    }
    
  } catch (error) {
    console.error('❌ Emergency protection system error:', error);
  }
}

// Run emergency protection check
emergencyProtectAllPositions();
