const { fork } = require('child_process');
const path = require('path');

let child = null;
let stopping = false;
let restartCount = 0;

function startServer() {
  const startedAt = Date.now();
  child = fork(path.join(__dirname, 'server.js'), [], {
    env: process.env,
    stdio: 'inherit'
  });

  child.on('exit', (code, signal) => {
    child = null;
    if (stopping) return;
    if (Date.now() - startedAt > 60000) restartCount = 0;
    restartCount += 1;
    const delay = Math.min(10000, 1000 * restartCount);
    console.error(`[Supervisor] Server stopped (${signal || code}). Restarting in ${delay / 1000}s...`);
    setTimeout(startServer, delay);
  });
}

function stop() {
  stopping = true;
  if (child) child.kill('SIGTERM');
  setTimeout(() => process.exit(0), 1500).unref();
}

process.on('SIGINT', stop);
process.on('SIGTERM', stop);
startServer();
