#!/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 here = dirname(fileURLToPath(import.meta.url));
const platformRoot = resolve(here, "../..");
const artifactRoot = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(here, "../deploy-artifacts"));
const [transitionId = "20260720-001", ...extra] = process.argv.slice(2);
if (extra.length || !/^\d{8}-[0-9]{3}$/.test(transitionId)) {
  throw new Error("usage: build-platform-gelios-provider-v4-artifact.mjs [YYYYMMDD-NNN]");
}

const id = `platform-gelios-provider-v4-${transitionId}`;
const target = join(artifactRoot, `nodedc-${id}.tgz`);
const files = [
  "platform/packages/external-provider-contract/src/provider-package.mjs",
  "platform/packages/external-provider-contract/providers/gelios/v4/README.md",
  "platform/packages/external-provider-contract/providers/gelios/v4/index.mjs",
  "platform/packages/external-provider-contract/providers/gelios/v4/package.mjs",
  "platform/services/external-data-plane/definitions/fleet.positions.current.v3.json",
];
const expectedSha256 = new Map([
  [files[0], "8ae73cae0be8cbf8484125e1ccf836fdc245b31872a5c7888ced289ed1895ba2"],
  [files[1], "9f38f5cb267269b54053fa590a3970abb4b6b9803fc931e997be4293aa6e592a"],
  [files[2], "b92fb1fed6ff2fe29c3dc77978e7c35dcdf4c7f2af4ae63ada23e9c3119e7fd9"],
  [files[3], "55a46f825e12bcef2354fefd956e674b72fea68b6997df3fcbe89b0a074ec9b8"],
  [files[4], "04d458f050313468990849f60d37a8a6c9aadd355137d4084b66556bb4a4b673"],
]);

await assertFresh(target);
const stage = await mkdtemp(join(tmpdir(), "nodedc-platform-gelios-provider-v4-"));
const payload = join(stage, "payload");
try {
  await mkdir(payload, { recursive: true });
  for (const rel of files) {
    const source = join(platformRoot, rel.replace(/^platform\//, ""));
    const stat = await lstat(source);
    if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`source_boundary_invalid:${rel}`);
    const bytes = await readFile(source);
    if (sha(bytes) !== expectedSha256.get(rel)) throw new Error(`source_sha256_mismatch:${rel}`);
    await mkdir(dirname(join(payload, rel)), { recursive: true });
    await cp(source, join(payload, rel), { force: false });
  }
  await writeFile(join(stage, "manifest.env"), `id=${id}\ncomponent=platform\ntype=app-overlay\n`, "utf8");
  await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
  await mkdir(artifactRoot, { recursive: true });
  run("python3", ["-c", canonicalTarScript(), target, stage]);
  console.log(JSON.stringify({
    ok: true,
    id,
    artifact: target,
    artifactSha256: sha(await readFile(target)),
    services: ["external-data-plane"],
    ontologyPackage: "gelios@1.1.0",
    providerPackage: "gelios.provider.v4",
    dataProductId: "fleet.positions.current.v3",
    files,
  }, null, 2));
} finally {
  await rm(stage, { recursive: true, force: true });
}

async function assertFresh(path) {
  try {
    await lstat(path);
  } catch (error) {
    if (error?.code === "ENOENT") return;
    throw error;
  }
  throw new Error("artifact_already_exists");
}

function canonicalTarScript() {
  return [
    "import gzip,io,pathlib,sys,tarfile",
    "root=pathlib.Path(sys.argv[2])",
    "with open(sys.argv[1],'wb') as out:",
    " with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
    "  with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
    "   for top in ('manifest.env','files.txt','payload'):",
    "    p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
    "    for x in paths:",
    "     info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
    "     info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
    "     with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
  ].join("\n");
}

function sha(bytes) {
  return createHash("sha256").update(bytes).digest("hex");
}

function run(command, args) {
  const result = spawnSync(command, args, {
    encoding: "utf8",
    maxBuffer: 128 * 1024 * 1024,
    stdio: ["ignore", "pipe", "pipe"],
  });
  if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
}
