import uni from '@dcloudio/vite-plugin-uni'
import fs from 'fs'
import path from 'path'
import { defineConfig } from 'vite'
import WindiCSS from 'vite-plugin-windicss'

const srcPath = path.resolve(__dirname, 'src/cloudfunctions')
const destPath = path.resolve(
  __dirname,
  'dist',
  process.env.NODE_ENV === 'production' ? 'build' : 'dev',
  process.env.UNI_PLATFORM || 'mp-weixin',
  'cloudfunctions'
)

console.log('📁 云函数复制配置:')
console.log(`   源: ${srcPath}`)
console.log(`   目标: ${destPath}`)
console.log(`   源存在: ${fs.existsSync(srcPath)}`)

// 递归复制目录的函数
function copyDir(src: string, dest: string) {
  if (!fs.existsSync(dest)) {
    fs.mkdirSync(dest, { recursive: true })
  }

  const entries = fs.readdirSync(src, { withFileTypes: true })

  for (const entry of entries) {
    const srcPath = path.join(src, entry.name)
    const destPath = path.join(dest, entry.name)

    if (entry.isDirectory()) {
      copyDir(srcPath, destPath)
    } else {
      fs.copyFileSync(srcPath, destPath)
    }
  }
}

// 自定义 Vite 插件
function copyCloudFunctions() {
  return {
    name: 'copy-cloud-functions',
    writeBundle() {
      if (!fs.existsSync(srcPath)) {
        console.log('⚠️ 源目录不存在，跳过复制')
        return
      }

      try {
        // 删除旧目录
        if (fs.existsSync(destPath)) {
          fs.rmSync(destPath, { recursive: true, force: true })
        }

        // 复制新目录
        copyDir(srcPath, destPath)
        console.log('✅ 云函数复制成功！')
        console.log(`   目标: ${destPath}`)
      } catch (err) {
        console.error('❌ 复制失败:', err)
      }
    }
  }
}

export default defineConfig({
  plugins: [
    // copyCloudFunctions(), // 添加自定义复制插件
    WindiCSS({
      scan: {
        dirs: ['.'],
        fileExtensions: ['vue', 'js', 'ts']
      }
    }),
    uni()
  ]
})
