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

// 自定义插件：修改 HTML 以支持 file:// 协议
const fixHtmlForFileProtocol = () => ({
  name: 'fix-html-for-file',
  closeBundle() {
    const distPath = path.resolve(__dirname, 'dist')
    const htmlPath = path.join(distPath, 'index.html')

    if (!fs.existsSync(htmlPath)) return

    let html = fs.readFileSync(htmlPath, 'utf-8')

    // 移除所有 crossorigin 属性
    html = html.replace(/ crossorigin/g, '')

    // 移除所有 type="module"
    html = html.replace(/ type="module"/g, '')

    // 将 script 从 head 移到 body 底部（在 #app 之后）
    const scriptMatch = html.match(/<script src="([^"]+)"><\/script>/)
    if (scriptMatch) {
      const src = scriptMatch[1]
      // 从 head 中移除 script
      html = html.replace(/<script src="[^"]+"><\/script>\s*/, '')
      // 在 #app 之后添加 script
      html = html.replace(
        /<div id="app"><\/div>/,
        `<div id="app"></div>\n    <script src="${src}"></script>`
      )
    }

    fs.writeFileSync(htmlPath, html)
    console.log('HTML fixed for file:// protocol')
  }
})

export default defineConfig({
  base: './',
  plugins: [
    vue(),
    AutoImport({
      resolvers: [ElementPlusResolver()]
    }),
    Components({
      resolvers: [ElementPlusResolver()]
    }),
    fixHtmlForFileProtocol()
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  },
  server: {
    port: 3005,
    // host: true
    host: '0.0.0.0'
  },
  build: {
    outDir: 'dist',
    assetsDir: '',
    cssCodeSplit: false,
    rollupOptions: {
      output: {
        format: 'iife',
        entryFileNames: 'js/[name]-[hash].js',
        chunkFileNames: 'js/[name]-[hash].js',
        assetFileNames: (assetInfo) => {
          if (/\.(css)$/i.test(assetInfo.name)) {
            return 'css/[name]-[hash][extname]'
          }
          if (/\.(png|jpe?g|gif|svg|webp|ico)$/i.test(assetInfo.name)) {
            return 'images/[name]-[hash][extname]'
          }
          if (/\.(woff2?|eot|ttf|otf)$/i.test(assetInfo.name)) {
            return 'fonts/[name]-[hash][extname]'
          }
          return 'assets/[name]-[hash][extname]'
        }
      }
    }
  }
})