import { getHTTPClient } from "../../../communication/http-client/index.js";
import { removeDoubleSlash } from "../../../utils/url.js";
import { getLogger } from "../../../utils/micro-frontend/index.js";
import { logRecords } from "../../../utils/log-records.js";
const getUnVersionedManifestPath = (path) => path.replace(/\/\d+\.\d+/, "/latest");
const getAppManifest = async ({
  hostUrl,
  manifestPath
}) => {
  if (!hostUrl || !manifestPath)
    throw new Error(
      "Unable to get app manifest. hostUrl and manifestPath are required."
    );
  const url = new URL(
    `${manifestPath.replace(/\/?$/, "/")}manifest.json`,
    hostUrl
  );
  const getUnVersionedManifestJson = () => {
    const unVersionedManifestPath = getUnVersionedManifestPath(manifestPath);
    if (manifestPath !== unVersionedManifestPath) {
      return getAppManifest({
        hostUrl,
        manifestPath: getUnVersionedManifestPath(manifestPath)
      });
    }
    throw new Error("manifest.json is not available for the application");
  };
  try {
    const response = await getHTTPClient().get(
      removeDoubleSlash(url.href)
    );
    const { headers } = response;
    if (headers["content-type"]?.includes?.("application/json"))
      return response.data;
    return await getUnVersionedManifestJson();
  } catch (err) {
    return getUnVersionedManifestJson();
  }
};
const getFullFileNameofAssetsFromManifest = (manifest, assetNames = []) => assetNames.reduce((assets, assetName) => {
  const fullFileName = manifest[assetName];
  if (fullFileName) assets.push(fullFileName);
  else {
    const logRecord = logRecords.ASSET_NOT_FOUND_IN_MANIFEST(assetName);
    getLogger().error(logRecord);
    throw new Error(logRecord.message);
  }
  return assets;
}, []);
export {
  getAppManifest,
  getFullFileNameofAssetsFromManifest
};
