#!/usr/bin/env node
// Progressive package loading test
// Loads packages one by one to identify which causes timeout

const http = require('http');

// Track what we've loaded
const loadStatus = {
  http: 'OK - Built-in module',
  express: 'Not tested',
  cors: 'Not tested',
  dotenv: 'Not tested',
  canvas: 'Not tested',
  sharp: 'Not tested'
};

// Try loading Express
console.log('Testing Express...');
let express;
try {
  express = require('express');
  loadStatus.express = 'OK - Loaded successfully';
  console.log('✅ Express loaded');
} catch (e) {
  loadStatus.express = 'FAILED: ' + e.message;
  console.log('❌ Express failed:', e.message);
}

// Try loading cors
console.log('Testing cors...');
try {
  require('cors');
  loadStatus.cors = 'OK - Loaded successfully';
  console.log('✅ cors loaded');
} catch (e) {
  loadStatus.cors = 'FAILED: ' + e.message;
  console.log('❌ cors failed:', e.message);
}

// Try loading dotenv
console.log('Testing dotenv...');
try {
  require('dotenv');
  loadStatus.dotenv = 'OK - Loaded successfully';
  console.log('✅ dotenv loaded');
} catch (e) {
  loadStatus.dotenv = 'FAILED: ' + e.message;
  console.log('❌ dotenv failed:', e.message);
}

// DO NOT load canvas or sharp yet - they'll likely cause timeout
// We'll test them via route

console.log('Creating server...');

// Create server using Express if available, otherwise http
let app;
if (express) {
  app = express();

  app.get('/', (req, res) => {
    res.send(`
      <!DOCTYPE html>
      <html>
      <head><title>Progressive Test</title></head>
      <body style="padding: 40px; font-family: Arial; background: #f0f0f0;">
        <h1 style="color: green;">✅ Express Works!</h1>
        <h2>Package Load Status:</h2>
        <div style="background: white; padding: 20px; border-radius: 5px;">
          ${Object.entries(loadStatus).map(([pkg, status]) =>
            `<p><strong>${pkg}:</strong> ${status}</p>`
          ).join('')}
        </div>
        <hr>
        <h3>Test Heavy Modules (may timeout):</h3>
        <p><a href="/test-canvas">⚠️ Test Canvas (RISKY)</a> - May hang the server</p>
        <p><a href="/test-sharp">⚠️ Test Sharp (RISKY)</a> - May hang the server</p>
        <hr>
        <p><strong>Node.js:</strong> ${process.version}</p>
        <p><strong>PID:</strong> ${process.pid}</p>
      </body>
      </html>
    `);
  });

  app.get('/test-canvas', (req, res) => {
    console.log('Attempting to load canvas...');
    try {
      const canvas = require('canvas');
      res.json({
        status: 'SUCCESS',
        message: 'Canvas loaded successfully!',
        canvas: 'OK'
      });
    } catch (e) {
      res.json({
        status: 'FAILED',
        message: e.message,
        stack: e.stack
      });
    }
  });

  app.get('/test-sharp', (req, res) => {
    console.log('Attempting to load sharp...');
    try {
      const sharp = require('sharp');
      res.json({
        status: 'SUCCESS',
        message: 'Sharp loaded successfully!',
        sharp: 'OK'
      });
    } catch (e) {
      res.json({
        status: 'FAILED',
        message: e.message,
        stack: e.stack
      });
    }
  });

  // Export for Passenger - don't call listen()
  module.exports = app;

} else {
  // Fallback to http if Express failed
  const server = http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(`
      <h1>Express Failed to Load</h1>
      <p>Error: ${loadStatus.express}</p>
      <p>Falling back to basic HTTP server</p>
    `);
  });

  // Export server for Passenger
  module.exports = server;
}
