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 gitStatusTool: ToolWithMetadata = {
  name: 'git_status',
  description: loadDescription('git_status'),
  metadata: {
    name: 'git_status',
    category: 'git',
    description: '查看 Git 仓库状态',
    keywords: ['git', 'status', '状态', '仓库', 'repository', 'changes', '变更'],
    deferLoading: false,
  },
  parameters: {
    short: {
      type: 'boolean',
      description: '简短输出格式（-s）',
      required: false,
    },
    branch: {
      type: 'boolean',
      description: '显示分支信息（-b）',
      required: false,
    },
  },
  execute: async (params: Record<string, unknown>): Promise<ToolResult> => {
    const short = params.short as boolean;
    const branch = params.branch !== false; // 默认显示分支

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

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

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

      if (short) {
        args.push('-s');
      }

      if (branch) {
        args.push('-b');
      }

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

      return {
        success: true,
        output: stdout + (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,
      };
    }
  },
};
