import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { batiaoPlugin } from '@batiao/batiao-sdk-vue-vite/onBuild'
import proxy from './src/proxy.cjs'
import fs from 'fs'
import axios from 'axios'

const copyPublicPlugin = () => {
  return {
    name: 'copy-src-public',
    closeBundle() {
      const srcDir = resolve(__dirname, 'src/public')
      const destDir = resolve(__dirname, 'dist/src/public')
      try {
        if (fs.existsSync(srcDir)) {
          fs.mkdirSync(destDir, { recursive: true })
          fs.cpSync(srcDir, destDir, { recursive: true })
          console.log('[copy-src-public] 成功将 src/public 复制到 dist/src/public')
        }
      } catch (err) {
        console.error('[copy-src-public] 复制失败:', err)
      }
    }
  }
}

const seoInjectionPlugin = () => {
  return {
    name: 'seo-injection',
    async transformIndexHtml(html, ctx) {
      if (ctx.originalUrl && ctx.originalUrl.includes('/article-detail')) {
        const urlObj = new URL(ctx.originalUrl, 'http://localhost')
        const id = urlObj.searchParams.get('id')
        if (id) {
          try {
            const res = await axios.get(`http://wechat.wenyitu.com/api/articles/${id}`)
            const article = res.data
            if (article) {
              let newHtml = html
              if (article.title) {
                newHtml = newHtml.replace(/<title>.*?<\/title>/, `<title>${article.title} - 装样大师</title>`)
              }
              if (article.seo_keywords) {
                newHtml = newHtml.replace(/<meta name="keywords" content="[^"]*"/, `<meta name="keywords" content="${article.seo_keywords}"`)
              }
              if (article.seo_description) {
                newHtml = newHtml.replace(/<meta name="description" content="[^"]*"/, `<meta name="description" content="${article.seo_description}"`)
              }
              return newHtml
            }
          } catch (e) {
            console.error('[seo-injection] 获取详情失败:', e.message)
          }
        }
      } else if (ctx.originalUrl && ctx.originalUrl.includes('/article') && ctx.originalUrl.includes('category_id=')) {
        const urlObj = new URL(ctx.originalUrl, 'http://localhost')
        const categoryId = urlObj.searchParams.get('category_id')
        if (categoryId) {
          try {
            const res = await axios.get(`http://wechat.wenyitu.com/api/articles?category_id=${categoryId}&page=1&per_page=10`)
            const data = res.data
            if (data && data.items && data.items.length > 0 && data.items[0].category) {
              let newHtml = html
              const category = data.items[0].category
              if (category.seo_keywords) {
                newHtml = newHtml.replace(/<meta name="keywords" content="[^"]*"/, `<meta name="keywords" content="${category.seo_keywords}"`)
              }
              if (category.seo_description) {
                newHtml = newHtml.replace(/<meta name="description" content="[^"]*"/, `<meta name="description" content="${category.seo_description}"`)
              }
              return newHtml
            }
          } catch (e) {
            console.error('[seo-injection] 获取列表分类失败:', e.message)
          }
        }
      }
      return html
    }
  }
}

export default defineConfig({
  plugins: [vue(), batiaoPlugin(), copyPublicPlugin(), seoInjectionPlugin()],
  css: {
    preprocessorOptions: {
      scss: {
        api: 'modern-compiler'
      }
    }
  },
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  },
  build: {
    chunkSizeWarningLimit: 2000,
    rollupOptions: {
      onwarn(warning, warn) {
        if (warning.code === 'UNRESOLVED_IMPORT' || warning.code === 'UNUSED_EXTERNAL_IMPORT') return;
        warn(warning);
      }
    }
  },
  server: {
    //通过电脑ip访问设置
    host: '0.0.0.0',
    port: 3000,
    proxy
  }
})
