import { createApp } from "vue";
import Antd, { message } from "ant-design-vue";

import {
  createMemoryHistory,
  createRouter,
  createWebHistory,
} from "vue-router";

import routes from "./router";

import App from "./App.vue";

import AgGridVue from "EFX/AgGridVue";

import { Pane, Splitpanes } from "splitpanes";

import { init, IAxiosInitConfig, isXinPlatWorkspace } from "EIX/ei";
import { initInstrumentation } from "./instrumentation";
import { type PrepareContext } from "./prepare";
import { evictCached, refreshCached } from "./sharedTabCache";

export async function bootstrap(baseURL: string, preparePromise: Promise<PrepareContext>, appBase: string, routerHistory?: string,) {

  // const { vueI18n } = await prepare();
  const { vueI18n } = await preparePromise;

  const app = createApp(App);

  const historyBase =
    import.meta.env.PROD
      ? `${baseURL}${appBase}/${import.meta.env.VITE_APP_NAME}/`
      : "";

  const history =
    routerHistory === "memory"
      ? createMemoryHistory(historyBase)
      : createWebHistory(historyBase);

  const router = createRouter({
    history,
    routes,
  });
  // if(import.meta.env.DEV) {
    router.beforeEach((to, from) => {
      console.debug(`[router] ${from.fullPath} -> ${to.fullPath}`);
    });
  // }
  app.use(router);

  app.use(vueI18n);

  app.use(Antd);

  app.component("ag-grid-vue", AgGridVue);

  app.component("v-splitter", Splitpanes);

  app.component("v-splitter-pane", Pane);

  const eiInitOptions: IAxiosInitConfig = {
    baseURL,
    powerByQianKun:
      window.__POWERED_BY_WUJIE__ ?? false,
    currentRouter: router,
    platType: import.meta.env.VITE_APP_PLAT_TYPE,
    messageService: message,
    jServerContext:
      import.meta.env.VITE_APP_SERVER_CONTEXT,
  };

  if (import.meta.env.DEV ) {
    (eiInitOptions as any).useLocalServer = (import.meta.env.VITE_APP_USE_LOCAL_SERVER === "true");
    (eiInitOptions as any).useGatewayProxy = (import.meta.env.VITE_APP_USE_GATEWAY_PROXY === "true")
  }

  init(eiInitOptions);

  app.mount("#sub-app");

  // 单容器多 tab(实验):宿主切换同 dll 的 tab 时,经 wujie bus 驱动内部路由(沙箱常驻)
  if (window.__POWERED_BY_WUJIE__ && (window as any).$wujie?.bus) {
    const dllName = import.meta.env.VITE_APP_NAME;
    // 诊断探针
    (window as any).__XR_ROUTER__ = router;
    (window as any).$wujie.bus.$on(`xr-shared-route:${dllName}`, (path: string) => {
      console.info(`[xr-shared] 收到路由事件: ${path}`);
      const wujie = (window as any).$wujie;
      // 同步 wujie props.formName:xrEfForm 取画面名时 props.formName 优先级最高,
      // 而共享沙箱下 props 冻结在首个 tab——不更新则新挂载实例永远拿到旧参数
      try {
        const formName = new URLSearchParams(path.split('?')[1] || '').get('formName');
        if (formName) {
          wujie.props = wujie.props ?? {};
          wujie.props.formName = formName;
        }
      } catch {
        /* path 无 query 时忽略 */
      }
      if (path && router.currentRoute.value.fullPath !== path) {
        router.push(path).catch((e) => console.warn(`[xr-shared] 路由跳转失败: ${path}`, e));
      }
    });
    // 宿主关闭 tab:按 fullPath 精确逐出该画面的 KeepAlive 缓存(同路由其他参数 tab 不受影响)
    (window as any).$wujie.bus.$on(`xr-shared-close:${dllName}`, (path: string) => {
      if (path) evictCached(path);
    });
    // 宿主刷新 tab:内层组件按刷新计数重建,状态归零,不影响同 dll 其他画面
    (window as any).$wujie.bus.$on(`xr-shared-refresh:${dllName}`, (path: string) => {
      if (path) refreshCached(path);
    });
  }

  // 3. 初始化链路追踪
  try {
    if (isXinPlatWorkspace() && !window.__OTEL_PROVIDER__) {
      const provider = await initInstrumentation();

      if (provider) {
        window.__OTEL_PROVIDER__ = provider;
      }
    }
  } catch (err) {
    console.error("[OTel] init failed", err);
  }

  // await initDevAuth(router);

  return {

    app,

    router,

    history,
  };
}
