import { readdir, readFile, stat } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { validatePluginManifestV2 } from "@thortiq/plugin-api";

const projectDirectory = dirname(fileURLToPath(new URL("../manifest.json", import.meta.url)));
const outputDirectory = join(projectDirectory, "dist");

await stat(join(outputDirectory, "manifest.json")).catch(() => {
  throw new Error("Run the build before packaging; dist/manifest.json is missing.");
});
const manifest = JSON.parse(await readFile(join(outputDirectory, "manifest.json"), "utf8"));
const validation = validatePluginManifestV2(manifest);
if (!validation.ok) throw new Error("Built manifest failed validation.");

const declared = new Set(["manifest.json", ...Object.keys(manifest.integrity ?? {})]);
const present = new Set();
const walk = async (dir, prefix) => {
  for (const entry of await readdir(dir, { withFileTypes: true })) {
    const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
    if (entry.isDirectory()) await walk(join(dir, entry.name), rel);
    else present.add(rel);
  }
};
await walk(outputDirectory, "");
for (const path of present) {
  if (!declared.has(path)) throw new Error(`Unexpected file in payload: ${path}`);
}
for (const path of declared) {
  if (!present.has(path)) throw new Error(`Declared payload file is missing: ${path}`);
}
console.log(`Package OK: install ${[...declared].sort().join(", ")} under .thortiq/plugins/${manifest.id}/.`);
