import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
import svgr from 'vite-plugin-svgr'
import * as process from 'process'
import { visualizer } from 'rollup-plugin-visualizer'
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js'

// https://vitejs.dev/config/
const noSourcemap = process.env.NO_SOURCEMAP
const visualizeBuild = !!process.env.VISUALIZE_BUILD
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  const isProduction = mode === 'production'
  console.log(env.VITE_BASE_URL)
  return {
    mode,
    define: {
      __DEV__: !isProduction,
      __USE_MOCK__: !!env.VITE_USE_MOCK && env.VITE_USE_MOCK !== 'False',
    },
    plugins: [
      react({
        jsxRuntime: 'automatic',
        jsxImportSource: '@emotion/react',
      }),
      svgr(),
      ...(visualizeBuild ? [visualizer({ filename: 'visual-build.html' })] : []),
      cssInjectedByJsPlugin()
    ],
    optimizeDeps: {
      // include: ['react/jsx-runtime', 'react-dom'],
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
        // molstar: path.resolve(__dirname, '../../../molstar'),
      },
    },
    build: {
      lib: {
        entry: path.resolve(__dirname, 'src/entry.ts'),
        name: 'UI',
        formats: ['umd'],
      },
      rollupOptions: {
        external: [
          'react',
          'react-dom',
          'molstar'
        ],
        output: {
          sourcemap: false,
          globals: {
            react: 'React',
            'react-dom': 'ReactDom',
            molstar: 'molstar'
          }
        }
      },
      sourcemap: !noSourcemap,
      terserOptions: {
        compress: {
          pure_funcs: isProduction ? ['console.log', 'console.info', 'console.debug'] : [],
          drop_debugger: true,
        },
      },
      minify: isProduction && 'esbuild',
      emptyOutDir: true,
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          additionalData: (content, loaderContext) => {
            // 更多可用的属性见 https://webpack.js.org/api/loaders/
            // console.log(loaderContext)
            // const relativePath = path.relative(rootContext, resourcePath)

            if (/styles\/variables\.less/.test(loaderContext)) {
              return content
            }

            return content + '\n@import "@/styles/variables.less";\n'
          },
        },
      },
    },
  }
})
