#!/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-registered-execution-profiles-20260724-048",
  ...extra
] = process.argv.slice(2);

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

const expectedSha256 = Object.freeze({
  "nodedc-source/server/assets/execution-plans/v1/catalog.json":
    "940510499a9260dbff718b7b1f96f72f8e9ac593b460805af3007731578a7668",
  "nodedc-source/server/l2ExecutionPlan/catalog.js":
    "fec56b154ae483ad21bbaaeb4c55707bffce223c27874ac135ce58a9203259a0",
  "nodedc-source/server/l2ExecutionPlan/registeredProfiles.js":
    "3c521c1652c61c9d757197c76e053fd3ec602e13ef7f6a4856835ecc1a8a61d1",
  "nodedc-source/server/routes/engineAgentGateway.js":
    "8f04edc11251de86b825351c92338be9537207887cf802474b6b6d8c3cce4077",
  "nodedc-source/services/node-intelligence/activation.json":
    "3d72709e40b79c01a62a6af4bde911fca4f609d5ac487d284cf97fd8ebd73686",
  "nodedc-source/server/deployTransitions/registeredExecutionProfilesV2.json":
    "1db523f035a47c6b00b41b26efe1390ad2d24acece9d30dd039eff56626e934d",
});
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-registered-execution-profiles-"),
);

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.12.0",
    transition:
      "gelios-items-envelope-v12-to-registered-profiles-v2-attested",
    tools: [
      "engine_list_l2_execution_profiles",
      "engine_plan_registered_l2_execution",
    ],
    registeredProfiles: 6,
    existingMaterializerReused: true,
    n8nCoreChanged: false,
    l1Changed: false,
    l2GraphChanged: false,
    engineUiChanged: false,
    databasesChanged: false,
    credentialsChanged: false,
    foundryChanged: false,
    ontologyChanged: false,
    nodeIntelligenceAttestationChanged: true,
    nodeIntelligenceImageChanged: false,
    nodeIntelligenceSourceChanged: 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_registered_execution_profiles_source_unsafe:${relativePath}`,
      );
    }
    const actual = digest(await readFile(sourcePath));
    if (actual !== expected) {
      throw new Error(
        `engine_registered_execution_profiles_target_mismatch:${relativePath}:`
          + `expected=${expected}:actual=${actual}`,
      );
    }
  }

  const catalog = JSON.parse(await readFile(
    join(
      engineRoot,
      "nodedc-source/server/assets/execution-plans/v1/catalog.json",
    ),
    "utf8",
  ));
  const descriptor = JSON.parse(await readFile(
    join(
      engineRoot,
      "nodedc-source/server/deployTransitions/"
        + "registeredExecutionProfilesV2.json",
    ),
    "utf8",
  ));
  const registered = catalog.packages.flatMap(
    (providerPackage) => (providerPackage.profiles || []).filter(
      (profile) => profile.executionPlanTemplate,
    ),
  );
  if (
    registered.length !== 6
    || registered.some((profile) => (
      !profile.dataClass
      || !profile.cadence
      || profile.executionPlanTemplate?.compilerVersion !== "1.4.0"
      || profile.executionPlanTemplate?.connection?.collectionProfileId
        !== profile.id
    ))
    || descriptor?.id !== "engine-mcp-registered-execution-profiles-v2"
    || descriptor?.predecessor !== "engine-mcp-gelios-items-envelope-v12"
    || descriptor?.mcpVersion !== "0.12.0"
    || descriptor?.tools?.apply
      !== "engine_apply_l2_execution_plan_materialization"
    || descriptor?.nodeIntelligenceAttestation?.targetGatewaySha256
      !== expectedSha256[
        "nodedc-source/server/routes/engineAgentGateway.js"
      ]
    || descriptor?.nodeIntelligenceAttestation?.sidecarImageChanged !== false
    || descriptor?.nodeIntelligenceAttestation
      ?.nodeIntelligenceSourceChanged !== false
    || descriptor?.boundaries?.nodeIntelligenceAttestationChanged !== true
    || Object.entries(descriptor?.boundaries || {}).some(
      ([key, value]) => (
        key !== "nodeIntelligenceAttestationChanged" && value !== false
      ),
    )
  ) {
    throw new Error("engine_registered_execution_profiles_boundary_invalid");
  }

  const gateway = await readFile(
    join(engineRoot, "nodedc-source/server/routes/engineAgentGateway.js"),
    "utf8",
  );
  const resolver = await readFile(
    join(
      engineRoot,
      "nodedc-source/server/l2ExecutionPlan/registeredProfiles.js",
    ),
    "utf8",
  );
  const nodeIntelligence = JSON.parse(await readFile(
    join(
      engineRoot,
      "nodedc-source/services/node-intelligence/activation.json",
    ),
    "utf8",
  ));
  if (
    nodeIntelligence?.releaseId !== "2.33.2-974a9fb3492f"
    || nodeIntelligence?.source?.gatewaySha256
      !== expectedSha256[
        "nodedc-source/server/routes/engineAgentGateway.js"
      ]
  ) {
    throw new Error(
      "engine_registered_execution_profiles_attestation_invalid",
    );
  }
  for (const marker of [
    "engine_list_l2_execution_profiles",
    "engine_plan_registered_l2_execution",
    "const ENGINE_AGENT_MCP_VERSION = '0.12.0'",
  ]) {
    if (!gateway.includes(marker)) {
      throw new Error(
        `engine_registered_execution_profiles_gateway_marker_missing:${marker}`,
      );
    }
  }
  if (
    !resolver.includes("registered_execution_profile_ref_scope_denied")
    || !resolver.includes("targetBoundPlan")
    || /gelios|robot2b/i.test(resolver)
  ) {
    throw new Error("engine_registered_execution_profiles_resolver_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}`);
  }
}
