#!/usr/bin/env node
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { cp, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";

const scriptDir = dirname(fileURLToPath(import.meta.url));
const platformRoot = resolve(scriptDir, "../..");
const launcherRoot = resolve(platformRoot, "../../data/nodedc_launcher");
const artifactDir = resolve(scriptDir, "../deploy-artifacts");
const patchId = process.argv[2] || "module-foundry-hub-registration-20260714-001";
const profile = process.argv[3] || "registration";

if (!/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) {
  throw new Error("patch_id_must_contain_only_letters_digits_dot_underscore_hyphen");
}

// DCPLATFORM-21: the production runner overlays this payload onto the existing
// Launcher source and recreates only the `launcher` service.  Keep corrective
// patches to their exact reviewed file set instead of re-sending unrelated
// registration sources.
const registrationFiles = [
  "server/authentik-sync.mjs",
  "server/control-plane-store.mjs",
  "server/dev-server.mjs",
  "src/entities/service/types.ts",
];

const filesByProfile = {
  registration: registrationFiles,
  "handoff-fix": ["server/dev-server.mjs"],
};

const files = filesByProfile[profile];
if (!files) {
  throw new Error(`unknown_profile:${profile}`);
}

const stage = await mkdtemp(join(tmpdir(), "nodedc-launcher-foundry-artifact-"));
const payloadRoot = join(stage, "payload");
const artifact = join(artifactDir, `launcher-${patchId}.tgz`);
const checksum = `${artifact}.sha256`;

try {
  await mkdir(payloadRoot, { recursive: true });

  for (const relativePath of files) {
    const source = resolve(launcherRoot, relativePath);
    const destination = join(payloadRoot, relativePath);
    const stat = await lstat(source);
    if (!stat.isFile() || stat.isSymbolicLink()) {
      throw new Error(`source_file_rejected:${relativePath}`);
    }
    await mkdir(dirname(destination), { recursive: true });
    await cp(source, destination, { force: true, verbatimSymlinks: true });
  }

  await writeFile(
    join(stage, "manifest.env"),
    `id=${patchId}\ncomponent=launcher\ntype=app-overlay\n`,
    "utf8",
  );
  await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
  await mkdir(artifactDir, { recursive: true });

  // macOS bsdtar may emit AppleDouble `._*` sidecars. DCPLATFORM-21 rejects
  // them, therefore create a data-only POSIX archive through stdlib tarfile.
  const tar = spawnSync("python3", ["-c", [
    "import sys, tarfile",
    "with tarfile.open(sys.argv[1], 'w:gz', format=tarfile.PAX_FORMAT) as archive:",
    "    [archive.add(name, arcname=name, recursive=True) for name in ('manifest.env', 'files.txt', 'payload')]",
  ].join("\n"), artifact], {
    cwd: stage,
    encoding: "utf8",
  });
  if (tar.status !== 0) throw new Error(`tar_failed:${tar.stderr || tar.stdout}`);

  const digest = createHash("sha256").update(await readFile(artifact)).digest("hex");
  await writeFile(checksum, `${digest}  ${artifact.split("/").at(-1)}\n`, "utf8");
  console.log(JSON.stringify({ ok: true, patchId, profile, artifact, checksum, sha256: digest, files }, null, 2));
} finally {
  await rm(stage, { recursive: true, force: true });
}
