import { execSync } from 'child_process';
import { logger } from './logger.js';

/**
 * Git 操作工具
 */
export class GitUtils {
  /**
   * 克隆仓库
   */
  static async clone(repoUrl: string, targetDir: string, options?: { branch?: string; depth?: number }): Promise<void> {
    try {
      const { branch, depth = 1 } = options || {};
      
      let command = `git clone`;
      
      if (depth) {
        command += ` --depth ${depth}`;
      }
      
      if (branch) {
        command += ` --branch ${branch}`;
      }
      
      command += ` ${repoUrl} ${targetDir}`;
      
      logger.info(`Cloning repository: ${repoUrl}`);
      execSync(command, { stdio: 'inherit' });
      
      // 删除 .git 目录
      const gitDir = `${targetDir}/.git`;
      if (await import('fs-extra').then(fs => fs.pathExists(gitDir))) {
        await import('fs-extra').then(fs => fs.remove(gitDir));
      }
      
      logger.success(`Repository cloned successfully to ${targetDir}`);
    } catch (error) {
      logger.error(`Failed to clone repository: ${repoUrl}`);
      throw error;
    }
  }

  /**
   * 初始化 Git 仓库
   */
  static async init(dir: string): Promise<void> {
    try {
      logger.info('Initializing Git repository...');
      execSync('git init', { cwd: dir, stdio: 'inherit' });
      logger.success('Git repository initialized');
    } catch (error) {
      logger.error('Failed to initialize Git repository');
      throw error;
    }
  }

  /**
   * 添加文件到 Git
   */
  static async add(dir: string, files: string = '.'): Promise<void> {
    try {
      execSync(`git add ${files}`, { cwd: dir, stdio: 'inherit' });
    } catch (error) {
      logger.error('Failed to add files to Git');
      throw error;
    }
  }

  /**
   * 提交更改
   */
  static async commit(dir: string, message: string): Promise<void> {
    try {
      execSync(`git commit -m "${message}"`, { cwd: dir, stdio: 'inherit' });
      logger.success(`Changes committed: ${message}`);
    } catch (error) {
      logger.error('Failed to commit changes');
      throw error;
    }
  }

  /**
   * 检查是否在 Git 仓库中
   */
  static isGitRepo(dir: string): boolean {
    try {
      execSync('git rev-parse --git-dir', { cwd: dir, stdio: 'pipe' });
      return true;
    } catch {
      return false;
    }
  }
}
