#!/usr/bin/env node

const { execSync } = require('child_process');

console.log('🧪 Testing Robust Cleanup System');
console.log('================================');

// Test 1: Check for any existing Chromium processes
console.log('\n1. Checking existing Chromium processes...');
try {
  const processes = execSync('pgrep -f "chrome|chromium" | wc -l', { encoding: 'utf8' }).trim();
  console.log(`   Found ${processes} existing Chromium processes`);
} catch (error) {
  console.log('   No existing Chromium processes found');
}

// Test 2: Check cleanup service files exist
console.log('\n2. Verifying cleanup service files...');
const fs = require('fs');
const files = [
  'lib/enhanced-screenshot-robust.ts',
  'lib/automated-cleanup-service.ts',
  'lib/aggressive-cleanup.ts'
];

files.forEach(file => {
  if (fs.existsSync(file)) {
    console.log(`   ✅ ${file} exists`);
  } else {
    console.log(`   ❌ ${file} missing`);
  }
});

// Test 3: Test API endpoint accessibility
console.log('\n3. Testing enhanced screenshot API...');
try {
  const http = require('http');
  const options = {
    hostname: 'localhost',
    port: 9001,
    path: '/api/enhanced-screenshot',
    method: 'GET',
    timeout: 5000
  };

  const req = http.request(options, (res) => {
    console.log(`   ✅ API accessible, status: ${res.statusCode}`);
  });

  req.on('error', (e) => {
    console.log(`   ⚠️  API error: ${e.message}`);
  });

  req.on('timeout', () => {
    console.log('   ⚠️  API timeout');
    req.abort();
  });

  req.end();
} catch (error) {
  console.log(`   ❌ API test failed: ${error.message}`);
}

// Test 4: Check Docker container status
console.log('\n4. Checking Docker container status...');
try {
  const containerStatus = execSync('docker ps --filter "name=trading_bot" --format "table {{.Names}}\t{{.Status}}"', { encoding: 'utf8' });
  console.log('   Container status:');
  console.log(`   ${containerStatus.trim()}`);
} catch (error) {
  console.log(`   ❌ Docker check failed: ${error.message}`);
}

console.log('\n✅ Cleanup system test completed!');
console.log('\n📋 Summary:');
console.log('   - Container rebuilt with new cleanup system');
console.log('   - Automation-v2 page restored with balance slider');
console.log('   - Enhanced screenshot service with finally blocks');
console.log('   - Background cleanup monitoring service');
console.log('   - Git changes committed and persistent');
