import type { Plugin } from 'vite';
import { execSync } from 'node:child_process';
import path from 'node:path';

/**
 * 获取 Git 提交哈希值插件
 * Git 仓库在上一级目录
 */
export default function gitHashPlugin(): Plugin {
  let gitHash = 'unknown';
  let gitBranch = 'unknown';
  let gitDate = 'unknown';

  try {
    // Git 仓库在上一级目录
    const execOptions = { cwd: path.resolve(__dirname, '../../..'), encoding: 'utf-8' as BufferEncoding };

    // 获取完整的 commit hash
    gitHash = execSync('git rev-parse HEAD', execOptions)
      .toString()
      .trim();

    // 获取短 hash (前7位)
    const shortHash = gitHash.substring(0, 7);

    // 获取分支名
    gitBranch = execSync('git rev-parse --abbrev-ref HEAD', execOptions)
      .toString()
      .trim();

    // 获取提交时间
    gitDate = execSync('git log -1 --format=%cd --date=iso', execOptions)
      .toString()
      .trim();

    console.log(`\n📦 Git Info:`);
    console.log(`   Branch: ${gitBranch}`);
    console.log(`   Commit: ${shortHash}`);
    console.log(`   Date: ${gitDate}\n`);

    gitHash = shortHash; // 使用短 hash
  } catch (error: any) {
    console.warn('⚠️  无法获取 Git 信息:', error?.message || error);
  }

  return {
    name: 'vite-plugin-git-hash',
    config() {
      // 在 config 钩子中返回配置
      return {
        define: {
          __GIT_HASH__: JSON.stringify(gitHash),
          __GIT_BRANCH__: JSON.stringify(gitBranch),
          __GIT_DATE__: JSON.stringify(gitDate),
          __BUILD_TIME__: JSON.stringify(new Date().toISOString()),
        },
      };
    },
  };
}
