#!/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-items-envelope-20260724-046", ...extra] =
  process.argv.slice(2);

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

const expectedSha256 = Object.freeze({
  "nodedc-source/server/assets/execution-plans/v1/catalog.json":
    "eb0c32fa0e8017b23e2d225fcb2d5805aa6dd1bf674e8aa248afc6a4079a7403",
  "nodedc-source/server/assets/provider-packages/v1/catalog.json":
    "42104d1267ca7840446c0c02edd3f9ecb29f8da8eb3e8f384cbd6dca0f676c4c",
  "nodedc-source/server/deployTransitions/geliosItemsEnvelopeV12.json":
    "16e39f54ebae776de9acfdf0078c79291310eeca5a1f720eb8b82496f4d419a3",
});
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-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"],
    mcpVersion: "0.11.0",
    providerPackageTransition: "gelios.provider.v11-to-v12",
    responseCollectionPath: "items",
    historicalExecutionPackagePreserved: true,
    activeSecurityAuthority: "gelios.provider.v12",
    engineCompilerChanged: false,
    n8nCoreChanged: false,
    l1Changed: false,
    ontologyChanged: false,
    credentialsChanged: false,
    rawProviderValuesIncluded: 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_items_envelope_source_unsafe:${relativePath}`);
    }
    const actual = digest(await readFile(sourcePath));
    if (actual !== expected) {
      throw new Error(
        `engine_gelios_items_envelope_target_mismatch:${relativePath}:`
          + `expected=${expected}:actual=${actual}`,
      );
    }
  }

  const executionCatalog = JSON.parse(await readFile(
    join(engineRoot, "nodedc-source/server/assets/execution-plans/v1/catalog.json"),
    "utf8",
  ));
  const securityCatalog = 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/geliosItemsEnvelopeV12.json"),
    "utf8",
  ));
  const executionIds = executionCatalog.packages.map(({ id }) => id);
  const securityIds = securityCatalog.packages.map(({ id }) => id);
  const v12 = executionCatalog.packages.find(({ id }) => id === "gelios.provider.v12");
  if (
    !executionIds.includes("gelios.provider.v11")
    || !v12?.profiles?.some((profile) => (
      profile.id === "gelios.units.identity.warm.v1"
      && profile.dataProductId === "fleet.units.identity.current.v1"
    ))
    || securityIds.includes("gelios.provider.v11")
    || securityIds.filter((id) => id === "gelios.provider.v12").length !== 1
    || descriptor?.id !== "engine-mcp-gelios-items-envelope-v12"
    || descriptor?.predecessor !== "engine-mcp-l2-execution-plan-sandbox-runtime-v4"
    || descriptor?.responseEnvelope?.collectionPath !== "items"
    || descriptor?.responseEnvelope?.rawValuesCaptured !== false
    || Object.values(descriptor?.boundaries || {}).some((value) => value !== false)
  ) {
    throw new Error("engine_gelios_items_envelope_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}`);
  }
}
