#!/usr/bin/env node
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, relative, 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 = "ontology-core-20260719-001", ...extra] = process.argv.slice(2);

if (extra.length || !/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) {
  throw new Error("usage: build-ontology-core-artifact.mjs [patch-id]");
}

const sourceRoot = resolve(platformRoot, "services/ontology-core");
const destinationRoot = "platform/ontology-core";
const ignoredBasenames = new Set([".DS_Store", ".git", "node_modules", "test"]);
const stage = await mkdtemp(join(tmpdir(), "nodedc-ontology-core-artifact-"));
const payload = join(stage, "payload");
const target = join(artifactDir, `nodedc-platform-${patchId}.tgz`);

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

  const tar = spawnSync("python3", ["-c", canonicalTarScript(), target, stage], {
    encoding: "utf8",
    maxBuffer: 128 * 1024 * 1024,
  });
  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"),
    entries: [destinationRoot],
    servicesExpected: ["ontology-core", "ai-workspace-hub"],
    excluded: [".env*", "node_modules", "test", "secrets"],
  }, null, 2));
} finally {
  await rm(stage, { recursive: true, force: true });
}

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");
}

async function copySafe(source, destination) {
  const sourceStat = await lstat(source);
  if (sourceStat.isSymbolicLink()) throw new Error(`source_symlink_rejected:${relative(platformRoot, source)}`);
  if (sourceStat.isFile()) {
    await mkdir(dirname(destination), { recursive: true });
    await cp(source, destination, { force: true, verbatimSymlinks: true });
    return;
  }
  if (!sourceStat.isDirectory()) throw new Error(`source_type_rejected:${relative(platformRoot, source)}`);

  await mkdir(destination, { recursive: true });
  for (const entry of await readdir(source, { withFileTypes: true })) {
    if (ignoredBasenames.has(entry.name) || entry.name.startsWith(".env")) continue;
    const childSource = join(source, entry.name);
    const childDestination = join(destination, entry.name);
    if (entry.isSymbolicLink()) throw new Error(`source_symlink_rejected:${relative(platformRoot, childSource)}`);
    await copySafe(childSource, childDestination);
  }
}
