#!/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-composite-provider-v4-\d{8}-\d{3}$/.test(patchId)) {
  throw new Error(
    "usage: build-engine-composite-provider-v4-artifact.mjs " +
    "<engine-composite-provider-v4-YYYYMMDD-NNN>",
  );
}

const targetSha256 = Object.freeze({
  "nodedc-source/server/assets/provider-packages/v1/catalog.json":
    "9c931f9abfcadb5b34a8a854c2efb8fd79913e000eecf0967d1b7c500bf9a56a",
  "nodedc-source/server/dataProductPublishGrant/providerCatalog.js":
    "689c6fbf695e582d983159973a21142787d1b19bb1d343da4c62c03092ac291f",
  "nodedc-source/server/dataProductPublishGrant/service.js":
    "83f045f4e0f332644310172ed51bb652d808bf04155b11c02e46bdffc95f7220",
  "nodedc-source/server/dataProductPublishGrant/store.js":
    "98662da6acd0489a9cae4b726eb61ce89d9b2c788b2ea95433e9c4f02930c095",
});
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-composite-provider-v4-"));
try {
  const payload = join(stage, "payload");
  for (const relativePath of entries) {
    const source = join(engineRoot, relativePath);
    const destination = join(payload, relativePath);
    await mkdir(dirname(destination), { recursive: true });
    await copyFile(source, destination, 0);
  }
  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-v3-to-v4",
    providerPackage: "gelios.provider.v4",
    capabilities: [
      "gelios.monitoring_config.current.read",
      "gelios.units.current.read",
    ],
    dataProductId: "fleet.positions.current.v3",
    credentialValues: "preserved",
    untouched: ["n8n", "L1 graph", "Engine UI", "databases"],
  }, null, 2));
} finally {
  await rm(stage, { recursive: true, force: true });
}

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

  const catalog = JSON.parse(await readFile(join(engineRoot, entries[0]), "utf8"));
  const provider = catalog?.packages?.[0];
  const capabilityIds = provider?.capabilities?.map((item) => item.id);
  const requestUrls = provider?.capabilities?.map((item) => item.request?.url);
  if (
    catalog?.schemaVersion !== "nodedc.engine.provider-security-catalog/v1" ||
    provider?.id !== "gelios.provider.v4" ||
    provider?.version !== "4.0.0" ||
    provider?.providerCredential?.credentialType !== "httpBearerAuth" ||
    JSON.stringify(capabilityIds) !== JSON.stringify([
      "gelios.monitoring_config.current.read",
      "gelios.units.current.read",
    ]) ||
    JSON.stringify(requestUrls) !== JSON.stringify([
      "https://api.geliospro.com/api/v1/users/me/monitoring-config",
      "https://api.geliospro.com/api/v1/units?incltrip=true",
    ]) ||
    provider?.capabilities?.some(
      (item) => item.dataProductIds?.length !== 1 ||
        item.dataProductIds[0] !== "fleet.positions.current.v3",
    )
  ) {
    throw new Error("engine_composite_provider_catalog_projection_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}`);
  }
}
