/**
 * 检查点差异工具
 */

import type { ToolResult } from '../../types/index.js';
import type { ToolWithMetadata } from '../types.js';
import { loadDescription } from '../load_description.js';
import { getCheckpointManager } from '../../checkpoint/index.js';

export const checkpointDiffTool: ToolWithMetadata = {
  name: 'checkpoint_diff',
  description: loadDescription('checkpoint_diff'),
  metadata: {
    name: 'checkpoint_diff',
    category: 'core',
    description: '显示检查点与当前工作区的差异',
    keywords: [
      'checkpoint',
      'diff',
      'compare',
      'changes',
      '检查点',
      '差异',
      '比较',
      '变更',
    ],
    deferLoading: true,
  },
  parameters: {
    checkpoint_id: {
      type: 'string',
      description: '检查点 ID 或 commit hash (默认为最近的检查点)',
      required: false,
    },
    file: {
      type: 'string',
      description: '指定文件路径查看详细差异 (可选)',
      required: false,
    },
  },
  execute: async (params: Record<string, unknown>): Promise<ToolResult> => {
    const checkpointId = params.checkpoint_id as string | undefined;
    const file = params.file as string | undefined;

    try {
      const manager = getCheckpointManager();

      if (!manager.isEnabled()) {
        return {
          success: false,
          output: '',
          error: '检查点系统已禁用',
        };
      }

      await manager.initialize();

      // 获取目标检查点
      let targetCheckpoint;
      if (checkpointId) {
        targetCheckpoint = await manager.getCheckpoint(checkpointId);
        if (!targetCheckpoint) {
          return {
            success: false,
            output: '',
            error: `找不到检查点: ${checkpointId}`,
          };
        }
      } else {
        targetCheckpoint = await manager.getLatestCheckpoint();
        if (!targetCheckpoint) {
          return {
            success: true,
            output: '暂无检查点',
          };
        }
      }

      // 显示文件详细差异
      if (file) {
        const fileDiff = await manager.getFileDiff(targetCheckpoint.id, file);

        const lines = [
          `文件差异: ${file}`,
          `检查点: ${targetCheckpoint.commitHash.slice(0, 8)}`,
          `变更类型: ${fileDiff.type}`,
          '',
        ];

        if (fileDiff.patch) {
          lines.push('```diff');
          lines.push(fileDiff.patch);
          lines.push('```');
        } else if (fileDiff.type === 'added') {
          lines.push('(新文件)');
        } else if (fileDiff.type === 'deleted') {
          lines.push('(已删除)');
        }

        return {
          success: true,
          output: lines.join('\n'),
        };
      }

      // 显示概要差异
      const diff = await manager.getDiff(targetCheckpoint.id);

      if (diff.files.length === 0) {
        return {
          success: true,
          output: `检查点 ${targetCheckpoint.commitHash.slice(0, 8)} 与当前工作区相同`,
        };
      }

      const lines = [
        `检查点 ${targetCheckpoint.commitHash.slice(0, 8)} 与当前工作区的差异:`,
        '',
        `  +${diff.totalInsertions} 行添加  -${diff.totalDeletions} 行删除`,
        '',
        '变更的文件:',
      ];

      for (const fileChange of diff.files) {
        const symbol =
          fileChange.type === 'added'
            ? '+'
            : fileChange.type === 'deleted'
              ? '-'
              : fileChange.type === 'renamed'
                ? 'R'
                : 'M';

        let line = `  ${symbol} ${fileChange.path}`;
        if (fileChange.oldPath) {
          line = `  ${symbol} ${fileChange.oldPath} -> ${fileChange.path}`;
        }

        if (fileChange.insertions || fileChange.deletions) {
          line += ` (+${fileChange.insertions || 0} -${fileChange.deletions || 0})`;
        }

        lines.push(line);
      }

      return {
        success: true,
        output: lines.join('\n'),
      };
    } catch (error) {
      return {
        success: false,
        output: '',
        error: error instanceof Error ? error.message : String(error),
      };
    }
  },
};
