#!/usr/bin/env node

import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { cp, 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 scriptDir = dirname(fileURLToPath(import.meta.url));
const platformRoot = resolve(scriptDir, "../..");
const workspaceRoot = resolve(platformRoot, "..");
const foundryRoot = resolve(workspaceRoot, "NODEDC_DESIGN_GUIDELINE");
const artifactDir = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"));
const [patchId = "module-foundry-filter-toggle-20260720-001", ...extra] = process.argv.slice(2);

if (extra.length || !/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) {
  throw new Error("patch_id_must_contain_only_letters_digits_dot_underscore_hyphen");
}

const files = [
  "apps/catalog/src/MapFixturePreview.tsx",
  "apps/catalog/src/mapPresentationProfile.ts",
  "scripts/map-presentation-filters.test.mjs",
];
const stage = await mkdtemp(join(tmpdir(), "nodedc-module-foundry-filter-toggle-artifact-"));
const payload = join(stage, "payload");
const artifact = join(artifactDir, `nodedc-module-foundry-${patchId}.tgz`);
const checksum = `${artifact}.sha256`;

await assertFilterToggleBoundary();

try {
  await mkdir(payload, { recursive: true });
  for (const relativePath of files) {
    const source = resolve(foundryRoot, relativePath);
    const sourceStat = await lstat(source);
    if (!sourceStat.isFile() || sourceStat.isSymbolicLink()) {
      throw new Error(`source_file_rejected:${relativePath}`);
    }
    const destination = join(payload, relativePath);
    await mkdir(dirname(destination), { recursive: true });
    await cp(source, destination, { force: true, verbatimSymlinks: true });
  }

  await writeFile(join(stage, "manifest.env"), `id=${patchId}\ncomponent=module-foundry\ntype=app-overlay\n`, "utf8");
  await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
  await mkdir(artifactDir, { recursive: true });

  const tar = spawnSync("python3", ["-c", canonicalTarScript(), artifact, stage], {
    encoding: "utf8",
    maxBuffer: 64 * 1024 * 1024,
  });
  if (tar.status !== 0) throw new Error(`tar_failed:${tar.stderr || tar.stdout}`);

  const sha256 = createHash("sha256").update(await readFile(artifact)).digest("hex");
  await writeFile(checksum, `${sha256}  ${artifact.split("/").at(-1)}\n`, "utf8");
  console.log(JSON.stringify({ ok: true, patchId, artifact, checksum, sha256, files }, null, 2));
} finally {
  await rm(stage, { recursive: true, force: true });
}

async function assertFilterToggleBoundary() {
  const helper = await readFile(resolve(foundryRoot, files[1]), "utf8");
  for (const marker of [
    "toggleMapPresentationFacetSelection",
    "const { [field]: _removed, ...unconstrained } = facets",
    "return unconstrained",
  ]) {
    if (!helper.includes(marker)) throw new Error(`foundry_filter_toggle_helper_missing:${marker}`);
  }

  const preview = await readFile(resolve(foundryRoot, files[0]), "utf8");
  if (!preview.includes("filters: toggleMapPresentationFacetSelection(filters, field, value)")) {
    throw new Error("foundry_filter_toggle_component_contract_missing");
  }

  const test = await readFile(resolve(foundryRoot, files[2]), "utf8");
  for (const marker of [
    "interactive deselect of the last chip removes the facet constraint",
    "interactive deselect preserves other values and facet constraints",
    "deselecting the last chip remains empty and never normalizes to all",
  ]) {
    if (!test.includes(marker)) throw new Error(`foundry_filter_toggle_regression_missing:${marker}`);
  }
}

function canonicalTarScript() {
  return [
    "import gzip,io,pathlib,sys,tarfile",
    "root=pathlib.Path(sys.argv[2])",
    "with open(sys.argv[1],'wb') 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");
}
