import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import electron from 'vite-plugin-electron';
import renderer from 'vite-plugin-electron-renderer';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import { resolve } from 'path';

export default defineConfig(({ command }) => {
  const isServe = command === 'serve';
  const isBuild = command === 'build';

  return {
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
      },
    },
    plugins: [
      vue({
        template: {
          compilerOptions: {
            // 将 webview 标记为自定义元素（Electron 特有标签）
            isCustomElement: (tag) => tag === 'webview',
          },
        },
      }),
      AutoImport({
        imports: ['vue', 'vue-router', 'pinia'],
        resolvers: [ElementPlusResolver()],
        dts: 'src/auto-imports.d.ts',
      }),
      Components({
        resolvers: [
          ElementPlusResolver(),
          // 自动解析 Element Plus 图标组件
          {
            type: 'component',
            resolve: (name: string) => {
              // Element Plus 图标组件通常是 PascalCase 且不以 El 开头
              const iconNames = [
                'Fold', 'Expand', 'Loading', 'DocumentCopy', 'Message', 'Close', 
                'Refresh', 'Delete', 'Right', 'FolderDelete', 'DataAnalysis', 
                'User', 'Film', 'Upload', 'Clock', 'Setting', 'Document', 
                'Monitor', 'TrendCharts', 'ChatDotRound', 'ArrowDown', 'ArrowLeft',
                'ArrowRight', 'VideoPlay', 'CircleCheck', 'CircleClose', 'Lock',
                'Picture', 'Plus', 'Search', 'Edit', 'Download', 'MoreFilled',
                'MagicStick',
              ];
              if (iconNames.includes(name)) {
                return { name, from: '@element-plus/icons-vue' };
              }
            },
          },
        ],
        dts: 'src/components.d.ts',
      }),
      electron([
        {
          entry: 'electron/main.ts',
          onstart(options) {
            if (process.env.VSCODE_DEBUG) {
              console.log('[startup] Electron App');
            } else {
              options.startup();
            }
          },
          vite: {
            build: {
              sourcemap: isServe,
              minify: isBuild,
              outDir: 'dist-electron',
              rollupOptions: {
                external: ['electron'],
                output: {
                  format: 'cjs',
                },
              },
            },
          },
        },
        {
          entry: 'electron/preload.ts',
          onstart(options) {
            options.reload();
          },
          vite: {
            build: {
              sourcemap: isServe ? 'inline' : undefined,
              minify: isBuild,
              outDir: 'dist-electron',
              rollupOptions: {
                external: ['electron'],
                output: {
                  format: 'cjs',
                },
              },
            },
          },
        },
      ]),
      renderer(),
    ],
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/styles/variables.scss" as *;`,
        },
      },
    },
    server: {
      port: 5173,
      proxy: {
        '/api': {
          target: 'http://localhost:3000',
          changeOrigin: true,
        },
        '/ws': {
          target: 'ws://localhost:3000',
          ws: true,
        },
      },
    },
    build: {
      outDir: 'dist',
      emptyOutDir: true,
    },
  };
});
