import { exec } from 'child_process';
import { promisify } from 'util';
import type { ToolResult } from '../../types/index.js';
import type { ToolWithMetadata } from '../types.js';
import { loadDescription } from '../load_description.js';
import { getPermissionManager } from '../../permission/index.js';
import type { GitOperation } from '../../permission/types.js';

const execAsync = promisify(exec);

export const gitBranchTool: ToolWithMetadata = {
  name: 'git_branch',
  description: loadDescription('git_branch'),
  metadata: {
    name: 'git_branch',
    category: 'git',
    description: '管理 Git 分支',
    keywords: ['git', 'branch', '分支', 'branches', 'create', 'delete', '创建', '删除'],
    deferLoading: false,
  },
  parameters: {
    action: {
      type: 'string',
      description: '操作类型: list（默认）, create, delete, rename',
      required: false,
    },
    name: {
      type: 'string',
      description: '分支名称（create/delete/rename 时必填）',
      required: false,
    },
    new_name: {
      type: 'string',
      description: '新分支名（rename 时必填）',
      required: false,
    },
    remote: {
      type: 'boolean',
      description: '显示远程分支（-r）',
      required: false,
    },
    all: {
      type: 'boolean',
      description: '显示所有分支（-a）',
      required: false,
    },
    force: {
      type: 'boolean',
      description: '强制删除未合并的分支（-D）',
      required: false,
    },
  },
  execute: async (params: Record<string, unknown>): Promise<ToolResult> => {
    const action = (params.action as string) || 'list';
    const name = params.name as string | undefined;
    const newName = params.new_name as string | undefined;
    const remote = params.remote as boolean;
    const all = params.all as boolean;
    const force = params.force as boolean;

    // 确定权限操作类型
    let operation: GitOperation = 'branch_list';
    if (action === 'create') {
      operation = 'branch_create';
    } else if (action === 'delete') {
      operation = 'branch_delete';
    } else if (action === 'rename') {
      operation = 'branch_create'; // rename 视为创建操作
    }

    // 权限检查
    const permissionManager = getPermissionManager();
    const permResult = await permissionManager.checkGitPermission({
      operation,
      target: name,
      force,
    });

    if (!permResult.allowed) {
      if (permResult.needsConfirmation) {
        return {
          success: false,
          output: '',
          error: `需要用户确认: git branch ${action}\n原因: ${permResult.reason || '需要权限确认'}`,
        };
      }
      return {
        success: false,
        output: '',
        error: `权限被拒绝: ${permResult.reason || '操作不被允许'}`,
      };
    }

    try {
      let command: string;

      switch (action) {
        case 'list':
          const listArgs = ['branch'];
          if (all) {
            listArgs.push('-a');
          } else if (remote) {
            listArgs.push('-r');
          }
          listArgs.push('-v'); // 显示最后提交信息
          command = `git ${listArgs.join(' ')}`;
          break;

        case 'create':
          if (!name) {
            return {
              success: false,
              output: '',
              error: '创建分支需要提供分支名称（name 参数）',
            };
          }
          command = `git branch ${name}`;
          break;

        case 'delete':
          if (!name) {
            return {
              success: false,
              output: '',
              error: '删除分支需要提供分支名称（name 参数）',
            };
          }
          command = `git branch ${force ? '-D' : '-d'} ${name}`;
          break;

        case 'rename':
          if (!name || !newName) {
            return {
              success: false,
              output: '',
              error: '重命名分支需要提供原名称（name）和新名称（new_name）',
            };
          }
          command = `git branch -m ${name} ${newName}`;
          break;

        default:
          return {
            success: false,
            output: '',
            error: `未知操作: ${action}。支持的操作: list, create, delete, rename`,
          };
      }

      const { stdout, stderr } = await execAsync(command, {
        cwd: process.cwd(),
        timeout: 30000,
      });

      let output = stdout;
      if (action !== 'list' && !stdout) {
        output = `分支操作成功: ${action} ${name}${newName ? ` -> ${newName}` : ''}`;
      }

      return {
        success: true,
        output: output + (stderr ? `\n${stderr}` : ''),
      };
    } catch (error) {
      const execError = error as { stdout?: string; stderr?: string; message: string };
      return {
        success: false,
        output: execError.stdout || '',
        error: execError.stderr || execError.message,
      };
    }
  },
};
