import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";

import { buildAndValidatePortablePackage } from "./lib/portable-package.mjs";
import { validateFinalReleaseRecord } from "./lib/wp7-07-final-release.mjs";

const outputIndex = process.argv.indexOf("--output");
const outputRoot = outputIndex >= 0 ? resolve(process.argv[outputIndex + 1]) : resolve(".build", "portable-release");
const previousRelease = JSON.parse(readFileSync(resolve("RELEASE.json"), "utf8"));
const releaseRecord = validateFinalReleaseRecord({
  ...previousRelease,
  buildCommit: execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(),
  maintenanceFromCommit: previousRelease.buildCommit,
  recordedAt: new Date().toISOString(),
});
const result = await buildAndValidatePortablePackage({ outputRoot, releaseRecord });
console.log(JSON.stringify({
  package: result.packageManifest.package_name,
  sha256: result.packageManifest.zip_sha256,
  status: result.status,
}, null, 2));
