import { SDK_URL } from "../constant";
import { getDebugContext } from "./debugger";
import { consoleLogger, logger } from "./logger";
export function loadSdk() {
  return new Promise(function (resolve, reject) {
    // 获取src
    var sdkSrc = SDK_URL.PROD;

    // debug模式动态传入sdkUrl
    var debugContext = getDebugContext();
    if ((debugContext === null || debugContext === void 0 ? void 0 : debugContext.debugMode) === true) {
      sdkSrc = (debugContext === null || debugContext === void 0 ? void 0 : debugContext.sdkUrl) || SDK_URL.PROD;
    }

    // 校验URL合法性
    try {
      new URL(sdkSrc);
    } catch (e) {
      consoleLogger.error("Invalid SDK URL: ".concat(sdkSrc));
      reject(e);
      return;
    }

    // 检查 SDK URL 是否存在
    if (!sdkSrc) {
      consoleLogger.error("SDK URL not found for: ".concat(sdkSrc));
      reject("SDK URL not found for: ".concat(sdkSrc));
      return;
    }

    // 检查是否已经加载过该脚本
    var existingScript = document.querySelector("script[src=\"".concat(sdkSrc, "\"]"));
    if (existingScript) {
      consoleLogger.log("SDK already loaded: ".concat(sdkSrc));
      resolve({
        success: true,
        loadType: 'cached'
      });
      return;
    }

    // 注入脚本到html
    var script = document.createElement('script');
    script.src = sdkSrc;
    document.head.appendChild(script);

    // 定义onload和onerror事件
    script.onload = function () {
      consoleLogger.log("Load SDK Success , SDK URL: ".concat(sdkSrc));
      resolve({
        success: true,
        loadType: 'network'
      });
    };
    script.onerror = function () {
      consoleLogger.log("Failed to load SDK: ".concat(sdkSrc));
      logger.logError({
        title: 'load_sdk_resource_error'
      }, {
        webSDKUrl: sdkSrc
      });
      logger.logInfo({
        title: 'create_antom_instance'
      }, {
        result: 'N'
      });
      // 失败时移除缓存脚本
      script.remove();
      reject("Failed to load SDK: ".concat(sdkSrc));
    };
  });
}
export function newActualInstance(constructorName, newProps) {
  try {
    var _window;
    // 获取构造函数
    if (!constructorName) {
      consoleLogger.error("Load SDK failed: constructorName not found, please check constructorName: ".concat(constructorName));
      logger.logError({
        title: 'load_constructor_resource_error'
      }, {
        constructorName: constructorName
      });
      return null;
    }
    var Constructor = (_window = window) === null || _window === void 0 ? void 0 : _window[constructorName];
    if (!Constructor) {
      consoleLogger.error("".concat(constructorName, " not found after SDK load"));
    }

    // 实例化对象
    return new Constructor(newProps);
  } catch (error) {
    consoleLogger.error('Load SDK failed:', error);
    return null;
  }
}