const path = require("path");
const { spawn } = require("child_process");
const { ensureRuntimeDependencies } = require("./src/services/dependency-manager");

const entry = path.join(__dirname, "src", "main.js");
const safeModeEntry = path.join(__dirname, "safe-mode.js");
const maxRestarts = Number(process.env.MAX_RESTARTS || 25);
const restartDelayMs = Number(process.env.RESTART_DELAY_MS || 1500);
const restartCodes = new Set([10, 100]);
const safeModeFlag = path.join(__dirname, "data", "recovery", "safe-mode.flag");

let restarts = 0;
let safeModeStarted = false;

function startSafeMode() {
  if (safeModeStarted) {
    return;
  }
  safeModeStarted = true;
  const child = spawn(process.execPath, [safeModeEntry], {
    stdio: "inherit",
    env: { ...process.env, SAFE_MODE: "1" }
  });
  child.on("exit", (code) => {
    safeModeStarted = false;
    if (code === 10) {
      restarts = 0;
      startChild();
    }
  });
}

function startChild() {
  if (process.env.LUMI_SKIP_DEPENDENCY_SYNC !== "1") {
    try {
      const dependencyResult = ensureRuntimeDependencies({ rootPath: __dirname });
      if (dependencyResult.installed) {
        console.log(`Lumi synchronized ${dependencyResult.issues.length} changed or missing runtime dependencies.`);
      }
      if (dependencyResult.optional_failed || dependencyResult.unresolved?.length) {
        console.warn("Lumi started without one or more optional integrations. Their settings pages will explain what is unavailable.");
      }
    } catch (error) {
      console.error(error.message);
      startSafeMode();
      return;
    }
  }
  const child = spawn(process.execPath, [entry], {
    stdio: "inherit",
    env: { ...process.env, BOT_WRAPPER: "1" }
  });

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

    const shouldRestart =
      restartCodes.has(code) || (code !== 0 && restarts < maxRestarts);

    if (code === 100) {
      startSafeMode();
      return;
    }

    if (!shouldRestart) {
      if (code && restarts >= maxRestarts) {
        startSafeMode();
        return;
      }
      process.exit(code || 0);
      return;
    }

    restarts += 1;
    setTimeout(startChild, restartDelayMs);
  });
}

if (
  process.env.LUMI_SAFE_MODE === "1" ||
  process.argv.includes("--safe-mode") ||
  require("fs").existsSync(safeModeFlag)
) {
  startSafeMode();
} else {
  startChild();
}
