// Copyright (c) 2025-2026 Withpica Ltd. All rights reserved.

export class BundleShapeError extends Error {}

/**
 * The ext-apps browser bundle is an ES module: it ends in one
 * `export{local as Name,…};`. The cards inline it in a plain <script>, where
 * that line is a SyntaxError and nothing in the bundle runs (2026-11-11: no
 * card ever started in any host). Swap the export for a window global and
 * wrap the bundle in a function so its top-level names stay private.
 * Throws if the bundle's shape changes, so a build can never ship a bridge
 * that cannot run.
 */
export function toClassicScript(moduleJs: string, globalName: string): string {
  const match = moduleJs.match(/export\s*\{([^}]*)\}\s*;?\s*$/);
  if (!match || match.index === undefined) {
    throw new BundleShapeError(
      "[bundle-apps] ext-apps bundle has no trailing export list",
    );
  }
  const body = moduleJs.slice(0, match.index);
  const entries = match[1]
    .split(",")
    .map((part) => part.trim())
    .filter(Boolean)
    .map((part) => {
      const [local, exported] = part.split(/\s+as\s+/);
      return `${JSON.stringify(exported ?? local)}:${local}`;
    });
  const classic = `(function(){"use strict";${body}\nwindow.${globalName}={${entries.join(",")}};})();`;
  try {
    // Parses as a plain script, or throws: any module syntax left (import,
    // import.meta, a second export) is a SyntaxError here.
    new Function(classic);
  } catch (err) {
    throw new BundleShapeError(
      `[bundle-apps] ext-apps bundle does not parse as a plain script: ${String(err)}`,
    );
  }
  return classic;
}
