#!/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 engineRoot = resolve(
  process.env.NODEDC_ENGINE_SOURCE_ROOT || resolve(platformRoot, "../NODEDC_ENGINE_INFRA"),
);
const artifactRoot = resolve(
  process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(here, "../deploy-artifacts"),
);
const [transitionId = "20260723-025", ...extra] = process.argv.slice(2);
if (extra.length || !/^\d{8}-[0-9]{3}$/.test(transitionId)) {
  throw new Error("usage: build-engine-provider-security-catalog-artifact.mjs [YYYYMMDD-NNN]");
}

const id = `engine-provider-security-catalog-${transitionId}`;
const target = join(artifactRoot, `nodedc-${id}.tgz`);
const file = "nodedc-source/server/assets/provider-packages/v1/catalog.json";
const expectedSha256 = "773335bb616a5c03eb2108c4f53ef092c02e75ee75f014511201bc12e2956b27";
const source = join(engineRoot, file);
const catalogBytes = await readFile(source);

await assertFresh(target);
if (sha(catalogBytes) !== expectedSha256) throw new Error(`pinned_catalog_sha256_mismatch:${file}`);

const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-provider-security-catalog-"));
const payload = join(stage, "payload");
try {
  await mkdir(dirname(join(payload, file)), { recursive: true });
  await cp(source, join(payload, file), { force: false });
  await writeFile(join(stage, "manifest.env"), `id=${id}\ncomponent=engine\ntype=app-overlay\n`, "utf8");
  await writeFile(join(stage, "files.txt"), `${file}\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: ["nodedc-backend"],
    providerPackage: "gelios.provider.v8",
    providerCredential: "ndcProviderRotatingAccessApi",
    endpoint: "https://api.geliospro.com/api/v1/units?incltrip=true&inclcntrs=true&inclsnsrs=true&incllsv=true",
    dataProductId: "fleet.units.profile.current.v1",
    preserved: ["n8n", "L1 graph", "Engine UI", "databases", "provider credential values"],
    files: [file],
  }, 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(value) {
  return createHash("sha256").update(value).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}`);
  return result;
}
