#!/usr/bin/env node

// Test script for robust cleanup system
const { enhancedScreenshotService } = require('./lib/enhanced-screenshot-robust')
const { automatedCleanupService } = require('./lib/automated-cleanup-service')
const aggressiveCleanup = require('./lib/aggressive-cleanup').default

async function testRobustCleanup() {
  console.log('🧪 Testing robust cleanup system...')
  
  try {
    // Start cleanup services
    console.log('🚀 Starting cleanup services...')
    automatedCleanupService.start(10000) // Every 10 seconds for testing
    aggressiveCleanup.startPeriodicCleanup()
    
    // Test screenshot capture with cleanup
    console.log('\n📸 Testing screenshot capture with robust cleanup...')
    
    const config = {
      symbol: 'SOLUSD',
      timeframe: '240',
      layouts: ['ai'],
      analyze: false
    }
    
    console.log('🔧 Test config:', config)
    
    // Run a quick screenshot test
    const screenshots = await enhancedScreenshotService.captureWithLogin(config)
    
    if (screenshots.length > 0) {
      console.log('✅ Screenshot capture test successful:', screenshots.length, 'files')
    } else {
      console.warn('⚠️ No screenshots captured')
    }
    
    // Force cleanup test
    console.log('\n🧹 Testing force cleanup...')
    await enhancedScreenshotService.cleanup()
    await aggressiveCleanup.runPostAnalysisCleanup()
    
    console.log('✅ Force cleanup test completed')
    
    // Check process status
    console.log('\n🔍 Checking process status...')
    await aggressiveCleanup.getProcessInfo()
    
    console.log('\n✅ Robust cleanup test completed successfully')
    
  } catch (error) {
    console.error('❌ Test failed:', error)
    process.exit(1)
  } finally {
    // Always cleanup at the end
    console.log('\n🧹 Final cleanup...')
    try {
      automatedCleanupService.stop()
      aggressiveCleanup.stop()
      await enhancedScreenshotService.cleanup()
      await aggressiveCleanup.forceCleanup()
      console.log('✅ Final cleanup completed')
    } catch (cleanupError) {
      console.error('❌ Error in final cleanup:', cleanupError)
    }
    
    // Wait a moment before exit
    setTimeout(() => {
      console.log('👋 Test completed')
      process.exit(0)
    }, 2000)
  }
}

// Run test if script is executed directly
if (require.main === module) {
  testRobustCleanup().catch(error => {
    console.error('💥 Test script error:', error)
    process.exit(1)
  })
}

module.exports = { testRobustCleanup }
