#!/usr/bin/env node

/**
 * Test script to verify the automation fixes
 * - Ensures stopped state is respected
 * - Verifies intervals work correctly
 * - Tests position-aware logic
 */

async function testAutomationFixes() {
  console.log('🧪 Testing Automation Fixes');
  console.log('===========================');
  
  const baseUrl = 'http://localhost:9001';
  
  // Test 1: Verify automation is stopped
  console.log('\n1️⃣  Testing initial stopped state...');
  const statusResponse = await fetch(`${baseUrl}/api/automation/status`);
  const status = await statusResponse.json();
  
  if (status.status.isActive === false) {
    console.log('✅ Automation properly shows as inactive');
  } else {
    console.log('❌ ISSUE: Automation still shows as active!');
    return;
  }
  
  // Test 2: Check if position detection works
  console.log('\n2️⃣  Testing position detection...');
  const positionsResponse = await fetch(`${baseUrl}/api/drift/positions`);
  const positions = await positionsResponse.json();
  
  const hasPositions = positions && positions.length > 0;
  console.log(`📊 Current positions: ${hasPositions ? positions.length : 0}`);
  
  if (hasPositions) {
    console.log('📊 Positions detected - automation should prevent auto-restart');
    
    // Test 3: Try to start automation with positions (should be prevented)
    console.log('\n3️⃣  Testing start prevention with positions...');
    const startResponse = await fetch(`${baseUrl}/api/automation/start`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        userId: 'test-user',
        mode: 'SIMULATION',
        symbol: 'SOLUSD',
        timeframe: '5',
        selectedTimeframes: ['5', '15', '30'],
        tradingAmount: 100,
        maxLeverage: 3,
        maxDailyTrades: 5,
        riskPercentage: 2
      })
    });
    
    const startResult = await startResponse.json();
    console.log(`🔄 Start attempt result: ${startResult.success ? 'STARTED' : 'PREVENTED'}`);
    
    if (!startResult.success && startResult.message && startResult.message.includes('positions')) {
      console.log('✅ Correctly prevented start due to open positions');
    } else if (startResult.success) {
      console.log('⚠️  WARNING: Automation started despite positions (checking if position-aware mode)');
      
      // Wait a bit and check if it's doing constant analysis
      console.log('⏱️  Waiting 30 seconds to check for constant analysis...');
      await new Promise(resolve => setTimeout(resolve, 30000));
      
      // Stop it
      await fetch(`${baseUrl}/api/automation/stop`, { method: 'POST' });
      console.log('🛑 Stopped automation for testing');
    }
  } else {
    console.log('📊 No positions detected - normal automation behavior expected');
  }
  
  // Test 4: Monitor for 30 seconds to ensure no automatic analysis
  console.log('\n4️⃣  Monitoring for 30 seconds to ensure no automatic analysis...');
  
  let analysisDetected = false;
  const startTime = Date.now();
  
  while (Date.now() - startTime < 30000) {
    // Check logs for any analysis activity
    try {
      const logCheck = await fetch(`${baseUrl}/api/health`);
      // If this were doing analysis, we'd see heavy load
      await new Promise(resolve => setTimeout(resolve, 5000));
      process.stdout.write('.');
    } catch (error) {
      // Container might be under heavy analysis load
      analysisDetected = true;
      break;
    }
  }
  
  console.log('\n');
  if (!analysisDetected) {
    console.log('✅ No automatic analysis detected - respects stopped state');
  } else {
    console.log('❌ ISSUE: Automatic analysis still running despite stopped state');
  }
  
  // Final verification
  console.log('\n🎯 Final Status Check...');
  const finalStatus = await fetch(`${baseUrl}/api/automation/status`);
  const finalResult = await finalStatus.json();
  
  console.log(`📊 Final automation state: ${finalResult.status.isActive ? 'ACTIVE' : 'INACTIVE'}`);
  
  if (!finalResult.status.isActive) {
    console.log('\n🎉 SUCCESS: All automation fixes working correctly!');
    console.log('✅ Stopped state is respected');
    console.log('✅ No constant analysis loops');
    console.log('✅ Position-aware logic implemented');
  } else {
    console.log('\n❌ ISSUE: Automation still showing as active');
  }
}

if (require.main === module) {
  testAutomationFixes().catch(console.error);
}
