#!/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 { dirname, join, resolve } from "node:path";
import { tmpdir } from "node:os";
import { fileURLToPath } from "node:url";

const scriptDir = dirname(fileURLToPath(import.meta.url));
const platformRoot = resolve(scriptDir, "../..");
const artifactDir = resolve(scriptDir, "../deploy-artifacts");
const [patchId = "cesium-egress-20260715-012", ...extra] = process.argv.slice(2);
if (extra.length || !/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) throw new Error("usage: build-proxy-contur-artifact.mjs [patch-id]");

const files = [
  ["services/proxy-contur/Dockerfile", "Dockerfile"],
  ["services/proxy-contur/README.md", "README.md"],
  ["services/proxy-contur/docker-compose.yml", "docker-compose.yml"],
  ["services/proxy-contur/package.json", "package.json"],
  ["services/proxy-contur/server.js", "server.js"],
];
const stage = await mkdtemp(join(tmpdir(), "nodedc-proxy-contur-artifact-"));
const payload = join(stage, "payload");
const target = join(artifactDir, `nodedc-proxy-contur-${patchId}.tgz`);

try {
  await mkdir(payload, { recursive: true });
  for (const [source, destination] of files) await copySafe(resolve(platformRoot, source), join(payload, destination));
  await writeFile(join(stage, "manifest.env"), `id=${patchId}\ncomponent=proxy-contur\ntype=app-overlay\n`, "utf8");
  await writeFile(join(stage, "files.txt"), `${files.map(([, destination]) => destination).join("\n")}\n`, "utf8");
  await mkdir(artifactDir, { recursive: true });
  const tar = spawnSync("python3", ["-c", "import sys,tarfile\nwith tarfile.open(sys.argv[1],'w:gz',format=tarfile.PAX_FORMAT) as a:\n [a.add(n,arcname=n,recursive=True) for n in ('manifest.env','files.txt','payload')]", target], { cwd: stage, encoding: "utf8" });
  if (tar.status !== 0) throw new Error(`tar_failed:${tar.stderr || tar.stdout}`);
  console.log(JSON.stringify({ ok: true, patchId, artifact: target, sha256: createHash("sha256").update(await readFile(target)).digest("hex") }, null, 2));
} finally {
  await rm(stage, { recursive: true, force: true });
}

async function copySafe(source, destination) {
  const info = await lstat(source);
  if (info.isSymbolicLink() || !info.isFile()) throw new Error(`source_file_rejected:${source}`);
  await mkdir(dirname(destination), { recursive: true });
  await cp(source, destination, { force: true });
}
