#!/usr/bin/env node
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { cp, lstat, mkdir, mkdtemp, 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(scriptDir, "../deploy-artifacts");
const args = process.argv.slice(2);
const gatewayOnly = args.includes("--gateway-only");
const positionalArgs = args.filter((argument) => argument !== "--gateway-only");
if (positionalArgs.length > 1) {
  throw new Error("usage: build-gelios-data-plane-artifact.mjs [patch-id] [--gateway-only]");
}
const patchId = positionalArgs[0] || "gelios-data-plane-20260713-001";

if (!/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) {
  throw new Error("patch_id_must_contain_only_letters_digits_dot_underscore_hyphen");
}

const fullDataPlaneFiles = [
  ["infra/synology/docker-compose.platform-http.yml", "platform/docker-compose.platform-http.yml"],
  ["services/ontology-core", "platform/ontology-core"],
  ["services/ai-workspace-hub", "platform/ai-workspace-hub"],
  ["services/ai-workspace-assistant", "platform/ai-workspace-assistant"],
  ["services/gelios-gateway", "platform/gelios-gateway"],
];
// A policy/code update to an already deployed Gelios data plane must not
// carry the common Platform compose file. The deploy runner treats that file
// as a whole-Platform change. The existing Gelios service already uses the
// live Platform env_file, so this overlay can safely recreate only Gelios.
const files = gatewayOnly
  ? [["services/gelios-gateway", "platform/gelios-gateway"]]
  : fullDataPlaneFiles;

const ignoredBasenames = new Set([".DS_Store", ".git", "node_modules"]);
const stage = await mkdtemp(join(tmpdir(), "nodedc-gelios-artifact-"));
const payload = join(stage, "payload");
const target = join(artifactDir, `nodedc-platform-${patchId}.tgz`);

try {
  await mkdir(payload, { recursive: true });

  for (const [sourceRelative, destinationRelative] of files) {
    const source = resolve(platformRoot, sourceRelative);
    const destination = join(payload, destinationRelative);
    await copySafe(source, destination);
  }

  if (!gatewayOnly) {
    // The Assistant imports the deterministic catalog as a local sibling at
    // runtime. Its production Dockerfile therefore expects this directory
    // inside the Assistant build context. Keep the deploy artifact equivalent
    // to the canonical Synology staging layout without making a second source
    // copy in the repository.
    await copySafe(
      resolve(platformRoot, "services/ontology-core"),
      join(payload, "platform/ai-workspace-assistant/ontology-core"),
    );
    // This nested copy is source-only build input for the Assistant. The nested
    // service Dockerfile is neither used nor allowed by the production runner.
    await rm(join(payload, "platform/ai-workspace-assistant/ontology-core/Dockerfile"), { force: true });
  }

  await writeFile(join(stage, "manifest.env"), `id=${patchId}\ncomponent=platform\ntype=app-overlay\n`, "utf8");
  await writeFile(join(stage, "files.txt"), `${files.map(([, destination]) => destination).join("\n")}\n`, "utf8");
  await mkdir(artifactDir, { recursive: true });

  // macOS bsdtar includes AppleDouble sidecar files for extended attributes.
  // The root runner rejects those as unexpected members, so use stdlib tarfile
  // to generate a portable, data-only archive instead.
  const tar = spawnSync("python3", ["-c", [
    "import sys, tarfile",
    "with tarfile.open(sys.argv[1], 'w:gz', format=tarfile.PAX_FORMAT) as archive:",
    "    [archive.add(name, arcname=name, recursive=True) for name in ('manifest.env', 'files.txt', 'payload')]",
  ].join("\n"), target], {
    cwd: stage,
    encoding: "utf8",
  });
  if (tar.status !== 0) throw new Error(`tar_failed:${tar.stderr || tar.stdout}`);

  const digest = createHash("sha256").update(await (await import("node:fs/promises")).readFile(target)).digest("hex");
  console.log(JSON.stringify({ ok: true, patchId, gatewayOnly, artifact: target, sha256: digest }, null, 2));
} finally {
  await rm(stage, { recursive: true, force: true });
}

async function copySafe(source, destination) {
  const sourceStat = await lstat(source);
  if (sourceStat.isSymbolicLink()) throw new Error(`source_symlink_rejected:${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:${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);
  }
}
