/**
 * Test AI Leverage Integration in Automation System
 * 
 * Tests that the automation system properly uses the AI leverage calculator
 * instead of hardcoded values.
 */

async function testAILeverageIntegration() {
  console.log('🧠 Testing AI Leverage Integration in Automation System...\n');

  // Test 1: Start automation with simulation mode
  console.log('📊 Test 1: Starting Automation with Simulation Mode');
  
  const startResponse = await fetch('http://localhost:9001/api/automation/simple/start', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      mode: 'SIMULATION',
      symbol: 'SOLUSD',
      timeframes: ['1h'],
      tradingAmount: 10,
      maxDailyTrades: 1
    })
  });
  
  const startResult = await startResponse.json();
  console.log('Start Result:', startResult);
  
  if (!startResult.success) {
    console.error('❌ Failed to start automation');
    return;
  }
  
  // Test 2: Trigger a fake analysis with BUY signal
  console.log('\n📊 Test 2: Triggering Mock Analysis with BUY Signal');
  
  // 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,
    signal: 'BUY'
  };
  
  // Manually trigger the automation analysis to test AI leverage calculation
  const baseUrl = 'http://localhost:9001';
  
  try {
    // First get the current automation status
    const statusResponse = await fetch(`${baseUrl}/api/automation/status`);
    const status = await statusResponse.json();
    console.log('Current Status:', {
      isActive: status.isActive,
      mode: status.mode,
      symbol: status.symbol
    });
    
    // Test the AI leverage calculator directly
    console.log('\n📊 Test 3: Testing AI Leverage Calculator Direct Call');
    
    const testLeverage = await testDirectAILeverageCall();
    console.log('Direct AI Leverage Test:', testLeverage);
    
    // Test 4: Check if automation can access account balance for AI calculation
    console.log('\n📊 Test 4: Testing Account Balance Access');
    
    const balanceResponse = await fetch(`${baseUrl}/api/balance`);
    if (balanceResponse.ok) {
      const balanceData = await balanceResponse.json();
      console.log('Account Balance for AI:', {
        accountValue: balanceData.accountValue,
        availableBalance: balanceData.availableBalance,
        success: balanceData.success
      });
    } else {
      console.log('⚠️ Balance API not accessible:', balanceResponse.status);
    }
    
    console.log('\n✅ AI Leverage Integration Test Completed!');
    console.log('🔍 Check automation logs for AI leverage calculations when trades are executed.');
    
  } catch (error) {
    console.error('❌ Test Error:', error.message);
  }
}

async function testDirectAILeverageCall() {
  try {
    // Test the AI leverage calculator with container environment
    const testCommand = `
      const { AILeverageCalculator } = require('./lib/ai-leverage-calculator.js');
      const result = AILeverageCalculator.calculateOptimalLeverage({
        accountValue: 244.45,
        availableBalance: 244.45,
        entryPrice: 185.50,
        stopLossPrice: 181.50, // 2.2% stop loss
        side: 'long',
        maxLeverageAllowed: 20,
        safetyBuffer: 0.10
      });
      console.log(JSON.stringify(result, null, 2));
    `;
    
    const response = await fetch('http://localhost:9001/api/test-leverage', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ testCommand })
    });
    
    if (!response.ok) {
      return { error: 'AI leverage test endpoint not available' };
    }
    
    return await response.json();
    
  } catch (error) {
    return { error: error.message };
  }
}

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