#!/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 [patchId = "", ...extra] = process.argv.slice(2);
if (extra.length || !/^engine-depttrans-zone-authority-v1-\d{8}-\d{3}$/.test(patchId)) {
  throw new Error(
    "usage: build-engine-depttrans-zone-authority-v1-artifact.mjs " +
    "<engine-depttrans-zone-authority-v1-YYYYMMDD-NNN>",
  );
}

const targetSha256 = Object.freeze({
  "nodedc-source/server/assets/provider-packages/v1/catalog.json":
    "1aac712a05e55137d69eedaf363969460ffe866288e8e18e35711967ab232f39",
  "nodedc-source/server/assets/provider-packages/v1/depttrans-zone-authority-v1.json":
    "1482032178b4816e599df570face9b1dfa8ae1fa2943ac8f941c561e8cb9aa9d",
  "nodedc-source/server/dataProductPublishGrant/providerCatalog.js":
    "e4c216b0affd89ddbd48abcec86febd48eb12a4c56507851daeb47f2ccd60c9a",
  "nodedc-source/server/dataProductPublishGrant/service.js":
    "408836564e9a422eb5e648cc24d764f4bfdf7f83d93306742e8615fa8186a642",
  "nodedc-source/server/dataProductPublishGrant/store.js":
    "ace5971d0772e9a9499f0849e6b754e3677cc2ca3080e573a12e26acf5a6c0c0",
});
const entries = Object.freeze(Object.keys(targetSha256));
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`);

await assertFresh(artifact);
await assertExactSources();
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-depttrans-zone-authority-v1-"));
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: "exact-platform-service-authority-v1",
    providerPackage: "moscow-department-of-transport.pmd-slow-zones.v1",
    dataProductId: "map.zones.current.v2",
    authorityBoundary: "platform-service",
    platformService: "nodedc-map-gateway",
    credentialValues: "preserved",
    untouched: ["n8n", "L1 graph", "Engine UI", "databases", "MCP Nginx"],
  }, 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_depttrans_zone_authority_source_unsafe:${relativePath}`);
    }
    const actual = digest(await readFile(sourcePath));
    if (actual !== expected) {
      throw new Error(
        `engine_depttrans_zone_authority_target_mismatch:${relativePath}:` +
        `expected=${expected}:actual=${actual}`,
      );
    }
  }

  const catalog = JSON.parse(await readFile(join(engineRoot, entries[0]), "utf8"));
  const provider = catalog.packages?.find(
    (item) => item.id === "moscow-department-of-transport.pmd-slow-zones.v1",
  );
  const request = provider?.capabilities?.[0]?.request;
  if (
    provider?.version !== "1.0.0"
    || provider?.providerId !== "moscow-department-of-transport"
    || provider?.providerCredential !== undefined
    || provider?.capabilities?.[0]?.dataProductIds?.[0] !== "map.zones.current.v2"
    || request?.authorityBoundary !== "platform-service"
    || request?.serviceId !== "nodedc-map-gateway"
    || request?.network !== "engine"
    || request?.url !== "http://map-gateway:18103/internal/zone-sources/v1/profiles/moscow-pmd-slow-zones/current"
  ) throw new Error("engine_depttrans_zone_authority_catalog_projection_mismatch");

  const marker = JSON.parse(await readFile(join(engineRoot, entries[1]), "utf8"));
  if (
    marker?.schemaVersion !== "nodedc.engine.platform-service-authority/v1"
    || marker?.id !== provider.id
    || marker?.serviceId !== request.serviceId
    || marker?.dataProductId !== provider.capabilities[0].dataProductIds[0]
  ) throw new Error("engine_depttrans_zone_authority_marker_projection_mismatch");
  const resolver = await readFile(join(engineRoot, entries[2]), "utf8");
  const service = await readFile(join(engineRoot, entries[3]), "utf8");
  const store = await readFile(join(engineRoot, entries[4]), "utf8");
  for (const marker of [
    "function platformServiceRequestIsExact",
    "pinned_platform_service_no_graph_credential",
    "platformServiceIds",
    "publish_grant_provider_request_path_unreachable",
  ]) {
    if (![resolver, service, store].some((source) => source.includes(marker))) {
      throw new Error(`engine_depttrans_zone_authority_marker_missing:${marker}`);
    }
  }
}

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