const { spawn } = require('child_process');
const fs = require('fs');
const LOG = '/home/z/my-project/dev.log';

function log(msg) {
  const line = `[${new Date().toISOString()}] ${msg}\n`;
  fs.appendFileSync(LOG, line);
  console.log(line.trim());
}

function startServer() {
  log('Starting Next.js dev server...');
  
  const proc = spawn(process.execPath, ['node_modules/.bin/next', 'dev', '-p', '3000', '-H', '0.0.0.0'], {
    cwd: '/home/z/my-project',
    stdio: ['ignore', 'pipe', 'pipe'],
    detached: false
  });

  proc.stdout.on('data', (data) => fs.appendFileSync(LOG, data.toString()));
  proc.stderr.on('data', (data) => fs.appendFileSync(LOG, data.toString()));

  proc.on('exit', (code, signal) => {
    log(`Server exited: code=${code} signal=${signal}. Restarting in 5s...`);
    setTimeout(startServer, 5000);
  });

  proc.on('error', (err) => {
    log(`Server error: ${err.message}. Restarting in 5s...`);
    setTimeout(startServer, 5000);
  });

  log(`Server PID: ${proc.pid}`);
  return proc;
}

// Clear old log
fs.writeFileSync(LOG, '');
startServer();

// Keep process alive
setInterval(() => {
  log('Keep-alive ping');
}, 30000);
