import { spawnSync } from "node:child_process";
import { existsSync, readdirSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";

const packageDir = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const initCwd = process.env.INIT_CWD && resolve(process.env.INIT_CWD);
const isGlobal =
  process.env.npm_config_global === "true" ||
  process.env.npm_config_location === "global";

if (
  process.env.MDL_SKIP_INIT === "1" ||
  isGlobal ||
  !initCwd ||
  initCwd === packageDir ||
  hasMdlProject(initCwd)
) {
  process.exit(0);
}

const wrapper = join(packageDir, "bin", "mdl.js");
const result = spawnSync(process.execPath, [wrapper, "init", "--quiet"], {
  cwd: initCwd,
  encoding: "utf8"
});

if (result.status === 0) {
  console.log("MDL project files are ready. Run `source bin/activate`, then `mdl serve`.");
  process.exit(0);
}

console.warn("MDL installed, but automatic project initialization did not finish.");
if (result.stdout.trim()) {
  console.warn(result.stdout.trim());
}
if (result.stderr.trim()) {
  console.warn(result.stderr.trim());
}

function hasMdlProject(root) {
  if (existsSync(join(root, "mdl.json"))) {
    return true;
  }

  const appsDir = join(root, "apps");
  if (!existsSync(appsDir)) {
    return false;
  }

  try {
    return readdirSync(appsDir, { withFileTypes: true }).some(
      (entry) => entry.isDirectory() && existsSync(join(appsDir, entry.name, "mdl.json"))
    );
  } catch {
    return false;
  }
}
