import fs from "node:fs/promises";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { generateReleaseNotes } from "./generate-release-notes.mjs";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const rootDir = path.resolve(__dirname, "..");
const distDir = path.join(rootDir, "dist");

execFileSync("node", ["scripts/check.mjs"], {
  cwd: rootDir,
  stdio: "inherit"
});

const manifest = JSON.parse(await fs.readFile(path.join(rootDir, "manifest.json"), "utf8"));
const version = manifest.version;
const releaseSummaryPath = path.join(distDir, `release-summary-v${version}.md`);
const zipPath = path.join(distDir, `Sensa_basic_v${version}.zip`);

await fs.mkdir(distDir, { recursive: true });

await generateReleaseNotes();

try {
  await fs.rm(zipPath);
} catch (error) {
  // ignore missing archive
}

execFileSync(
  "zip",
  [
    "-qr",
    zipPath,
    ".",
    "-x",
    "dist/*",
    "-x",
    ".git/*",
    "-x",
    "node_modules/*"
  ],
  {
    cwd: rootDir,
    stdio: "inherit"
  }
);
