/**
 * Release script — produces module.zip.
 *
 * Single version source of truth: reads version from package.json,
 * writes it into module.json, then zips all release artefacts.
 *
 * Usage: node scripts/package.mjs
 */

import { createWriteStream, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
import { resolve, dirname } from "path";
import { fileURLToPath } from "url";
import { createGzip } from "zlib";
import { exec } from "child_process";
import { promisify } from "util";

const execAsync = promisify(exec);
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");

// Read version from package.json (single source of truth)
let pkg;
try {
  pkg = JSON.parse(readFileSync(resolve(ROOT, "package.json"), "utf8"));
} catch (err) {
  console.error("[ScryingPool] Failed to read package.json:", err instanceof Error ? err.message : String(err));
  process.exit(1);
}
const { version } = pkg;

// Write version into module.json
const moduleJsonPath = resolve(ROOT, "module.json");
let moduleJson;
try {
  moduleJson = JSON.parse(readFileSync(moduleJsonPath, "utf8"));
} catch (err) {
  console.error("[ScryingPool] Failed to read module.json:", err instanceof Error ? err.message : String(err));
  process.exit(1);
}
moduleJson.version = version;
writeFileSync(moduleJsonPath, JSON.stringify(moduleJson, null, 2) + "\n", "utf8");
console.log(`[ScryingPool] module.json version set to ${version}`);

// Ensure build output exists (styles/scrying-pool.css is created by npm run build)
const buildOutputPath = resolve(ROOT, "styles/scrying-pool.css");
if (!existsSync(buildOutputPath)) {
  console.error("[ScryingPool] Build output not found — run npm run build first");
  console.error(`Expected file: ${buildOutputPath}`);
  process.exit(1);
}

// Files and directories to include in module.zip
const INCLUDE = [
  "module.json",
  "module.js",
  "lang/",
  "styles/",
  "templates/",
  "src/",
];

// Build zip using system zip command
const targets = INCLUDE.filter((f) => existsSync(resolve(ROOT, f)));
// Escape each target path properly for shell execution
const zipArgs = targets.map((t) => t.replace(/'/g, "'\\''")).map((t) => `"${t}"`).join(" ");
const zipCmd = `cd "${ROOT.replace(/'/g, "'\\''")}" && zip -r module.zip ${zipArgs}`;

console.log("[ScryingPool] Creating module.zip...");
try {
  await execAsync(zipCmd);
  console.log(`[ScryingPool] module.zip created (v${version})`);
} catch (err) {
  console.error("[ScryingPool] zip failed:", err instanceof Error ? err.message : String(err));
  process.exit(1);
}
