import fs from 'fs'
import path from 'path'
import { execSync } from 'child_process'
import type { Plugin } from 'vite'
import { formatDateTime } from '../src/utils'

export default function buildInfoPlugin(mode: string): Plugin {
  return {
    name: 'build-info-plugin',
    closeBundle() {
      const pkg = JSON.parse(fs.readFileSync('./package.json', 'utf-8'))

      const buildInfo = {
        version: pkg.version,
        buildTime: formatDateTime(new Date()),
        branch: execSync('git rev-parse --abbrev-ref HEAD').toString().trim(),
        commitHash: execSync('git rev-parse --short HEAD').toString().trim(),
        env: mode,
      }

      const outDir = path.resolve(process.cwd(), 'dist')
      fs.writeFileSync(path.join(outDir, 'version.json'), JSON.stringify(buildInfo, null, 2))

      console.log('\x1b[36m📦 已生成 version.json\x1b[0m')
      console.log(buildInfo)
    },
  }
}
