import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { readFileSync, writeFileSync } from 'fs'
import { join } from 'path'

function getVersion() {
  try {
    const versionFile = join(__dirname, '..', 'config', 'VERSION')
    const content = readFileSync(versionFile, 'utf-8')
    const match = content.match(/^VERSION=(.*)$/m)
    return match ? match[1].trim() : '0.0.0'
  } catch (e) {
    return '0.0.0'
  }
}

const APP_VERSION = getVersion()

function updateHtmlTitle() {
  try {
    const htmlPath = join(__dirname, 'index.html')
    let htmlContent = readFileSync(htmlPath, 'utf-8')
    htmlContent = htmlContent.replace(
      /<title>甲辰收藏 v[\d.]+<\/title>/,
      `<title>甲辰收藏 v${APP_VERSION}</title>`
    )
    writeFileSync(htmlPath, htmlContent, 'utf-8')
  } catch (e) {}
}

updateHtmlTitle()

export default defineConfig({
  plugins: [react()],
  define: {
    'import.meta.env.APP_VERSION': JSON.stringify(APP_VERSION)
  },
  build: {
    minify: false,
    rollupOptions: {
      treeshake: false,
      output: {
        manualChunks: undefined
      }
    },
    esbuild: {
      treeShaking: false
    }
  }
})
