// Use native fetch or alternative
const fetch = globalThis.fetch || require('node-fetch');

async function emergencyRiskManagement() {
  try {
    console.log('🚨 EMERGENCY: Placing protective orders for unprotected SHORT position...');
    
    // Get current position details
    const positionResponse = await fetch('http://localhost:9001/api/automation/position-monitor');
    const positionData = await positionResponse.json();
    
    if (!positionData.monitor.hasPosition) {
      console.log('✅ No position detected - no emergency action needed');
      return;
    }
    
    const position = positionData.monitor.position;
    console.log('📊 Current position:', {
      side: position.side,
      size: position.size,
      entryPrice: position.entryPrice,
      currentPrice: position.currentPrice,
      unrealizedPnl: position.unrealizedPnl
    });
    
    if (position.side !== 'short') {
      console.log('ℹ️ Position is not SHORT - different risk management needed');
      return;
    }
    
    // For SHORT position: Stop-loss ABOVE entry, Take-profit BELOW entry
    const entryPrice = position.entryPrice;
    const currentPrice = position.currentPrice;
    
    // Conservative stop-loss: 5% above entry price
    const stopLossPrice = (entryPrice * 1.05).toFixed(2);
    
    // Take profit: 3% below entry price  
    const takeProfitPrice = (entryPrice * 0.97).toFixed(2);
    
    console.log('📋 Calculated protective levels:');
    console.log(`  Entry: $${entryPrice.toFixed(2)}`);
    console.log(`  Stop-Loss: $${stopLossPrice} (${((stopLossPrice/entryPrice - 1) * 100).toFixed(1)}% above entry)`);
    console.log(`  Take-Profit: $${takeProfitPrice} (${((takeProfitPrice/entryPrice - 1) * 100).toFixed(1)}% below entry)`);
    
    // Place stop-loss order (LONG direction to close SHORT)
    console.log('🛑 Placing stop-loss order...');
    const stopLossResponse = await fetch('http://localhost:9001/api/trading', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        action: 'place_order',
        symbol: 'SOL-PERP',
        side: 'LONG', // To close SHORT position
        amount: position.size,
        orderType: 'stop_limit',
        price: stopLossPrice,
        triggerPrice: stopLossPrice,
        reduceOnly: true
      })
    });
    
    const stopLossResult = await stopLossResponse.json();
    console.log('🛑 Stop-loss result:', stopLossResult.success ? '✅ SUCCESS' : '❌ FAILED');
    if (!stopLossResult.success) {
      console.error('❌ Stop-loss error:', stopLossResult.error);
    }
    
    // Place take-profit order
    console.log('🎯 Placing take-profit order...');
    const takeProfitResponse = await fetch('http://localhost:9001/api/trading', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        action: 'place_order',
        symbol: 'SOL-PERP',
        side: 'LONG', // To close SHORT position
        amount: position.size,
        orderType: 'limit',
        price: takeProfitPrice,
        reduceOnly: true
      })
    });
    
    const takeProfitResult = await takeProfitResponse.json();
    console.log('🎯 Take-profit result:', takeProfitResult.success ? '✅ SUCCESS' : '❌ FAILED');
    if (!takeProfitResult.success) {
      console.error('❌ Take-profit error:', takeProfitResult.error);
    }
    
    // Verify orders were placed
    console.log('🔍 Verifying 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}`);
    
    activeOrders.forEach(order => {
      console.log(`  ${order.direction} ${order.size} @ $${order.price} (${order.orderType})`);
    });
    
    if (activeOrders.length === 0) {
      console.log('⚠️ WARNING: No active protective orders detected!');
    } else {
      console.log('✅ Position is now protected with stop-loss and take-profit orders');
    }
    
  } catch (error) {
    console.error('❌ Emergency risk management failed:', error);
  }
}

emergencyRiskManagement();
