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 gitDiffTool: ToolWithMetadata = {
  name: 'git_diff',
  description: loadDescription('git_diff'),
  metadata: {
    name: 'git_diff',
    category: 'git',
    description: '查看 Git 变更差异',
    keywords: ['git', 'diff', '差异', '对比', 'changes', '变更', 'compare'],
    deferLoading: false,
  },
  parameters: {
    path: {
      type: 'string',
      description: '指定文件或目录路径',
      required: false,
    },
    staged: {
      type: 'boolean',
      description: '显示已暂存的变更（--staged）',
      required: false,
    },
    commit: {
      type: 'string',
      description: '与指定提交对比（如 HEAD~1, commit-hash）',
      required: false,
    },
    stat: {
      type: 'boolean',
      description: '仅显示统计信息（--stat）',
      required: false,
    },
  },
  execute: async (params: Record<string, unknown>): Promise<ToolResult> => {
    const path = params.path as string | undefined;
    const staged = params.staged as boolean;
    const commit = params.commit as string | undefined;
    const stat = params.stat as boolean;

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

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

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

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

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

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

      if (path) {
        args.push('--', path);
      }

      const { stdout, stderr } = await execAsync(`git ${args.join(' ')}`, {
        cwd: process.cwd(),
        timeout: 60000,
        maxBuffer: 1024 * 1024 * 10,
      });

      const output = stdout || '(无差异)';

      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,
      };
    }
  },
};
