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';

const execAsync = promisify(exec);

export const gitPullTool: ToolWithMetadata = {
  name: 'git_pull',
  description: loadDescription('git_pull'),
  metadata: {
    name: 'git_pull',
    category: 'git',
    description: '从远程仓库拉取更新',
    keywords: ['git', 'pull', '拉取', 'fetch', 'download', '下载', 'update', '更新'],
    deferLoading: false,
  },
  parameters: {
    remote: {
      type: 'string',
      description: '远程仓库名（默认 origin）',
      required: false,
    },
    branch: {
      type: 'string',
      description: '分支名（默认当前分支）',
      required: false,
    },
    rebase: {
      type: 'boolean',
      description: '使用 rebase 而非 merge（--rebase）',
      required: false,
    },
  },
  execute: async (params: Record<string, unknown>): Promise<ToolResult> => {
    const remote = (params.remote as string) || 'origin';
    const branch = params.branch as string | undefined;
    const rebase = params.rebase as boolean;

    // 权限检查
    const permissionManager = getPermissionManager();
    const permResult = await permissionManager.checkGitPermission({
      operation: 'pull',
      remote,
      target: branch,
    });

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

    try {
      const args: string[] = ['pull'];

      if (rebase) {
        args.push('--rebase');
      }

      args.push(remote);

      if (branch) {
        args.push(branch);
      }

      const { stdout, stderr } = await execAsync(`git ${args.join(' ')}`, {
        cwd: process.cwd(),
        timeout: 120000,
      });

      const output = stdout || stderr || '已是最新';

      return {
        success: true,
        output,
      };
    } catch (error) {
      const execError = error as { stdout?: string; stderr?: string; message: string };
      const errorMsg = execError.stderr || execError.message;

      // 检查冲突
      if (errorMsg.includes('CONFLICT') || errorMsg.includes('conflict')) {
        return {
          success: false,
          output: execError.stdout || '',
          error: `拉取时发生合并冲突，请手动解决冲突后使用 git_add 和 git_commit 提交。\n${errorMsg}`,
        };
      }

      // 检查本地变更
      if (errorMsg.includes('local changes') || errorMsg.includes('uncommitted changes')) {
        return {
          success: false,
          output: execError.stdout || '',
          error: `本地有未提交的变更。请先提交或暂存（git_stash）本地变更。\n${errorMsg}`,
        };
      }

      return {
        success: false,
        output: execError.stdout || '',
        error: errorMsg,
      };
    }
  },
};
