#!/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 descriptorPath =
  "nodedc-source/server/deployTransitions/executionPlanModuleOwnershipV3.json";
const activationPath =
  "nodedc-source/services/node-intelligence/activation.json";
const targetSha256 = Object.freeze({
  "nodedc-source/server/l2ExecutionPlan/materializer.js":
    "dabf0073520049d7a04d1962b29e591ae092b87b287a50534ad2d98b03ae683c",
  "nodedc-source/server/routes/engineAgentGateway.js":
    "17c5f502b3ceacc45278eef7418d08e1e55a8b3e46e00942e559d25566fdba41",
  "nodedc-source/server/assets/execution-plans/v1/catalog.json":
    "7e34b93aa30b06cd52853b48013baef2970cc27e4fddc333a1011dc73ea8c08a",
  [descriptorPath]:
    "d187d539a219fec453e06c55c3f5486ef66059371b4ae9b145266307b2af9889",
  [activationPath]:
    "4cdeb85ebb2e43f088f095f75b7fc31aabd8ab81c8ac96ded4aafd7dbd8e30bd",
});
const entries = Object.freeze(Object.keys(targetSha256));
const [patchId = "", ...extra] = process.argv.slice(2);
if (
  extra.length
  || !/^engine-mcp-execution-plan-module-ownership-\d{8}-\d{3}$/.test(patchId)
) {
  throw new Error(
    "usage: build-engine-mcp-execution-plan-module-ownership-artifact.mjs "
    + "<engine-mcp-execution-plan-module-ownership-YYYYMMDD-NNN>",
  );
}
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`);

await assertFresh(artifact);
await assertExactSources();
const stage = await mkdtemp(
  join(tmpdir(), "nodedc-engine-mcp-execution-plan-module-ownership-"),
);
try {
  const payload = join(stage, "payload");
  for (const relativePath of entries) {
    const destination = join(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`,
    { 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: "execution-plan-telemetry-runtime-v2-to-module-ownership-v3",
    mcpVersion: "0.10.0",
    mcpSurface: "external-codex",
    compilerVersions: ["1.1.0", "1.2.0"],
    materializationStrategies: [
      "create_or_reconcile_owned",
      "adopt_existing",
      "adopt_existing_module",
    ],
    moduleOwnership: {
      nodeBindings: "exact-one-to-one",
      retireBoundary: "closed",
      sharedManualWebhook: "compatible-existing-configuration-preserved",
      providerCredentialNodes: "engine-managed",
      publisherNodes: "engine-managed",
    },
    providerPackage: {
      added: "gelios.provider.v9",
      legacyPreserved: "gelios.provider.v8",
    },
    untouched: [
      "live L2 graphs",
      "n8n workflow data",
      "L1",
      "Engine UI",
      "node-intelligence image",
      "databases",
      "credentials",
      "MCP Nginx",
      "embedded AI Workspace",
    ],
  }, null, 2));
} finally {
  await rm(stage, { recursive: true, force: true });
}

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

  const materializer = await readFile(
    join(engineRoot, "nodedc-source/server/l2ExecutionPlan/materializer.js"),
    "utf8",
  );
  for (const marker of [
    "nodedc.engine.materialized-execution-plan-module/v1",
    "adopt_existing_module",
    "preserveBoundNodeIds",
    "execution_plan_module_retire_boundary_not_closed",
    "manual_webhook_same_method",
  ]) {
    if (!materializer.includes(marker)) {
      throw new Error(
        `engine_mcp_execution_plan_module_ownership_marker_missing:${marker}`,
      );
    }
  }
  if (/gelios|robot2b/i.test(materializer)) {
    throw new Error("engine_mcp_execution_plan_module_ownership_provider_hardcode");
  }

  const gateway = await readFile(
    join(engineRoot, "nodedc-source/server/routes/engineAgentGateway.js"),
    "utf8",
  );
  if (
    !gateway.includes("const ENGINE_AGENT_MCP_VERSION = '0.10.0'")
    || !gateway.includes("preserveBoundNodeIds")
    || !gateway.includes("adopt_existing_module")
  ) {
    throw new Error(
      "engine_mcp_execution_plan_module_ownership_gateway_contract_mismatch",
    );
  }

  const catalog = JSON.parse(await readFile(
    join(engineRoot, "nodedc-source/server/assets/execution-plans/v1/catalog.json"),
    "utf8",
  ));
  const geliosV9 = catalog?.packages?.find(
    (providerPackage) => providerPackage?.id === "gelios.provider.v9",
  );
  if (
    geliosV9?.contractDigest
      !== "sha256:7dd4ce4a45ce76e884ffa1e304bfaa521f552e9a45e535930f2d17b882ae23ed"
    || !catalog?.packages?.some(
      (providerPackage) => providerPackage?.id === "gelios.provider.v8",
    )
  ) {
    throw new Error(
      "engine_mcp_execution_plan_module_ownership_catalog_contract_mismatch",
    );
  }

  const descriptor = JSON.parse(
    await readFile(join(engineRoot, descriptorPath), "utf8"),
  );
  if (
    descriptor?.schemaVersion !== "nodedc.engine.deploy-transition/v1"
    || descriptor?.id !== "engine-mcp-l2-execution-plan-module-ownership-v3"
    || descriptor?.mcpVersion !== "0.10.0"
    || descriptor?.moduleOwnership?.adoptionStrategy !== "adopt_existing_module"
    || descriptor?.sharedBoundary?.configurationAuthority !== "existing-graph"
    || descriptor?.providerPackageTrust?.addedPackageId !== "gelios.provider.v9"
    || descriptor?.providerPackageTrust?.legacyPackagePreserved !== true
    || descriptor?.engineProviderHardcode !== false
    || descriptor?.embeddedCodexChanged !== false
  ) {
    throw new Error(
      "engine_mcp_execution_plan_module_ownership_descriptor_contract_mismatch",
    );
  }

  const activation = JSON.parse(
    await readFile(join(engineRoot, activationPath), "utf8"),
  );
  if (
    activation?.action !== "activate"
    || activation?.releaseId !== "2.33.2-974a9fb3492f"
    || activation?.source?.gatewaySha256
      !== targetSha256["nodedc-source/server/routes/engineAgentGateway.js"]
  ) {
    throw new Error(
      "engine_mcp_execution_plan_module_ownership_activation_contract_mismatch",
    );
  }
}

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;
}
