import { execFileSync } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";

import { frozenRuntime } from "./frozen-versions.mjs";

if (
  process.platform !== frozenRuntime.os ||
  process.arch !== frozenRuntime.arch ||
  process.version.slice(1) !== frozenRuntime.node
) {
  throw new Error("The package smoke must run on the frozen win-x64 Node 24.13.0 runtime.");
}

const runtimeDirectory = resolve(".build/runtime");
const runtimeNode = resolve(runtimeDirectory, "node.exe");
mkdirSync(runtimeDirectory, { recursive: true });
copyFileSync(process.execPath, runtimeNode);

const nativeSmoke = JSON.parse(
  execFileSync(runtimeNode, ["scripts/native-smoke.mjs"], { encoding: "utf8" }).trim(),
);
const workerSmoke = JSON.parse(
  execFileSync(runtimeNode, ["scripts/worker-smoke.mjs"], { encoding: "utf8" }).trim(),
);
const supervisorChannelSmoke = JSON.parse(
  execFileSync(runtimeNode, ["scripts/supervisor-channel-smoke.mjs"], { encoding: "utf8" }).trim(),
);

execFileSync(
  "dotnet",
  [
    "restore",
    "supervisor/Dada.Supervisor.Tests/Dada.Supervisor.Tests.csproj",
    "--configfile",
    "NuGet.Config",
  ],
  { stdio: "inherit" },
);
execFileSync(
  "dotnet",
  [
    "build",
    "supervisor/Dada.Supervisor/Dada.Supervisor.csproj",
    "--configuration",
    "Release",
    "--no-restore",
  ],
  { stdio: "inherit" },
);
execFileSync(
  "dotnet",
  [
    "run",
    "--project",
    "supervisor/Dada.Supervisor.Tests/Dada.Supervisor.Tests.csproj",
    "--configuration",
    "Release",
    "--no-restore",
  ],
  { stdio: "inherit" },
);

const supervisorExecutable = resolve(
  "supervisor/Dada.Supervisor/bin/Release/net8.0-windows/Dada.Supervisor.exe",
);
if (!existsSync(supervisorExecutable)) {
  throw new Error("The .NET 8 WinForms supervisor executable was not produced.");
}

const result = {
  schema_version: "1.0",
  native: nativeSmoke,
  packagedNodeCandidate: {
    path: ".build/runtime/node.exe",
    version: frozenRuntime.node,
  },
  status: "passed",
  supervisor: {
    build: "passed",
    channel: supervisorChannelSmoke,
    lifecycle: "passed",
    target: frozenRuntime.dotnetTarget,
  },
  worker: workerSmoke,
};

const evidenceDirectory = process.env.DADA_EVIDENCE_DIR;
if (evidenceDirectory) {
  mkdirSync(evidenceDirectory, { recursive: true });
  writeFileSync(resolve(evidenceDirectory, "native-smoke.json"), `${JSON.stringify(result, null, 2)}\n`);
}

console.log(JSON.stringify(result, null, 2));
