#!/usr/bin/env node

/**
 * AI-Enhanced Position Consolidation Test
 * Shows difference between AI-calculated vs adaptive levels
 */

async function testAIConsolidation() {
  console.log('🧹 TESTING AI-ENHANCED POSITION CONSOLIDATION');
  console.log('='.repeat(60));
  
  try {
    // 1. Get current position
    console.log('1️⃣ Fetching current position...');
    const positionResponse = await fetch('http://localhost:9001/api/drift/positions');
    const positionData = await positionResponse.json();
    
    if (!positionData.success || !positionData.positions.length) {
      console.log('❌ No active positions found');
      return;
    }
    
    const position = positionData.positions[0];
    console.log(`   📊 Position: ${position.side.toUpperCase()} ${position.size} ${position.symbol}`);
    console.log(`   💰 Entry: $${position.entryPrice.toFixed(4)}`);
    console.log(`   📈 Current: $${(position.markPrice || position.entryPrice).toFixed(4)}`);
    console.log(`   💸 P&L: $${position.unrealizedPnl.toFixed(2)}`);
    
    // 2. Get current orders count
    console.log('\n2️⃣ Checking current orders...');
    const ordersResponse = await fetch('http://localhost:9001/api/drift/orders');
    const ordersData = await ordersResponse.json();
    const activeOrders = ordersData.orders.filter(o => o.status === 'OPEN');
    console.log(`   📋 Active orders: ${activeOrders.length}`);
    
    // 3. Test ADAPTIVE LEVELS (no AI analysis)
    console.log('\n3️⃣ ADAPTIVE LEVELS (No AI Analysis):');
    console.log('-'.repeat(40));
    
    const adaptiveResult = await fetch('http://localhost:9001/api/drift/consolidate-position', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ 
        dryRun: true,
        analysis: null
      })
    });
    
    const adaptiveData = await adaptiveResult.json();
    if (adaptiveData.success) {
      const plan = adaptiveData.plan;
      console.log(`   🛑 Stop Loss: $${plan.stopLoss.toFixed(4)} (${plan.stopLossPercent.toFixed(1)}% risk)`);
      console.log(`   🎯 Take Profit 1: $${plan.takeProfit1.toFixed(4)} (${plan.tp1Percent.toFixed(1)}% gain) - ${plan.tp1Size} SOL`);
      console.log(`   🚀 Take Profit 2: $${plan.takeProfit2.toFixed(4)} (${plan.tp2Percent.toFixed(1)}% gain) - ${plan.tp2Size} SOL`);
      console.log(`   ⚖️ Risk/Reward: ${plan.riskReward.toFixed(1)}:1`);
    }
    
    // 4. Test AI-CALCULATED LEVELS
    console.log('\n4️⃣ AI-CALCULATED LEVELS (Mock AI Analysis):');
    console.log('-'.repeat(40));
    
    // Mock AI analysis with tighter, more optimal levels
    const mockAIAnalysis = {
      stopLoss: { price: 185.50 },  // AI suggests tighter 1% stop loss
      takeProfits: { 
        tp1: { price: 191.25 },     // AI suggests 2.1% first TP
        tp2: { price: 194.80 }      // AI suggests 3.9% second TP
      },
      confidence: 85,
      marketConditions: { volatility: 'LOW' }
    };
    
    const aiResult = await fetch('http://localhost:9001/api/drift/consolidate-position', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ 
        dryRun: true,
        analysis: mockAIAnalysis
      })
    });
    
    const aiData = await aiResult.json();
    if (aiData.success) {
      const plan = aiData.plan;
      console.log(`   🛑 Stop Loss: $${plan.stopLoss.toFixed(4)} (${plan.stopLossPercent.toFixed(1)}% risk)`);
      console.log(`   🎯 Take Profit 1: $${plan.takeProfit1.toFixed(4)} (${plan.tp1Percent.toFixed(1)}% gain) - ${plan.tp1Size} SOL`);
      console.log(`   🚀 Take Profit 2: $${plan.takeProfit2.toFixed(4)} (${plan.tp2Percent.toFixed(1)}% gain) - ${plan.tp2Size} SOL`);
      console.log(`   ⚖️ Risk/Reward: ${plan.riskReward.toFixed(1)}:1`);
    }
    
    // 5. Comparison and benefits
    console.log('\n5️⃣ CONSOLIDATION BENEFITS:');
    console.log('   📉 BEFORE: 24+ fragmented orders');
    console.log('   📈 AFTER: 3 clean orders (adaptive OR AI-optimized)');
    console.log('   ✅ Benefits:');
    console.log('      • AI calculates optimal entry/exit levels');
    console.log('      • Falls back to adaptive levels when AI unavailable');
    console.log('      • Clear risk management structure');
    console.log('      • Lower transaction costs');
    console.log('      • Better profit optimization');
    console.log('      • Easier monitoring');
    
    console.log('\n💡 EXECUTION OPTIONS:');
    console.log('🧠 WITH AI: Send analysis data for optimal levels');
    console.log('📊 WITHOUT AI: Uses adaptive levels based on position size');
    console.log('🚀 LIVE EXECUTION: Set dryRun: false to execute');
    
    return {
      success: true,
      currentOrders: activeOrders.length,
      consolidatedOrders: 3,
      aiLevelsAvailable: aiData.success,
      adaptiveLevelsAvailable: adaptiveData.success
    };
    
  } catch (error) {
    console.error('❌ AI consolidation test failed:', error.message);
    return { success: false, error: error.message };
  }
}

// Run the test
testAIConsolidation().then(result => {
  if (result.success) {
    console.log('\n✅ AI-ENHANCED CONSOLIDATION ANALYSIS COMPLETE');
    console.log(`📊 Reduction: ${result.currentOrders} → ${result.consolidatedOrders} orders`);
    console.log(`🧠 AI Levels: ${result.aiLevelsAvailable ? 'Available' : 'Not available'}`);
    console.log(`📊 Adaptive Levels: ${result.adaptiveLevelsAvailable ? 'Available' : 'Not available'}`);
  }
}).catch(console.error);
