import { defineConfig } from 'vite'
import { createVuePlugin } from 'vite-plugin-vue2'
import path from 'path'

// 插件：处理文件协议兼容 - 内联 CSS 到 HTML 并修复资源路径
const inlineCssForFileProtocol = () => ({
  name: 'inline-css-for-file',
  enforce: 'post',
  generateBundle(_, bundle) {
    const htmlFile = Object.keys(bundle).find(key => key.endsWith('.html'))
    const cssFile = Object.keys(bundle).find(key => key.endsWith('.css'))

    if (htmlFile && cssFile) {
      const htmlAsset = bundle[htmlFile]
      const cssAsset = bundle[cssFile]

      let htmlSource = htmlAsset.source.toString()
      let cssContent = cssAsset.source.toString()

      // 修复 CSS 中的资源路径（字体、图片等）
      cssContent = cssContent.replace(
        /url\(['"]?\.\/([^'"\)]+)['"]?\)/g,
        'url(./assets/$1)'
      )

      // 提取 script 标签
      let scriptTag = ''
      htmlSource = htmlSource.replace(/<script[^>]*src="[^"]*"[^>]*><\/script>/g, (match) => {
        scriptTag = match.replace(/type="module"|crossorigin/g, '').replace(/\s+/g, ' ').trim()
        return ''
      })

      // 将 CSS 链接替换为内联 style 标签
      htmlSource = htmlSource.replace(
        /<link[^>]*rel="stylesheet"[^>]*href="[^"]*\.css"[^>]*>/g,
        `<style>${cssContent}</style>`
      )

      // 将 script 移动到 </body> 前
      if (scriptTag) {
        htmlSource = htmlSource.replace('</body>', `  ${scriptTag}\n  </body>`)
      }

      htmlAsset.source = htmlSource

      // 删除独立的 CSS 文件
      delete bundle[cssFile]
    }
  }
})

export default defineConfig({
  base: './',
  plugins: [
    createVuePlugin(),
    inlineCssForFileProtocol()
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  },
  server: {
    port: 3005,
    host: '0.0.0.0'
  },
  build: {
    outDir: 'dist',
    assetsDir: 'assets',
    cssCodeSplit: false,
    rollupOptions: {
      output: {
        format: 'iife',
        inlineDynamicImports: true,
        entryFileNames: 'assets/[name].js',
        assetFileNames: 'assets/[name][extname]'
      }
    }
  }
})
