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 gitLogTool: ToolWithMetadata = {
  name: 'git_log',
  description: loadDescription('git_log'),
  metadata: {
    name: 'git_log',
    category: 'git',
    description: '查看 Git 提交历史',
    keywords: ['git', 'log', 'history', '历史', '提交', 'commit', 'commits'],
    deferLoading: false,
  },
  parameters: {
    limit: {
      type: 'number',
      description: '显示的提交数量（默认 10）',
      required: false,
    },
    oneline: {
      type: 'boolean',
      description: '单行显示（--oneline）',
      required: false,
    },
    file: {
      type: 'string',
      description: '查看指定文件的提交历史',
      required: false,
    },
    author: {
      type: 'string',
      description: '筛选指定作者的提交',
      required: false,
    },
    since: {
      type: 'string',
      description: '起始日期（如 "2024-01-01" 或 "1 week ago"）',
      required: false,
    },
    graph: {
      type: 'boolean',
      description: '显示分支图（--graph）',
      required: false,
    },
  },
  execute: async (params: Record<string, unknown>): Promise<ToolResult> => {
    const limit = (params.limit as number) || 10;
    const oneline = params.oneline as boolean;
    const file = params.file as string | undefined;
    const author = params.author as string | undefined;
    const since = params.since as string | undefined;
    const graph = params.graph as boolean;

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

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

    try {
      const args: string[] = ['log', `-${limit}`];

      if (oneline) {
        args.push('--oneline');
      } else {
        // 默认格式：更易读
        args.push('--format=%h %s (%an, %ar)');
      }

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

      if (author) {
        args.push(`--author=${author}`);
      }

      if (since) {
        args.push(`--since="${since}"`);
      }

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

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

      return {
        success: true,
        output: stdout || '(无提交记录)',
      };
    } catch (error) {
      const execError = error as { stdout?: string; stderr?: string; message: string };
      return {
        success: false,
        output: execError.stdout || '',
        error: execError.stderr || execError.message,
      };
    }
  },
};
