"use strict";

const crypto = require("node:crypto");
const fs = require("node:fs");
const path = require("node:path");

const repositoryRoot = path.resolve(__dirname, "..");
const sourcePath = path.join(repositoryRoot, "Web", "legacy-fixed-workflow.js");
const outputPath = path.join(
  repositoryRoot,
  "src",
  "MBN_STOCK_WEBVIEW.LegacyApplication",
  "Catalog",
  "LegacyFixedActions.json");

const sourceBytes = fs.readFileSync(sourcePath);
const workflow = require(sourcePath);
if (!Array.isArray(workflow.actions) || workflow.actions.length !== 328) {
  throw new Error("The fixed legacy catalog must contain exactly 328 actions.");
}

const actions = workflow.actions.map((action, index) => {
  const expectedId = `fixed-${String(index + 1).padStart(3, "0")}`;
  if (action.id !== expectedId || !workflow.fixedMarkets.includes(action.market)) {
    throw new Error(`Unexpected fixed action identity at index ${index}.`);
  }

  return {
    id: action.id,
    market: action.market,
    section: action.section,
    label: action.label,
    detail: action.detail,
    category: action.category,
    builderKey: action.builderKey,
    code: action.code,
    aliases: action.aliases,
    available: action.available,
    prerequisite: action.prerequisite,
    selection: action.selection,
    dynamicDate: action.dynamicDate,
    dynamicNxtSession: action.dynamicNxtSession
  };
});

const document = {
  schemaVersion: 1,
  generatedFrom: "Web/legacy-fixed-workflow.js",
  sourceSha256: crypto.createHash("sha256").update(sourceBytes).digest("hex").toUpperCase(),
  runtimeAssets: workflow.runtimeAssets,
  actions
};

fs.mkdirSync(path.dirname(outputPath), { recursive: true });
fs.writeFileSync(outputPath, `${JSON.stringify(document, null, 2)}\n`, "utf8");
process.stdout.write(`${outputPath}\n`);
