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

const dir = dirname(fileURLToPath(new URL("../manifest.json", import.meta.url)));
const manifest = JSON.parse(await readFile(join(dir, "manifest.json"), "utf8"));
const javascript = await readFile(join(dir, "plugin.js"), "utf8");
const css = await readFile(join(dir, "styles.css"), "utf8");

const result = validatePluginManifestV2(manifest);
if (!result.ok) {
  throw new Error(`manifest.json is invalid: ${result.issues.map(i => i.code).join(", ")}`);
}
if (manifest.runtime !== "live-sandboxed") {
  throw new Error("Live customization manifests must declare runtime live-sandboxed.");
}
assertSelfContainedSource(javascript);
// Canonicalizes and cross-checks the live content just like the preview path.
parseLivePluginContentV1(manifest.id, { manifest, javascript, css });
console.log(`Live bundle OK for ${manifest.id}.`);

export function assertSelfContainedSource(source) {
  if (/(?:^|\n)\s*import\b/u.test(source) || /\bimport\s*\(/u.test(source)) {
    throw new Error("Live source must not use static or dynamic imports.");
  }
  if (/\bexport\s+\*/u.test(source) || /\bexport\s*\{/u.test(source)) {
    throw new Error("Live source may only use one default export.");
  }
  if (!/\bexport\s+default\b/u.test(source)) {
    throw new Error("Live source must have exactly one default export.");
  }
}
