import _ from "lodash";
import { CMicroAppGuest } from "./guest.js";
import { CMicroAppHost } from "./host.js";
import { getAppConfigValue } from "../app-config/config.js";
import { convertRelativeToAbsoluteUrl, isCIBuild } from "../helpers.js";
import { LaunchMode } from "./types.js";
const isHost = () => CMicroAppHost.isInitialized();
const isGuest = () => CMicroAppGuest.isInitialized();
const isStandAloneGuest = () => isGuest() && window.top === window.self;
const getLogger = () => isHost() ? CMicroAppHost.getInstance().getLogger() : CMicroAppGuest.getInstance().getLogger();
const isProduction = (mode) => {
  if (isCIBuild()) return true;
  if (mode) return mode === LaunchMode.PRODUCTION;
  return true;
};
const getVersionedPath = (path) => {
  const { systemVersion } = CMicroAppHost.getInstance().getProps();
  const majorMinorVersion = systemVersion.match(/^(?:\d+\.\d+)*/g);
  return path.replace(
    /{SYSTEM_VERSION}/,
    majorMinorVersion && majorMinorVersion[0] || "latest"
  );
};
const getMicroFrontEndAppConfig = (appInfo) => {
  const microFEAppConfig = getAppConfigValue(
    `microFrontendApps.${appInfo.id}`
  );
  if (!microFEAppConfig)
    throw new Error(
      `unable to locate application configuraiton for ${appInfo.id} under microFrontendApps section of app.config.json`
    );
  const { mode = LaunchMode.PRODUCTION } = microFEAppConfig;
  const envConfig = isProduction(mode) ? microFEAppConfig.production : microFEAppConfig.development;
  if (microFEAppConfig.production) delete microFEAppConfig.production;
  if (microFEAppConfig.development) delete microFEAppConfig.development;
  const microFEConfig = _.merge(
    appInfo,
    {
      mode: "production",
      hostUrl: "./",
      manifestPath: "./{SYSTEM_VERSION}",
      isJsModule: false
    },
    microFEAppConfig,
    envConfig
  );
  microFEConfig.hostUrl = convertRelativeToAbsoluteUrl(
    microFEConfig.hostUrl.replace(/\/?$/, "/")
  );
  microFEConfig.manifestPath = getVersionedPath(microFEConfig.manifestPath);
  return microFEConfig;
};
export {
  getLogger,
  getMicroFrontEndAppConfig,
  isGuest,
  isHost,
  isStandAloneGuest
};
