const path = require("path");

const root = path.join(__dirname, "..");
const minimumNodeMajor = 18;

function fail(message, details = []) {
  console.error(`Verification preflight failed: ${message}`);
  for (const detail of details) console.error(`- ${detail}`);
  process.exitCode = 1;
}

const nodeMajor = Number.parseInt(process.versions.node.split(".")[0], 10);
if (!Number.isFinite(nodeMajor) || nodeMajor < minimumNodeMajor) {
  fail(`Lumi requires Node.js ${minimumNodeMajor} or newer; this process is ${process.version}.`, [
    "Install a supported Node.js release, reopen the terminal, then run npm install."
  ]);
} else {
  try {
    const BetterSqlite3 = require("better-sqlite3");
    const database = new BetterSqlite3(":memory:");
    database.prepare("SELECT 1 AS ready").get();
    database.close();
  } catch (error) {
    fail("The better-sqlite3 native module is missing or incompatible with this Node.js installation.", [
      `Node: ${process.version} (${process.platform} ${process.arch})`,
      `Module error: ${error.message}`,
      `From ${root}, run npm install. Do not use --ignore-scripts because native modules must be built or downloaded.`,
      "If Node.js was upgraded after installation, run npm rebuild better-sqlite3 or remove node_modules and run npm install again.",
      "On Linux, ensure a compiler toolchain and Python are available if no prebuilt binary exists."
    ]);
  }
}

if (!process.exitCode) {
  console.log(`Verification preflight passed: Node ${process.version}, better-sqlite3 loaded (${process.platform} ${process.arch}).`);
}
