import { type ConfigEnv, type UserConfig, defineConfig } from 'vite';
import Vue from '@vitejs/plugin-vue';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { useViteCompression } from './vite/compression';
import Icons from 'unplugin-icons/vite';
import AutoImport from 'unplugin-auto-import/vite';
import { FileSystemIconLoader } from 'unplugin-icons/loaders';
/**
 * 简化入口专用配置
 * 仅包含 Vue 插件,用于构建 other_pages 中的页面
 */
export default defineConfig(({ command }: ConfigEnv): Promise<UserConfig> => {
  const isBuild = Boolean(command === 'build');

  const config: UserConfig = {
    base: './',

    // 只使用 Vue 插件
    plugins: [
      Vue({}),
      AutoImport({
        imports: ['vue'],
        vueTemplate: true, // Vue模板内自动导入
      }),
      // 注册 svgIcon
      Icons({
        autoInstall: true,
        compiler: 'vue3',
        customCollections: { my: FileSystemIconLoader(resolve(__dirname, 'src/assets/svg-icons/unplugin-icons')) },
      }),
      // 压缩
      useViteCompression(isBuild),
    ],

    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          // 简化版不需要注入全局样式
          additionalData: '',
        },
      },
    },

    // 开发服务器配置
    server: {
      open: false,
      port: 4265, // 使用不同的端口避免冲突
      strictPort: false,
      cors: true,
    },

    define: {
      __APP_VERSION_TIMESTAMP__: JSON.stringify(new Date().getTime()),
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
    },

    clearScreen: false,
    envPrefix: ['VITE_', 'TAURI_ENV_'],

    build: {
      outDir: 'dist', // 输出到同一个目录
      emptyOutDir: false, // 不清空目录,保留主应用的构建产物
      cssCodeSplit: true,
      sourcemap: false,
      target: 'es2020',
      chunkSizeWarningLimit: 1150,
      assetsInlineLimit: 4096,
      minify: 'oxc',
      rollupOptions: {
        // 只构建简化入口
        input: {
          'floating-list-window': resolve(__dirname, 'floating-list-window.html'),
          'popup-window': resolve(__dirname, 'popup-window.html'),
        },
        output: {
          // 自定义输出文件名,避免与主应用冲突
          chunkFileNames: 'js/[name]-[hash].js',
          entryFileNames: 'js/[name]-[hash].js',
          assetFileNames: (assetInfo) => {
            const ext: string = assetInfo.name?.split('.').pop() || '';
            let extType: string = ext;
            if (['mp4', 'webm', 'ogg', 'mp3', 'wav', 'flac', 'aac'].includes(ext)) {
              extType = 'media';
            } else if (['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'ico'].includes(ext)) {
              extType = 'images';
            } else if (['woff', 'woff2', 'ttf', 'eot', 'otf'].includes(ext)) {
              extType = 'fonts';
            } else if (ext === 'css') {
              extType = 'css';
            } else {
              extType = 'assets';
            }
            return `${extType}/[name]-[hash].[ext]`;
          },
        },
      },
    },
  };

  return Promise.resolve(config);
});
