#!/usr/bin/env node

/**
 * Test script to validate the cleanup improvements
 * This will simulate the analysis workflow and verify cleanup occurs properly
 */

console.log('🧪 Testing cleanup improvements...')

async function testCleanupWorkflow() {
  try {
    console.log('\n1️⃣ Initial process check...')
    await checkProcesses()
    
    console.log('\n2️⃣ Running enhanced screenshot analysis...')
    const config = {
      symbol: 'BTCUSD',
      timeframe: '60',
      layouts: ['ai'],
      analyze: true
    }
    
    // Simulate API call
    const response = await fetch('http://localhost:3000/api/enhanced-screenshot', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(config)
    })
    
    const result = await response.json()
    console.log('📊 Analysis result:', {
      success: result.success,
      sessionId: result.sessionId,
      screenshots: result.screenshots?.length || 0,
      analysis: !!result.analysis
    })
    
    console.log('\n3️⃣ Waiting 10 seconds for cleanup to complete...')
    await new Promise(resolve => setTimeout(resolve, 10000))
    
    console.log('\n4️⃣ Checking processes after cleanup...')
    await checkProcesses()
    
    console.log('\n5️⃣ Checking system process monitoring endpoint...')
    const processResponse = await fetch('http://localhost:3000/api/system/processes')
    const processInfo = await processResponse.json()
    console.log('📊 Process monitoring:', processInfo)
    
    console.log('\n6️⃣ Running manual cleanup if needed...')
    const cleanupResponse = await fetch('http://localhost:3000/api/system/processes', {
      method: 'POST'
    })
    const cleanupResult = await cleanupResponse.json()
    console.log('🧹 Manual cleanup result:', cleanupResult)
    
    console.log('\n7️⃣ Final process check...')
    await checkProcesses()
    
    console.log('\n✅ Cleanup test completed!')
    
  } catch (error) {
    console.error('❌ Test failed:', error)
    process.exit(1)
  }
}

async function checkProcesses() {
  try {
    const { exec } = require('child_process')
    const { promisify } = require('util')
    const execAsync = promisify(exec)
    
    // Check for chromium processes
    try {
      const { stdout } = await execAsync('ps aux | grep -E "(chromium|chrome)" | grep -v grep | wc -l')
      const processCount = parseInt(stdout.trim()) || 0
      console.log(`🔍 Browser processes: ${processCount}`)
      
      if (processCount > 0) {
        const { stdout: details } = await execAsync('ps aux | grep -E "(chromium|chrome)" | grep -v grep')
        console.log('📋 Process details:')
        details.split('\n').forEach((line, index) => {
          if (line.trim()) {
            const parts = line.split(/\s+/)
            const pid = parts[1]
            const cpu = parts[2]
            const mem = parts[3]
            console.log(`  ${index + 1}. PID: ${pid}, CPU: ${cpu}%, MEM: ${mem}%`)
          }
        })
      }
    } catch (error) {
      console.log('✅ No browser processes found')
    }
    
    // Check memory usage
    try {
      const { stdout: memInfo } = await execAsync('free -h | head -2')
      console.log('💾 Memory:')
      memInfo.split('\n').forEach(line => {
        if (line.trim()) console.log(`  ${line}`)
      })
    } catch (error) {
      console.log('Warning: Could not get memory info')
    }
    
  } catch (error) {
    console.error('Error checking processes:', error)
  }
}

// Run the test
if (require.main === module) {
  testCleanupWorkflow()
}

module.exports = { testCleanupWorkflow, checkProcesses }
