import { pluginModuleFederation } from '@module-federation/rsbuild-plugin';
import { defineConfig, loadEnv } from '@rsbuild/core';
import { pluginBabel } from '@rsbuild/plugin-babel';
import { pluginLess } from '@rsbuild/plugin-less';
import { pluginSass } from '@rsbuild/plugin-sass';
import { pluginVue } from '@rsbuild/plugin-vue';
import pkg from './package.json';
import { generateExposesFromRoutes } from './plugins/generateExposesPlugin';
import { generateRoutesInfoPlugin } from './plugins/generateRoutesInfoPlugin';
import { zipDistPlugin } from './plugins/zipDistPlugin';
import { routes } from './src/router/routes';

export default defineConfig((env: any) => {
  const nodeEnv = env?.env || 'development';
  const envVars = loadEnv(nodeEnv) as any;
  const distDir = nodeEnv === 'production' ? pkg.name : 'dist';
  const isDev = nodeEnv !== 'production';

  const { exposes } = generateExposesFromRoutes(routes, {
    onlyLeafNodes: true,
  });

  const backendHost =
    envVars.parsed?.VITE_API_BASE_HOST || 'http://10.15.0.138:26278';

  const plugins: any[] = [
    pluginVue({
      vueLoaderOptions: {
        compilerOptions: {
          expressionPlugins: ['typescript'],
        },
      },
    }),
    pluginLess({
      lessLoaderOptions: {
        lessOptions: {
          javascriptEnabled: true,
        },
      },
    }),
    pluginSass(),
    pluginBabel({
      include: /\.(?:vue|jsx|tsx)$/,
      babelLoaderOptions: {
        plugins: ['@vue/babel-plugin-jsx'],
      },
    }),
  ];

  if (!isDev) {
    plugins.push(
      pluginModuleFederation({
        name: pkg.name,
        getPublicPath: `function() { try { if (window.__MF_REMOTE_BASE_URL__ && window.__MF_REMOTE_BASE_URL__["${pkg.name}"]) { return window.__MF_REMOTE_BASE_URL__["${pkg.name}"]; } console.warn("__MF_REMOTE_BASE_URL__ not found, using fallback"); } catch (e) { console.warn("Failed to get publicPath from global variable:", e); } return window.location.origin + "/"; }`,
        exposes: exposes,
        dts: false,
        shared: {
          vue: { singleton: true, requiredVersion: '^3.5.26' },
          'vue-router': { singleton: true, requiredVersion: '^4.6.4' },
          pinia: { singleton: true, requiredVersion: '^3.0.4' },
          'ant-design-vue': { singleton: true, requiredVersion: '^4.2.6' },
        },
      }),
      generateRoutesInfoPlugin(),
      zipDistPlugin(distDir),
    );
  }

  return {
    resolve: {
      alias: {
        '@': './src',
        'vue-video-player': './src/compat/VideoPlayer.vue',
        'vue-video-player/src/custom-theme.css':
          './src/compat/custom-theme.css',
      },
    },
    server: {
      port: 3000,
      proxy: {
        '/pdcApi': {
          target: 'http://u8b948ca.natappfree.cc',
          changeOrigin: true,
          pathRewrite: {
            '^/pdcApi': '',
          },
        },
      },
    },
    dev: {},
    output: {
      assetPrefix: 'auto',
      distPath: { root: distDir },
    },
    plugins,
  };
});
