#!/usr/bin/env node

// Require Node.js Version
const main = fileURLToPath(import.meta.url);
const root = path.dirname(main);
const parent = path.dirname(root);
const appPath = path.basename(parent) === "resources" ? path.dirname(parent) : root;
const pkg = JSON.parse(fs.readFileSync(`${root}/package.json`, "utf8"));
const startupMessages = [];
const nodeVer = process.versions.node;
startupMessages.push({level: "info", message: `Running on Node.js - Version ${nodeVer}`});
if ( nodeVer.split(".").shift() < pkg.release.node_version ) {
  console.error(`You are using Node.js version ${nodeVer}. Foundry Virtual Tabletop requires Node.js version`
    + ` ${pkg.release.node_version} or greater.`);
  process.exit(1);
}

// Import Initial Modules
import fs from "node:fs";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import path from "node:path";

// Bootstrap Foundry Commons
import "./common/primitives/_module.mjs";
import "./common/server.mjs";

/**
 * When running as a portable Electron build, relocate the Electron user data (cache, cookies, localStorage, etc.) into
 * the portable installation's own directory so that it does not share state with an installed copy of Foundry Virtual
 * Tabletop or with other portable copies extracted elsewhere. This must run before the Electron "ready" event is
 * emitted, as the sessionData path cannot be changed once the default session has been created.
 */
function configurePortableElectronData() {
  if ( !process.versions.electron ) return;
  const { app } = createRequire(import.meta.url)("electron");
  const dataPath = path.resolve(appPath, "..", "ElectronData");
  app.setPath("userData", dataPath);
  app.setPath("sessionData", dataPath);
}

/**
 * Invoke application initialization workflow
 * @returns {Promise<void>}
 */
(async function() {
  const isDebug = process.argv.includes("--debug") && fs.existsSync("./server");
  const isPortable = fs.existsSync(path.join(appPath, "portable.json"));
  if ( isPortable ) configurePortableElectronData();
  const init = await import(isDebug ? "./server/init.mjs" : "./dist/init.mjs");
  init.default({
    args: process.argv,
    root: root,
    messages: startupMessages,
    debug: isDebug,
    portable: isPortable
  });
})();
