import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import { resolve } from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import pkg from './package.json'

export default defineConfig({
  plugins: [
    process.env.NODE_ENV === 'development' && vueDevTools(),
    vue(),
    AutoImport({
      imports: [
        'vue',
        'vue-router',
        'pinia',
        {
          '@iconify/vue': ['Icon']
        }
      ],
      resolvers: [
        ElementPlusResolver(),
        IconsResolver({
          prefix: 'Icon'
        })
      ],
      dts: 'src/auto-imports.d.ts',
      eslintrc: {
        enabled: true,
        filepath: './.eslintrc-auto-import.json',
        globalsPropValue: true
      }
    }),
    Components({
      resolvers: [
        ElementPlusResolver(),
        IconsResolver({
          enabledCollections: ['ep', 'mdi', 'ri']
        })
      ],
      dts: 'src/components.d.ts'
    }),
    Icons({
      autoInstall: false
    })
  ],
  define: {
    __APP_VERSION__: JSON.stringify(pkg.version)
  },
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  },
  server: {
    host: '0.0.0.0',
    port: 3000,
    open: true,
    proxy: {
      // 后端 API
      '/api': {
        target: 'https://tg-live-game.pwtk.cc',
        changeOrigin: true,
        secure: false // 禁用 SSL 证书验证（开发环境）
      },
      // 摄像头 PTZ 代理 - 固定 IP（开发环境）
      '/camera-proxy': {
        target: 'http://192.168.0.64',
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path.replace(/^\/camera-proxy/, '')
      }
    }
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "@/assets/styles/variables.scss" as *;`,
        silenceDeprecations: ['legacy-js-api']
      }
    }
  },
  build: {
    emptyOutDir: true, // 确保每次构建前清空 dist 目录
    chunkSizeWarningLimit: 1500,
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            // Vue 核心、Element Plus、vue-i18n 放在一起，避免循环依赖和模块初始化顺序问题
            if (
              id.includes('vue') ||
              id.includes('@vue') ||
              id.includes('element-plus') ||
              id.includes('@element-plus') ||
              id.includes('pinia') ||
              id.includes('vue-router') ||
              id.includes('vue-i18n')
            ) {
              return 'vendor'
            }
          }
        }
      }
    }
  }
})
