import { spawnSync } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const appRoot = path.resolve(__dirname, "..");
const repoRoot = path.resolve(appRoot, "..");

const sidecarProject = path.join(
  repoRoot,
  "Journal.Sidecar",
  "Journal.Sidecar.csproj",
);
const publishOutputDir = path.join(repoRoot, "output");
const tauriBinDir = path.join(appRoot, "src-tauri", "bin");

function runtimeForCurrentPlatform() {
  const arch = process.arch;
  if (process.platform === "win32") {
    if (arch === "arm64") return "win-arm64";
    return "win-x64";
  }
  if (process.platform === "linux") {
    if (arch === "arm64") return "linux-arm64";
    return "linux-x64";
  }
  if (process.platform === "darwin") {
    if (arch === "arm64") return "osx-arm64";
    return "osx-x64";
  }
  throw new Error(
    `Unsupported platform '${process.platform}' for sidecar publish.`,
  );
}

function sidecarFileName() {
  return process.platform === "win32"
    ? "Journal.Sidecar.exe"
    : "Journal.Sidecar";
}

function publishProject(projectPath, runtime) {
  const publishArgs = [
    "publish",
    projectPath,
    "-c",
    "Release",
    "-r",
    runtime,
    "--self-contained",
    "-p:PublishSingleFile=true",
    "-p:IncludeNativeLibrariesForSelfExtract=true",
    "-p:IncludeAllContentForSelfExtract=true",
    "-p:RestoreIgnoreFailedSources=true",
    "-p:NuGetAudit=false",
    "-o",
    publishOutputDir,
  ];

  const publish = spawnSync("dotnet", publishArgs, {
    cwd: repoRoot,
    stdio: "inherit",
  });

  if (publish.error) {
    throw publish.error;
  }
  if (publish.status !== 0) {
    process.exit(publish.status ?? 1);
  }
}

function stageBinary(fileName) {
  const publishedBinary = path.join(publishOutputDir, fileName);
  const bundledBinary = path.join(tauriBinDir, fileName);

  if (!existsSync(publishedBinary)) {
    throw new Error(`Published binary not found: ${publishedBinary}`);
  }

  mkdirSync(tauriBinDir, { recursive: true });
  copyFileSync(publishedBinary, bundledBinary);
  console.log(`Staged binary for Tauri: ${bundledBinary}`);
}

const runtime = runtimeForCurrentPlatform();
const sidecarName = sidecarFileName();

console.log(
  `Publishing sidecar for ${process.platform}/${process.arch} (${runtime})...`,
);

console.log("Publishing Journal.Sidecar...");
publishProject(sidecarProject, runtime);
stageBinary(sidecarName);
