import { appendFileSync, mkdirSync } from "node:fs";
import { dirname, resolve } from "node:path";

const serviceLogFile = process.env.LIVE_RUSH_COLLECTOR_LOG_FILE
  ? resolve(process.env.LIVE_RUSH_COLLECTOR_LOG_FILE)
  : null;

process.on("uncaughtException", (error) => {
  writeBootstrapLog(`uncaughtException ${formatError(error)}`);
  process.exit(1);
});

process.on("unhandledRejection", (error) => {
  writeBootstrapLog(`unhandledRejection ${formatError(error)}`);
  process.exit(1);
});

try {
  await import("./serve-live-data-collector-plugin.mjs");
} catch (error) {
  writeBootstrapLog(`startup import failed ${formatError(error)}`);
  console.error(error);
  process.exit(1);
}

function writeBootstrapLog(message) {
  if (!serviceLogFile) {
    return;
  }
  try {
    mkdirSync(dirname(serviceLogFile), { recursive: true });
    appendFileSync(serviceLogFile, `${new Date().toISOString()} ${message}\n`, "utf8");
  } catch {
    // Diagnostics must never hide the original startup failure.
  }
}

function formatError(error) {
  return error?.stack ?? error?.message ?? String(error);
}
