import { readFileSync, writeFileSync, cpSync } from 'node:fs'
import { resolve, basename } from 'node:path'
import { execSync } from 'node:child_process'
import type { Plugin } from 'vite'

/**
 * 打包时自增版本号、复制配置文件、压缩 dist 为 zip
 */
export function bumpVersion(mode: string): Plugin {
  return {
    name: 'bump-version-and-copy',
    writeBundle(options) {
      const outDir = options.dir
      if (!outDir) return

      const suffix = mode === 'production' ? 'pro' : 'test'
      const src = `src/config/plugin.properties.${suffix}`

      let content = readFileSync(src, 'utf-8')
      const match = content.match(/version_code=(\d+)/)
      if (!match) return

      const oldCode = Number(match[1])
      const newCode = oldCode + 1

      const major = Math.floor(newCode / 100000)
      const minor = Math.floor((newCode % 100000) / 1000)
      const patch = String(newCode % 1000).padStart(3, '0')
      const versionName = `${major}.${minor}.${patch}`

      content = content
        .replace(/version_code=\d+/, `version_code=${newCode}`)
        .replace(/version_name=[^;\n]+/, `version_name=${versionName}`)

      writeFileSync(src, content)
      writeFileSync(resolve(outDir, '..', 'plugin.properties'), content)

      // 复制 config.properties 到 dist/www/
      cpSync('src/config/config.properties', resolve(outDir, 'config.properties'))

      console.log(`[plugin.properties] version: ${oldCode} → ${newCode} (${versionName})`)

      // 压缩 dist 为 zip
      const distDir = resolve(outDir, '..')
      const zipName = `dist_${newCode}.zip`
      execSync(`cd ${distDir} && zip -r ${zipName} www plugin.properties config.properties`, { stdio: 'inherit' })
      console.log(`[zip] 已生成 ${basename(distDir)}/${zipName}`)
    },
  }
}
