import { execSync } from "node:child_process";
import { createRequire } from "node:module";
import { existsSync, mkdirSync, rmSync } from "node:fs";
import { join } from "node:path";

/**
 * Zips the built extension targets into the web panel's public dir so caddy
 * serves them from the download page (stable names, overwritten per release).
 * Usage: node scripts/package.mjs
 */
const require = createRequire(import.meta.url);
const { version } = require("../package.json");
const extDir = new URL("..", import.meta.url).pathname;
const outDir = join(extDir, "..", "web", "public", "ext");

if (execSync("command -v zip || true").toString().trim() === "") {
  console.error("The `zip` CLI is not installed — install it (apt install zip / apk add zip / pacman -S zip) and re-run.");
  process.exit(1);
}

mkdirSync(outDir, { recursive: true });
for (const target of ["chrome", "firefox"]) {
  const dist = join(extDir, "dist", target);
  if (!existsSync(join(dist, "manifest.json"))) {
    console.error(`${dist} has no manifest.json — run \`npm run build -w @ltt/extension\` first.`);
    process.exit(1);
  }
  const out = join(outDir, `bugtrail-${target}.zip`);
  rmSync(out, { force: true });
  // zip the directory contents (manifest at the archive root) so the unpacked
  // folder can be loaded directly via "Load unpacked"
  execSync(`zip -qr ${JSON.stringify(out)} .`, { cwd: dist, stdio: "inherit" });
  console.log(`packaged bugtrail-${target} v${version} -> ${out}`);
}