/**
 * Test AI Leverage Integration - Direct Trade Execution Test
 * 
 * Tests that the trade execution uses AI leverage calculation
 * instead of hardcoded values.
 */

const { simpleAutomation } = require('./lib/simple-automation');

async function testAILeverageDirectly() {
  console.log('🧠 Testing AI Leverage Integration - Direct Trade Execution...\n');

  // Configure automation to set up the context
  const config = {
    mode: 'SIMULATION',
    symbol: 'SOLUSD',
    selectedTimeframes: ['60'],
    tradingAmount: 10,
    maxDailyTrades: 1,
    dexProvider: 'DRIFT'
  };

  // Set up the automation context
  simpleAutomation.config = config;
  simpleAutomation.isRunning = true;

  // Create a mock analysis that would trigger a trade
  const mockAnalysis = {
    recommendation: 'Strong Buy',
    confidence: 85,
    reasoning: 'Test analysis for AI leverage integration',
    currentPrice: 185.50,
    timeframeResults: [
      {
        timeframe: '60',
        analysis: {
          recommendation: 'Strong Buy',
          confidence: 85,
          reasoning: 'Mock 1h analysis'
        }
      }
    ]
  };

  console.log('📊 Mock Analysis:', {
    recommendation: mockAnalysis.recommendation,
    confidence: mockAnalysis.confidence,
    currentPrice: mockAnalysis.currentPrice
  });

  // Test the trade execution directly
  console.log('\n🚀 Testing AI leverage calculation in trade execution...');
  
  try {
    // First test if AI leverage calculator is accessible
    console.log('\n📊 Testing AI Leverage Calculator Access...');
    
    const { AILeverageCalculator } = require('./lib/ai-leverage-calculator.js');
    
    const testLeverageResult = AILeverageCalculator.calculateOptimalLeverage({
      accountValue: 244.45,
      availableBalance: 244.45,
      entryPrice: 185.50,
      stopLossPrice: 181.50, // 2.2% stop loss
      side: 'long',
      maxLeverageAllowed: 100, // Drift actual max leverage
      safetyBuffer: 0.10
    });
    
    console.log('✅ AI Leverage Calculator Working!');
    console.log('📊 Test Result:', {
      recommendedLeverage: `${testLeverageResult.recommendedLeverage.toFixed(1)}x`,
      riskAssessment: testLeverageResult.riskAssessment,
      reasoning: testLeverageResult.reasoning.substring(0, 100) + '...'
    });

    // Now test the trade execution flow
    console.log('\n🚀 Testing Trade Execution with AI Leverage...');
    
    // Call the shouldExecuteTrade method to see decision logic
    const shouldTrade = simpleAutomation.evaluateTradeDecision(mockAnalysis);
    console.log('📊 Trade Decision:', shouldTrade);
    
    if (shouldTrade.decision) {
      console.log('💰 Trade would be executed with AI leverage calculations');
      console.log('📋 Decision Reasoning:', shouldTrade.reasoning);
      
      // Show what the last decision would contain
      console.log('\n📊 Last Decision Preview:');
      console.log('- Timestamp:', new Date().toISOString());
      console.log('- Analysis Confidence:', mockAnalysis.confidence + '%');
      console.log('- Recommendation:', mockAnalysis.recommendation);
      console.log('- Trade Executed:', shouldTrade.decision);
      console.log('- AI Leverage:', `${testLeverageResult.recommendedLeverage.toFixed(1)}x`);
      console.log('- Risk Assessment:', testLeverageResult.riskAssessment);
    } else {
      console.log('📈 Trade would NOT be executed');
      console.log('📋 Reason:', shouldTrade.reasoning);
    }

    console.log('\n✅ AI Leverage Integration Test Completed Successfully!');
    console.log('🎯 Key Findings:');
    console.log(`   - AI Calculator produces ${testLeverageResult.recommendedLeverage.toFixed(1)}x leverage (not hardcoded 1x)`);
    console.log(`   - Risk assessment: ${testLeverageResult.riskAssessment}`);
    console.log(`   - Decision logic: ${shouldTrade.decision ? 'WOULD TRADE' : 'WOULD NOT TRADE'}`);
    console.log(`   - Confidence-based SL: ${mockAnalysis.confidence >= 80 ? '1.5%' : mockAnalysis.confidence >= 60 ? '2%' : '3%'}`);
    
  } catch (error) {
    console.error('❌ Test Error:', error.message);
    console.error('Stack:', error.stack);
  }
}

// Run the test
testAILeverageDirectly().catch(console.error);
