#!/usr/bin/env node

const http = require('http');
const services = [
  { name: 'Data Ingestion', port: 2001 },
  { name: 'Data Pipeline', port: 2002 },
  { name: 'Web API', port: 2003 },
];

console.log('🏥 Stock Bot Health Check\n');

async function checkService(service) {
  return new Promise((resolve) => {
    const options = {
      hostname: 'localhost',
      port: service.port,
      path: '/health',
      method: 'GET',
      timeout: 5000,
    };

    const req = http.request(options, (res) => {
      if (res.statusCode === 200) {
        resolve({ ...service, status: '✅ Healthy', code: res.statusCode });
      } else {
        resolve({ ...service, status: '⚠️  Unhealthy', code: res.statusCode });
      }
    });

    req.on('error', (err) => {
      resolve({ ...service, status: '❌ Offline', error: err.message });
    });

    req.on('timeout', () => {
      req.destroy();
      resolve({ ...service, status: '⏱️  Timeout', error: 'Request timed out' });
    });

    req.end();
  });
}

async function checkAllServices() {
  const results = await Promise.all(services.map(checkService));
  
  results.forEach((result) => {
    console.log(`${result.name.padEnd(15)} ${result.status}`);
    if (result.error) {
      console.log(`                ${result.error}`);
    }
  });

  const allHealthy = results.every(r => r.status === '✅ Healthy');
  
  console.log('\n' + (allHealthy ? '✅ All services are healthy!' : '⚠️  Some services need attention'));
  
  process.exit(allHealthy ? 0 : 1);
}

checkAllServices();