import { URL } from "url";
import loadConfigFile from "rollup/loadConfigFile";
import path from "path";
import { rollup } from "rollup";
import caxa from "caxa";

import { verify, normalize } from "./executor-configurator.js";
const { default: executorConfig } = await import(path.resolve("executor.config.js"));

const __dirname = new URL(".", import.meta.url).pathname;
const { default: caxaPackage } = caxa;

function testConfig() {
  console.log("Testing config");
  verify(normalize(executorConfig([])));
}

async function packageBin() {
  console.log("Packaging bundle into binary");
  return caxaPackage({
    input: "dist/bundles/",
    output: "bin/executor",
    command: [
      "{{caxa}}/node_modules/.bin/node",
      "{{caxa}}/qualiteer-executor.mjs",
    ],
    uncompressionMessage: "Unpacking, please wait...",
  });
}

async function rollupBundle() {
  console.log("Rolling up executor into bundle");
  const { options, warnings } = await loadConfigFile(
    path.resolve(__dirname, "rollup.config.js")
  );
  console.log(`Rollup has ${warnings.count} warnings`);
  warnings.flush();

  for (const optionsObj of options) {
    const bundle = await rollup(optionsObj);
    await Promise.all(optionsObj.output.map(bundle.write));
  }
}

testConfig();
await rollupBundle();
await packageBin();
console.log("Done");
