import _ from "lodash";
import { updateBAEventParameters } from "@elliemae/pui-analytics-so";
import { getAppConfigValue, setAppConfig } from "./config.js";
import { getAssetPath } from "../window.js";
import { getAppConfigValue as getAppConfigValue2 } from "./config.js";
const parseAppConfig = (data) => {
  const { activeEnv } = data;
  const activeEnvConfig = data.env[activeEnv] || {};
  if (data.env) delete data.env;
  setAppConfig(_.merge(data, activeEnvConfig));
  sessionStorage.setItem("envName", activeEnv);
  window.emui = window.emui || {};
  window.emui.appId = getAppConfigValue("appId") ?? window.emui.appId ?? "";
  updateBAEventParameters({ envName: activeEnv });
};
const getUnVersionedPath = (path) => path.replace(/(\d+\.\d+)(?!.*\d+\.\d+)/, "latest");
const loadAppConfig = async (configPath = getAssetPath()) => {
  const appConfigUrl = `${configPath.replace(/\/?$/, "/")}app.config.json`;
  const unversionedConfigPath = getUnVersionedPath(configPath);
  try {
    const response = await fetch(appConfigUrl);
    if (!response.ok) {
      if (configPath !== unversionedConfigPath) {
        await loadAppConfig(unversionedConfigPath);
        return;
      }
      const message = `App Config is not found at ${appConfigUrl}`;
      throw new Error(message);
    }
    const appConfig = await response.json();
    parseAppConfig(appConfig);
  } catch (ex) {
    if (configPath !== unversionedConfigPath) {
      await loadAppConfig(unversionedConfigPath);
      return;
    }
    if (ex?.message?.includes(`Unexpected token`)) {
      throw new Error(`App config file at ${appConfigUrl} is not a valid JSON`);
    }
    throw ex;
  }
};
export {
  getAppConfigValue2 as getAppConfigValue,
  loadAppConfig
};
