"use strict";

const path = require("path");
const { spawn } = require("child_process");
const fs = require("fs-extra");
const { ensureLatest } = require("./update");

async function installDependencies() {
  return new Promise((resolve, reject) => {
    const binary = process.platform === "win32" ? "npm.cmd" : "npm";
    // Skip dev dependencies on production devices (Raspberry Pi) unless explicitly requested.
    const args = ["install", "--omit=dev"];
    if (process.env.PI_INSTALL_DEV === "1") {
      args.pop(); // remove --omit=dev
    }
    const child = spawn(binary, args, {
      cwd: path.resolve(__dirname, ".."),
      stdio: "inherit",
    });

    child.on("exit", (code) => {
      if (code === 0) {
        resolve();
      } else {
        reject(new Error(`npm install exited with code ${code}`));
      }
    });
  });
}

async function launchElectron(electronArgs) {
  const electronPath = require("electron");
  const child = spawn(electronPath, ["."].concat(electronArgs), {
    cwd: path.resolve(__dirname, ".."),
    stdio: "inherit",
    env: process.env,
  });

  child.on("exit", (code) => {
    process.exit(code ?? 0);
  });

  child.on("error", (error) => {
    console.error("[start] Failed to launch Electron:", error);
    process.exitCode = 1;
  });
}

async function main() {
  const args = process.argv.slice(2);
  const electronArgs = [];

  for (const arg of args) {
    if (arg === "--debug") {
      process.env.ELECTRON_ENABLE_LOGGING = "1";
      continue;
    }

    electronArgs.push(arg);
  }

  if (!(await fs.pathExists(path.join(__dirname, "update.js")))) {
    console.warn(
      "[start] Update script not found. Launching Electron without update check."
    );
    await launchElectron(electronArgs);
    return;
  }

  let updateResult;

  try {
    updateResult = await ensureLatest();
  } catch (error) {
    console.warn(
      `[start] Update check failed with ${error.message}. Continuing with existing version.`
    );
  }

  if (updateResult && updateResult.updated) {
    console.log(
      `[start] Updated application to version ${updateResult.targetVersion}.`
    );

    if (updateResult.requiresInstall) {
      console.log("[start] Installing dependencies after update...");
      try {
        await installDependencies();
      } catch (error) {
        console.error("[start] Failed to install dependencies:", error.message);
        process.exitCode = 1;
        return;
      }
    }
  }

  await launchElectron(electronArgs);
}

main().catch((error) => {
  console.error("[start] Unexpected error:", error);
  process.exitCode = 1;
});
