import fs from "fs";
import { pathToFileURL } from "url";

const [, , moduleFile, exportName, contextFile] = process.argv;

if (!moduleFile || !exportName || !contextFile) {
  console.error("Usage: node template-step-module-runner.mjs <module-file> <export-name> <context-file>");
  process.exit(1);
}

try {
  const context = JSON.parse(fs.readFileSync(contextFile, "utf8"));
  const moduleRef = await import(pathToFileURL(moduleFile).href);
  const fn = moduleRef[exportName];
  if (typeof fn !== "function") {
    throw new Error(
      `Template module step "${moduleFile}#${exportName}" did not export a function named "${exportName}"`
    );
  }

  await fn(context);
} catch (error) {
  console.error(error?.stack || error?.message || String(error));
  process.exit(1);
}
