import { existsSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";

const executableName = process.platform === "win32" ? "dotnet.exe" : "dotnet";
const candidates = [
  process.env.DOTNET_HOST_PATH,
  process.env.DOTNET_ROOT ? path.join(process.env.DOTNET_ROOT, executableName) : undefined,
  path.join(os.homedir(), ".dotnet", executableName),
].filter(Boolean);

const dotnet = candidates.find((candidate) => existsSync(candidate)) ?? "dotnet";
const dotnetDirectory = path.dirname(dotnet);
const childEnv = {
  ...process.env,
  DOTNET_HOST_PATH: dotnet,
  PATH: dotnet === "dotnet"
    ? process.env.PATH
    : `${dotnetDirectory}${path.delimiter}${process.env.PATH ?? ""}`,
};

function run(command, args) {
  const result = spawnSync(command, args, { cwd: process.cwd(), env: childEnv, stdio: "inherit", shell: false });
  if (result.error) {
    console.error(`Unable to start ${command}: ${result.error.message}`);
    process.exit(1);
  }
  if (result.status !== 0) process.exit(result.status ?? 1);
}

run(dotnet, ["build", "../JobTrackerApi/JobTrackerApi.csproj", "--configuration", "Release"]);
run(process.execPath, [path.resolve("node_modules/@playwright/test/cli.js"), "test", ...process.argv.slice(2)]);
