#!/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 here = dirname(fileURLToPath(import.meta.url));
const workspaceRoot = resolve(here, "../../..");
const engineRoot = resolve(
  process.env.NODEDC_ENGINE_SOURCE_ROOT || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
);
const artifactRoot = resolve(
  process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(here, "../deploy-artifacts"),
);
const baselineArtifact = resolve(
  here,
  "../deploy-artifacts/nodedc-engine-mcp-autonomy-provider-v5-20260720-004.tgz",
);
const baselineArtifactSha256 =
  "3400954cdce078892a06b04b9bfd85a90f6ea775b1a0caf99eba1f880ef6601c";
const projectionRel = "nodedc-source/server/nodeIntelligence/upstreamProjection.js";
const descriptorRel = "nodedc-source/services/node-intelligence/activation.json";
const [patchId = "", ...extra] = process.argv.slice(2);
if (extra.length || !/^engine-provider-authority-diagnostics-\d{8}-\d{3}$/.test(patchId)) {
  throw new Error(
    "usage: build-engine-provider-authority-diagnostics-artifact.mjs " +
    "<engine-provider-authority-diagnostics-YYYYMMDD-NNN>",
  );
}

const targetSha256 = Object.freeze({
  [projectionRel]:
    "2dfa6b4f37d9bfa8b92a8109d4060d02dd2634ceb8f7924504b83ccf3fdd1523",
  [descriptorRel]:
    "84b0e15a10cedf334ad04d6f31c908da2dc155503c9974f0eeb75b01e20fb884",
});
const entries = Object.freeze(Object.keys(targetSha256));
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`);

await assertFresh(artifact);
await assertExactSources();
const descriptorText = await buildTargetDescriptor();
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-provider-authority-diagnostics-"));
try {
  const payload = join(stage, "payload");
  for (const relativePath of entries) {
    const destination = join(payload, relativePath);
    await mkdir(dirname(destination), { recursive: true });
    if (relativePath === descriptorRel) {
      await writeFile(destination, descriptorText, {
        encoding: "utf8",
        flag: "wx",
        mode: 0o644,
      });
    } else {
      await copyFile(join(engineRoot, relativePath), destination);
    }
  }
  await writeFile(
    join(stage, "manifest.env"),
    `id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
    { encoding: "utf8", flag: "wx", mode: 0o644 },
  );
  await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, {
    encoding: "utf8",
    flag: "wx",
    mode: 0o644,
  });
  await mkdir(artifactRoot, { recursive: true });
  run("python3", ["-c", canonicalTarScript(), artifact, stage]);
  console.log(JSON.stringify({
    ok: true,
    patchId,
    artifact,
    sha256: digest(await readFile(artifact)),
    entries,
    targetSha256,
    services: ["nodedc-backend"],
    transition: "private-node-name-reconciliation",
    validationBoundary: "engine-pinned-private-node-catalog",
    privateNodeIdentity: "node-id-or-exact-display-name",
    credentialValues: "preserved",
    untouched: ["L2 graph", "n8n", "L1", "Engine UI", "databases"],
  }, null, 2));
} finally {
  await rm(stage, { recursive: true, force: true });
}

async function assertExactSources() {
  for (const [relativePath, expected] of Object.entries(targetSha256)) {
    if (relativePath === descriptorRel) continue;
    const sourcePath = join(engineRoot, relativePath);
    const info = await lstat(sourcePath);
    if (!info.isFile() || info.isSymbolicLink()) {
      throw new Error(`engine_provider_authority_diagnostics_source_unsafe:${relativePath}`);
    }
    const actual = digest(await readFile(sourcePath));
    if (actual !== expected) {
      throw new Error(
        `engine_provider_authority_diagnostics_target_mismatch:${relativePath}:` +
        `expected=${expected}:actual=${actual}`,
      );
    }
    const source = await readFile(sourcePath, "utf8");
    for (const marker of [
      "isUnknownPrivateNodeIssue",
      "issue?.nodeName || issue?.node",
      "privateResults",
      "NDC_PRIVATE_NODE_VALIDATED_BY_ENGINE_CATALOG",
    ]) {
      if (!source.includes(marker)) {
        throw new Error(`engine_provider_authority_diagnostics_marker_missing:${marker}`);
      }
    }
  }
}

async function buildTargetDescriptor() {
  const baselineBytes = await readFile(baselineArtifact);
  if (digest(baselineBytes) !== baselineArtifactSha256) {
    throw new Error("engine_node_intelligence_baseline_artifact_sha256_mismatch");
  }
  const result = run("python3", [
    "-c",
    [
      "import pathlib,sys,tarfile",
      "p=pathlib.Path(sys.argv[1]); name=sys.argv[2]",
      "with tarfile.open(p,'r:gz') as t:",
      " m=t.getmember(name)",
      " if not m.isfile(): raise SystemExit('member-not-file')",
      " f=t.extractfile(m)",
      " if f is None: raise SystemExit('member-unreadable')",
      " sys.stdout.buffer.write(f.read())",
    ].join("\n"),
    baselineArtifact,
    `payload/${descriptorRel}`,
  ]);
  const descriptor = JSON.parse(result.stdout);
  if (
    descriptor?.schemaVersion !== "nodedc.engine-node-intelligence-transition/v1"
    || descriptor?.action !== "activate"
    || descriptor?.releaseId !== "2.33.2-974a9fb3492f"
    || descriptor?.source?.upstreamProjectionSha256
      !== "761a874b102a938bc6018159ddacdaac71ad6ae08e9f0f8d7f3b58a0165a5131"
    || descriptor?.source?.gatewaySha256
      !== "5331f6dc8dc306f641370a2968eb025ee3e278e27ae9a217e4cfc2901fec369c"
  ) {
    throw new Error("engine_node_intelligence_baseline_descriptor_mismatch");
  }
  descriptor.source.upstreamProjectionSha256 = targetSha256[projectionRel];
  const text = `${JSON.stringify(descriptor, null, 2)}\n`;
  if (digest(Buffer.from(text, "utf8")) !== targetSha256[descriptorRel]) {
    throw new Error("engine_node_intelligence_target_descriptor_sha256_mismatch");
  }
  return text;
}

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,
    stdio: ["ignore", "pipe", "pipe"],
  });
  if (result.status !== 0) {
    throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
  }
  return result;
}
