// Test the enhanced automation system for scalping re-entry
const SimpleAutomation = require('./lib/simple-automation.js');

async function testScalpingReEntry() {
  console.log('🧪 TESTING: Enhanced scalping automation for immediate re-entry');
  
  try {
    // Create automation instance configured for scalping
    const automation = new SimpleAutomation();
    
    // Configure for 5-minute scalping (aggressive re-entry)
    const config = {
      symbol: 'SOLUSD',
      selectedTimeframes: ['5m', '15m'], // Scalping timeframes
      enableTrading: true,
      mode: 'LIVE',
      layouts: ['ai', 'diy']
    };
    
    automation.updateConfig(config);
    
    console.log('\n📊 CONFIGURATION:');
    console.log('Symbol:', config.symbol);
    console.log('Timeframes:', config.selectedTimeframes.join(', '));
    console.log('Trading Mode:', config.mode);
    
    // Test interval calculation for no position scenario
    console.log('\n🕐 TESTING INTERVAL CALCULATION:');
    const interval = await automation.getNextInterval();
    const intervalMinutes = interval / (60 * 1000);
    
    console.log(`⏰ Next analysis interval: ${intervalMinutes} minutes`);
    console.log(`🏃‍♂️ Scalping mode: ${intervalMinutes <= 5 ? 'ACTIVE' : 'STANDARD'}`);
    
    // Test position monitoring integration
    console.log('\n📍 TESTING POSITION MONITOR INTEGRATION:');
    
    const baseUrl = process.env.INTERNAL_API_URL || 'http://localhost:9001';
    const response = await fetch(`${baseUrl}/api/automation/position-monitor`);
    
    if (response.ok) {
      const data = await response.json();
      const hasPosition = data.monitor?.hasPosition;
      const recommendation = data.monitor?.recommendation;
      const activeOrders = data.monitor?.orphanedOrderCleanup?.summary?.activeOrders || 0;
      
      console.log(`Position Status: ${hasPosition ? 'ACTIVE' : 'NO POSITION'}`);
      console.log(`Monitor Recommendation: ${recommendation}`);
      console.log(`Active Orders: ${activeOrders}`);
      
      if (!hasPosition && recommendation === 'START_TRADING') {
        console.log('✅ CONDITION MET: No position + START_TRADING recommendation');
        console.log('🚀 SCALPING ACTION: System should immediately scan for new opportunities');
        console.log(`⚡ Expected interval: 2 minutes (actual: ${intervalMinutes} minutes)`);
      } else if (!hasPosition) {
        console.log('⚠️ NO POSITION: But recommendation is not START_TRADING');
        console.log('🔍 System should still scan more frequently for opportunities');
      } else {
        console.log('📊 POSITION EXISTS: Normal monitoring intervals apply');
      }
    }
    
    console.log('\n🎯 CONFIDENCE TESTING:');
    
    // Test confidence thresholds for scalping
    const mockAnalysis = {
      recommendation: 'BUY LONG',
      confidence: 67,
      reasoning: 'Mock analysis for testing confidence thresholds'
    };
    
    const shouldTrade = automation.shouldExecuteTrade(mockAnalysis);
    console.log(`Mock Analysis: ${mockAnalysis.recommendation} (${mockAnalysis.confidence}%)`);
    console.log(`Should Execute: ${shouldTrade ? 'YES' : 'NO'}`);
    console.log(`Scalping Advantage: Lower confidence threshold when no position exists`);
    
    console.log('\n✅ ENHANCED AUTOMATION FEATURES:');
    console.log('1. ✅ Immediate position monitor check each cycle');
    console.log('2. ✅ Automatic orphaned order cleanup before new entry');
    console.log('3. ✅ Ultra-fast 2-minute intervals for scalping when no position');
    console.log('4. ✅ Aggressive confidence thresholds (65-70%) for faster re-entry');
    console.log('5. ✅ Real-time position status integration');
    
  } catch (error) {
    console.error('❌ Test failed:', error.message);
  }
}

// Run the test
testScalpingReEntry();
