import path from 'path'
import { createRequire } from 'module'
import { fileURLToPath } from 'url'
import { defineConfig, loadEnv } from '@rsbuild/core'
import { pluginReact } from '@rsbuild/plugin-react'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const require = createRequire(import.meta.url)
const semiUiDir = path.resolve(
  path.dirname(require.resolve('@douyinfe/semi-ui')),
  '../..',
)
const semiUiDateFnsDir = path.resolve(semiUiDir, 'node_modules/date-fns')
const resolvePackageRoot = (packageName: string, baseRequire = require) => {
  let current = path.dirname(baseRequire.resolve(packageName))
  while (current !== path.dirname(current)) {
    if (require('fs').existsSync(path.join(current, 'package.json'))) {
      return current
    }
    current = path.dirname(current)
  }
  return current
}
const vchartDir = resolvePackageRoot('@visactor/vchart')
const vchartRequire = createRequire(path.join(vchartDir, 'package.json'))
const visactorChartAliases = Object.fromEntries(
  [
    '@visactor/react-vchart',
    '@visactor/vchart',
    '@visactor/vchart-semi-theme',
    '@visactor/vchart-theme-utils',
    '@visactor/vrender-components',
    '@visactor/vrender-core',
    '@visactor/vrender-kits',
    '@visactor/vdataset',
    '@visactor/vscale',
    '@visactor/vutils',
    '@visactor/vutils-extension',
  ].map((packageName) => [
    packageName,
    resolvePackageRoot(
      packageName,
      packageName === '@visactor/react-vchart' ||
        packageName === '@visactor/vchart-semi-theme' ||
        packageName === '@visactor/vchart-theme-utils'
        ? require
        : vchartRequire,
    ),
  ]),
)

export default defineConfig(({ envMode }) => {
  const env = loadEnv({ mode: envMode, prefixes: ['VITE_'] })
  const clientServerUrl =
    process.env.VITE_REACT_APP_SERVER_URL ||
    env.rawPublicVars.VITE_REACT_APP_SERVER_URL ||
    ''
  const proxyServerUrl =
    clientServerUrl ||
    'http://localhost:3000'
  const isProd = envMode === 'production'
  const devProxy = Object.fromEntries(
    (['/api', '/mj', '/pg'] as const).map((key) => [
      key,
      { target: proxyServerUrl, changeOrigin: true },
    ]),
  ) as Record<string, { target: string; changeOrigin: boolean }>

  return {
    plugins: [pluginReact()],
    source: {
      entry: {
        index: './src/index.jsx',
      },
      define: {
        'import.meta.env.VITE_REACT_APP_SERVER_URL': JSON.stringify(
          clientServerUrl,
        ),
      },
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
        '@douyinfe/semi-ui/dist/css/semi.css': path.resolve(
          semiUiDir,
          'dist/css/semi.css',
        ),
        'date-fns': semiUiDateFnsDir,
        ...visactorChartAliases,
      },
    },
    html: {
      template: './index.html',
    },
    server: {
      host: '0.0.0.0',
      strictPort: false,
      proxy: devProxy,
      port:5173
    },
    output: {
      minify: isProd,
      target: 'web',
      distPath: {
        root: 'dist',
      },
    },
    performance: {
      removeConsole: isProd ? ['log'] : false,
      buildCache: {
        cacheDigest: [process.env.VITE_REACT_APP_VERSION],
      },
    },
    tools: {
      rspack: {
        module: {
          rules: [
            {
              test: /src[\\/].*\.js$/,
              type: 'javascript/auto',
              use: [
                {
                  loader: 'builtin:swc-loader',
                  options: {
                    jsc: {
                      parser: {
                        syntax: 'ecmascript',
                        jsx: true,
                      },
                      transform: {
                        react: {
                          runtime: 'automatic',
                          development: !isProd,
                          refresh: !isProd,
                        },
                      },
                    },
                  },
                },
              ],
            },
          ],
        },
      },
    },
  }
})
