/**
 * Execute Position Consolidation
 * Converts 24+ fragmented orders into clean 3-order structure
 */

async function executeConsolidation() {
  console.log('🧹 EXECUTING POSITION CONSOLIDATION');
  console.log('==================================================');
  
  const baseUrl = process.env.INTERNAL_API_URL || 'http://localhost:3000';
  
  try {
    // Step 1: Analyze current position
    console.log('1️⃣ Analyzing current position...');
    const response = await fetch(`${baseUrl}/api/drift/consolidate-position`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ dryRun: false })
    });
    
    const result = await response.json();
    
    if (result.success) {
      console.log('✅ CONSOLIDATION SUCCESSFUL!');
      console.log('📊 Summary:');
      console.log(`   Orders before: ${result.ordersBefore}`);
      console.log(`   Orders after: ${result.ordersAfter}`);
      console.log(`   Reduction: ${result.ordersBefore} → ${result.ordersAfter} orders`);
      
      if (result.newOrders) {
        console.log('🆕 New clean orders:');
        result.newOrders.forEach((order, index) => {
          console.log(`   ${index + 1}. ${order.orderType} at $${order.price} for ${order.size} SOL`);
        });
      }
    } else {
      console.log('❌ CONSOLIDATION FAILED:');
      console.log(`   Error: ${result.error}`);
      if (result.details) {
        console.log(`   Details: ${JSON.stringify(result.details, null, 2)}`);
      }
    }
    
  } catch (error) {
    console.log('💥 EXECUTION ERROR:');
    console.log(`   ${error.message}`);
  }
  
  console.log('==================================================');
}

// Execute if run directly
if (require.main === module) {
  executeConsolidation();
}

module.exports = { executeConsolidation };
