#!/usr/bin/env node

import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { copyFile, 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 artifactDir = resolve(
  process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"),
);
const [patchId = "external-data-plane-unit-contacts-20260724-014", ...extra] =
  process.argv.slice(2);

if (extra.length || !/^external-data-plane-unit-contacts-\d{8}-\d{3}$/.test(patchId)) {
  throw new Error(
    "usage: build-external-data-plane-unit-contacts-artifact.mjs "
      + "[external-data-plane-unit-contacts-YYYYMMDD-NNN]",
  );
}

const sourceRelative =
  "services/external-data-plane/definitions/fleet.units.contacts.current.v1.json";
const destinationRelative = `platform/${sourceRelative}`;
const artifact = join(artifactDir, `nodedc-${patchId}.tgz`);
const checksum = `${artifact}.sha256`;
const stage = await mkdtemp(join(tmpdir(), "nodedc-edp-unit-contacts-artifact-"));

await assertFresh(artifact);
await assertDefinition();

try {
  const payloadFile = join(stage, "payload", destinationRelative);
  await mkdir(dirname(payloadFile), { recursive: true });
  await copyFile(join(platformRoot, sourceRelative), payloadFile);
  await writeFile(
    join(stage, "manifest.env"),
    `id=${patchId}\ncomponent=platform\ntype=app-overlay\n`,
    "utf8",
  );
  await writeFile(join(stage, "files.txt"), `${destinationRelative}\n`, "utf8");
  await mkdir(artifactDir, { recursive: true });
  run("python3", ["-c", canonicalTarScript(), artifact, stage]);
  const sha256 = digest(await readFile(artifact));
  await writeFile(checksum, `${sha256}  ${artifact.split("/").at(-1)}\n`, "utf8");
  console.log(JSON.stringify({
    ok: true,
    patchId,
    artifact,
    checksum,
    sha256,
    services: ["external-data-plane"],
    files: [destinationRelative],
  }, null, 2));
} finally {
  await rm(stage, { recursive: true, force: true });
}

async function assertDefinition() {
  const definition = JSON.parse(
    await readFile(join(platformRoot, sourceRelative), "utf8"),
  );
  if (
    definition?.id !== "fleet.units.contacts.current.v1"
    || definition?.version !== "1.0.0"
    || definition?.ontologyRevision !== "ontology.map.moving_object.v3"
    || JSON.stringify(definition?.semanticTypes)
      !== JSON.stringify(["map.moving_object"])
    || JSON.stringify(definition?.fields) !== JSON.stringify([
      "device_imei",
      "device_phone_primary",
      "device_phone_secondary",
      "display_name",
      "provider_creator_login",
    ])
  ) {
    throw new Error("unit_contacts_definition_contract_invalid");
  }
  if (
    /(token|secret|password|authorization|decrypt|raw_provider_payload)/i.test(
      JSON.stringify(definition),
    )
  ) {
    throw new Error("unit_contacts_definition_secret_boundary_violation");
  }
}

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 digest(value) {
  return createHash("sha256").update(value).digest("hex");
}

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