#!/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/executionPlanTelemetryRuntimeV2.json";
const targetSha256 = Object.freeze({
  "nodedc-source/server/l2ExecutionPlan/compiler.js":
    "6b783ad15c26dc7de0645082c8a426002d943138c70bf31a240247b16a33b6a0",
  "nodedc-source/server/assets/execution-plans/v1/catalog.json":
    "5bdfc92284a7c836ff326e3a89b559110e376b32efd34b5f23f2bec272745781",
  [descriptorPath]:
    "68b275efb6303284336d8b637c966c24d891a4bd0b3fec4fb83247359929ef79",
});
const entries = Object.freeze(Object.keys(targetSha256));
const [patchId = "", ...extra] = process.argv.slice(2);
if (
  extra.length
  || !/^engine-mcp-execution-plan-telemetry-runtime-\d{8}-\d{3}$/.test(patchId)
) {
  throw new Error(
    "usage: build-engine-mcp-execution-plan-telemetry-runtime-artifact.mjs "
    + "<engine-mcp-execution-plan-telemetry-runtime-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-telemetry-runtime-"),
);
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-materialization-v1-to-telemetry-runtime-v2",
    mcpVersion: "0.9.0",
    mcpSurface: "external-codex",
    compilerVersions: ["1.1.0", "1.2.0"],
    legacyRuntimePreserved: true,
    telemetryAuthority: [
      "trusted-telemetry-projection",
      "visible-sensor-definition",
    ],
    unprojectedParameters: "discarded",
    rawProviderPayloadAtPublish: "forbidden",
    providerLogicAuthority: "trusted-provider-package",
    untouched: [
      "live L2 graphs",
      "n8n workflow data",
      "L1",
      "Engine UI",
      "node-intelligence image and descriptor",
      "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_telemetry_runtime_source_unsafe:${relativePath}`,
      );
    }
    const actual = digest(await readFile(sourcePath));
    if (actual !== expected) {
      throw new Error(
        `engine_mcp_execution_plan_telemetry_runtime_target_mismatch:${relativePath}:`
        + `expected=${expected}:actual=${actual}`,
      );
    }
  }

  const compiler = await readFile(
    join(engineRoot, "nodedc-source/server/l2ExecutionPlan/compiler.js"),
    "utf8",
  );
  for (const marker of [
    "if (compilerVersion === '1.1.0')",
    "if (compilerVersion !== '1.2.0')",
    '"msgParam", "msg_param"',
    "descriptor.telemetryProjection",
    '"message-param"',
    "convertedSensorValue",
    "visibleSensorDefinition",
  ]) {
    if (!compiler.includes(marker)) {
      throw new Error(
        `engine_mcp_execution_plan_telemetry_runtime_marker_missing:${marker}`,
      );
    }
  }
  if (/gelios|robot2b/i.test(compiler)) {
    throw new Error("engine_mcp_execution_plan_telemetry_runtime_provider_hardcode");
  }

  const catalog = JSON.parse(await readFile(
    join(
      engineRoot,
      "nodedc-source/server/assets/execution-plans/v1/catalog.json",
    ),
    "utf8",
  ));
  if (
    JSON.stringify(catalog?.runtime?.compilerVersions)
    !== JSON.stringify(["1.1.0", "1.2.0"])
  ) {
    throw new Error("engine_mcp_execution_plan_telemetry_runtime_catalog_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-telemetry-runtime-v2"
    || descriptor?.mcpVersion !== "0.9.0"
    || JSON.stringify(descriptor?.compilerTransition?.supported)
      !== JSON.stringify(["1.1.0", "1.2.0"])
    || descriptor?.compilerTransition?.legacyRuntimePreserved !== true
    || descriptor?.providerLogicAuthority !== "trusted-provider-package"
    || descriptor?.engineProviderHardcode !== false
    || descriptor?.embeddedCodexChanged !== false
  ) {
    throw new Error(
      "engine_mcp_execution_plan_telemetry_runtime_descriptor_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;
}
