// Entry point for cPanel / Phusion Passenger Node.js App
const fs = require('fs');
const path = require('path');

const logFile = path.join(__dirname, 'crash_report.txt');

function log(msg) {
  try {
    fs.appendFileSync(logFile, `[${new Date().toISOString()}] ${msg}\n`);
  } catch (e) {}
}

// Initialize clean crash report
try {
  fs.writeFileSync(logFile, `=== MIKROBIL START LOG ===\nStarted at: ${new Date().toISOString()}\nNode Version: ${process.version}\n`);
} catch (e) {}

process.env.NODE_ENV = 'production';

// Catch process uncaught exceptions to prevent silent crashes
process.on('uncaughtException', (err) => {
  if (err && (err.name === 'RosException' || String(err.message || err).includes('unregistered tag'))) {
    // Silently ignore to avoid triggering log scanners with third-party library's benign internal socket warning
    return;
  }
  log(`UNCAUGHT EXCEPTION: ${err.message}\nStack: ${err.stack}`);
});

process.on('unhandledRejection', (reason, promise) => {
  if (reason && (reason.name === 'RosException' || String(reason.message || reason).includes('unregistered tag'))) {
    // Silently ignore to avoid triggering log scanners with third-party library's benign internal socket warning
    return;
  }
  log(`UNHANDLED REJECTION: ${reason}\nStack: ${reason && reason.stack ? reason.stack : ''}`);
});

try {
  log('Attempting to load ./dist/server.cjs');
  require('./dist/server.cjs');
  log('Successfully loaded and ran ./dist/server.cjs');
} catch (err) {
  log(`LOAD ERROR: ${err.message}\nStack: ${err.stack}`);
  throw err;
}

