#!/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 workspaceRoot = resolve(scriptDir, "../../..");
const engineRoot = resolve(
  process.env.NODEDC_ENGINE_SOURCE_ROOT
    || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
);
const artifactDir = resolve(
  process.env.NODEDC_DEPLOY_ARTIFACT_DIR
    || resolve(scriptDir, "../deploy-artifacts"),
);
const [
  patchId = "engine-mcp-gelios-units-items-envelope-20260724-049",
  ...extra
] = process.argv.slice(2);

if (
  extra.length
  || !/^engine-mcp-gelios-units-items-envelope-\d{8}-\d{3}$/.test(patchId)
) {
  throw new Error(
    "usage: build-engine-mcp-gelios-units-items-envelope-artifact.mjs "
      + "[engine-mcp-gelios-units-items-envelope-YYYYMMDD-NNN]",
  );
}

const expectedSha256 = Object.freeze({
  "nodedc-source/server/assets/execution-plans/v1/catalog.json":
    "d0cc95fa5e55bda315947fdb13bd8a0d8931b9484677e4c4cc0dcb0e9614e215",
  "nodedc-source/server/assets/provider-packages/v1/catalog.json":
    "1f1b866b6f837bffc6d529dfffd8bfa9c87495bfcd9ae3515a79765143d94b1d",
  "nodedc-source/server/deployTransitions/geliosUnitsItemsEnvelopeV12Patch1.json":
    "7a1594573e98342d3a3edcc0dc4f663f06b30ca24cc20adb5f36d50591066d96",
});
const files = Object.freeze(Object.keys(expectedSha256));
const artifact = join(artifactDir, `nodedc-${patchId}.tgz`);
const checksum = `${artifact}.sha256`;
const stage = await mkdtemp(
  join(tmpdir(), "nodedc-engine-gelios-units-items-envelope-"),
);

await assertFresh(artifact);
await assertExactSources();

try {
  for (const relativePath of files) {
    const destination = join(stage, "payload", relativePath);
    await mkdir(dirname(destination), { recursive: true });
    await copyFile(join(engineRoot, relativePath), destination);
  }
  await writeFile(
    join(stage, "manifest.env"),
    `id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
    "utf8",
  );
  await writeFile(join(stage, "files.txt"), `${files.join("\n")}\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: ["nodedc-backend"],
    transition:
      "registered-profiles-v2-to-gelios-v12.0.1-units-items-envelope",
    mcpVersion: "0.12.0",
    providerPackage: {
      id: "gelios.provider.v12",
      predecessorVersion: "12.0.0",
      targetVersion: "12.0.1",
    },
    registeredProfile: "gelios.units.profile.cold.v1",
    responseCollectionPath: "items",
    existingMaterializerReused: true,
    compilerVersion: "1.4.0",
    engineRuntimeCodeChanged: false,
    n8nCoreChanged: false,
    l1Changed: false,
    l2GraphChanged: false,
    engineUiChanged: false,
    databasesChanged: false,
    credentialsChanged: false,
    foundryChanged: false,
    ontologyChanged: false,
    providerEndpointsChanged: false,
    files,
  }, null, 2));
} finally {
  await rm(stage, { recursive: true, force: true });
}

async function assertExactSources() {
  for (const [relativePath, expected] of Object.entries(expectedSha256)) {
    const sourcePath = join(engineRoot, relativePath);
    const info = await lstat(sourcePath);
    if (!info.isFile() || info.isSymbolicLink()) {
      throw new Error(
        `engine_gelios_units_items_source_unsafe:${relativePath}`,
      );
    }
    const actual = digest(await readFile(sourcePath));
    if (actual !== expected) {
      throw new Error(
        `engine_gelios_units_items_target_mismatch:${relativePath}:`
          + `expected=${expected}:actual=${actual}`,
      );
    }
  }

  const execution = JSON.parse(await readFile(
    join(
      engineRoot,
      "nodedc-source/server/assets/execution-plans/v1/catalog.json",
    ),
    "utf8",
  ));
  const security = JSON.parse(await readFile(
    join(
      engineRoot,
      "nodedc-source/server/assets/provider-packages/v1/catalog.json",
    ),
    "utf8",
  ));
  const descriptor = JSON.parse(await readFile(
    join(
      engineRoot,
      "nodedc-source/server/deployTransitions/"
        + "geliosUnitsItemsEnvelopeV12Patch1.json",
    ),
    "utf8",
  ));
  const providerPackage = execution.packages.find(
    (item) => item.id === "gelios.provider.v12",
  );
  const profile = providerPackage?.profiles.find(
    (item) => item.id === "gelios.units.profile.cold.v1",
  );
  const extract = profile?.executionPlanTemplate?.steps.find(
    (step) => (
      step.kind === "extract_items"
      && step.config?.capabilityId === "gelios.units.current.read"
    ),
  );
  const securityPackage = security.packages.find(
    (item) => item.id === "gelios.provider.v12",
  );
  if (
    providerPackage?.version !== "12.0.1"
    || securityPackage?.version !== "12.0.1"
    || profile?.dataProductId !== "fleet.units.profile.current.v1"
    || profile?.executionPlanTemplate?.compilerVersion !== "1.4.0"
    || extract?.config?.response?.collectionPaths?.[0] !== "items"
    || descriptor?.id
      !== "engine-mcp-gelios-units-items-envelope-v12-patch1"
    || descriptor?.predecessor
      !== "engine-mcp-registered-execution-profiles-v2"
    || descriptor?.mcpVersion !== "0.12.0"
    || descriptor?.registeredProfile?.materializer
      !== "existing-immutable-two-phase"
    || Object.values(descriptor?.boundaries || {}).some(Boolean)
  ) {
    throw new Error("engine_gelios_units_items_boundary_invalid");
  }
}

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],'xb') 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: 128 * 1024 * 1024,
  });
  if (result.status !== 0) {
    throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
  }
}
