import { defineConfig } from 'vite'
import { createVuePlugin } from 'vite-plugin-vue2'
import legacy from '@vitejs/plugin-legacy'
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')

    // 提取 CSS 文件路径
    const cssMatch = html.match(/<link rel="stylesheet" href="([^"]+)"/)
    const cssPath = cssMatch ? cssMatch[1] : null

    // 如果有 CSS 文件，内联它
    if (cssPath) {
      const cssFullPath = path.join(distPath, cssPath.replace(/^\.\//, ''))
      if (fs.existsSync(cssFullPath)) {
        const cssContent = fs.readFileSync(cssFullPath, 'utf-8')
        html = html.replace(
          /<link rel="stylesheet" href="[^"]+"[^>]*>/,
          `<style>${cssContent}</style>`
        )
      }
    }

    // 移除所有 type="module" 的脚本
    html = html.replace(/<script type="module"[^>]*>.*?<\/script>/gs, '')
    html = html.replace(/<script[^>]*type="module"[^>]*>.*?<\/script>/gs, '')
    html = html.replace(/<script crossorigin type="module" src="[^"]+"><\/script>/g, '')
    html = html.replace(/<script type="module" crossorigin src="[^"]+"><\/script>/g, '')

    // 保留 legacy 脚本，但移除 crossorigin 属性（在 file:// 协议下不需要）
    html = html.replace(/crossorigin id="vite-legacy-polyfill"/g, 'id="vite-legacy-polyfill"')
    html = html.replace(/crossorigin id="vite-legacy-entry"/g, 'id="vite-legacy-entry"')

    // 添加 file:// 协议检测
    const fileProtocolCheck = `<script>if(location.protocol==="file:"){window.__vite_is_file_protocol=true}</script>`
    html = html.replace('</head>', `${fileProtocolCheck}</head>`)

    // 移除 nomodule 属性，让所有浏览器都加载 legacy 版本
    html = html.replace(/nomodule/g, '')
    // 移除 Safari 10 nomodule 检测脚本（在 file:// 协议下不需要）
    html = html.replace(/<script[^>]*>!function\(\)\{var e=document,t=e\.createElement\("script"\)[^<]*<\/script>/g, '')
    // 清理多余的空格
    html = html.replace(/<script  /g, '<script ')

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

export default defineConfig({
  base: './',
  plugins: [
    createVuePlugin(),
    legacy({
      targets: ['defaults', 'not IE 11'],
      modernPolyfills: true,
      renderLegacyChunks: true,
      // renderModernChunks: true, // 默认就是 true
    }),
    fixHtmlForFileProtocol()
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  },
  server: {
    port: 3005,
    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]'
        }
      }
    }
  }
})
