import { spawnSync } from "node:child_process";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { getReleaseArch, isBundleCefEnabled } from "./release-artifact-utils.mjs";

const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const electrobunCli = path.join(
  rootDir,
  "node_modules/electrobun/src/cli/index.ts",
);

const buildEnv = process.env.ELECTROBUN_BUILD_ENV || "stable";
const targetArch = getReleaseArch(
  process.env.ELECTROBUN_TARGET_ARCH ||
    process.env.ELECTROBUN_FORCE_ARCH ||
    process.arch,
);
const bundleCef = isBundleCefEnabled();

const patchResult = spawnSync("bun", [path.join(rootDir, "scripts/patch-electrobun-src.mjs")], {
  cwd: rootDir,
  stdio: "inherit",
  env: process.env,
});

if (patchResult.status !== 0) {
  process.exit(patchResult.status ?? 1);
}

const macosEffectsResult = spawnSync(
  "bun",
  [path.join(rootDir, "scripts/build-macos-effects.mjs")],
  { cwd: rootDir, stdio: "inherit", env: process.env },
);

if (macosEffectsResult.status !== 0) {
  process.exit(macosEffectsResult.status ?? 1);
}

if (process.platform === "darwin") {
  const { validateMacosEffectsDylib, outFile } = await import(
    pathToFileURL(
      path.join(rootDir, "scripts/build-macos-effects.mjs"),
    ).href
  );

  if (!validateMacosEffectsDylib({ dylibPath: outFile })) {
    console.error(
      "run-electrobun-build: macOS window effects dylib is missing or invalid.",
    );
    process.exit(1);
  }
}

const ensureCoreEnv = {
  ...process.env,
  ELECTROBUN_TARGET_ARCH: targetArch,
  ELECTROBUN_FORCE_ARCH: targetArch,
};

const ensureCoreResult = spawnSync(
  "bun",
  [path.join(rootDir, "scripts/ensure-electrobun-core.mjs")],
  {
    cwd: rootDir,
    stdio: "inherit",
    env: ensureCoreEnv,
  },
);

if (ensureCoreResult.status !== 0) {
  process.exit(ensureCoreResult.status ?? 1);
}

const env = {
  ...process.env,
  ELECTROBUN_BUILD_ENV: buildEnv,
  ELECTROBUN_OS: "macos",
  ELECTROBUN_ARCH: targetArch,
  ELECTROBUN_FORCE_ARCH: targetArch,
  ELECTROBUN_TARGET_ARCH: targetArch,
  NODE_ENV: process.env.NODE_ENV || "production",
};

console.log(
  `run-electrobun-build: env=${buildEnv} os=macos arch=${targetArch} cef=${bundleCef} (host ${getReleaseArch(process.arch)})`,
);

const result = spawnSync(
  "bun",
  [electrobunCli, "build", `--env=${buildEnv}`],
  {
    cwd: rootDir,
    stdio: "inherit",
    env,
  },
);

if (result.status !== 0) {
  process.exit(result.status ?? 1);
}
