/**
 * 撤销操作工具 (快捷回滚)
 */

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 undoTool: ToolWithMetadata = {
  name: 'undo',
  description: loadDescription('undo'),
  metadata: {
    name: 'undo',
    category: 'core',
    description: '撤销上一次文件操作，回滚到最近的检查点',
    keywords: ['undo', 'rollback', 'revert', '撤销', '回滚', '恢复'],
    deferLoading: false, // 常用命令，始终加载
  },
  parameters: {
    confirm: {
      type: 'boolean',
      description: '确认执行撤销操作 (默认 true)',
      required: false,
    },
  },
  execute: async (params: Record<string, unknown>): Promise<ToolResult> => {
    const confirm = params.confirm !== false;

    try {
      const manager = getCheckpointManager();

      if (!manager.isEnabled()) {
        return {
          success: false,
          output: '',
          error: '检查点系统已禁用，无法执行撤销操作',
        };
      }

      await manager.initialize();

      // 获取最近两个检查点
      const checkpoints = await manager.listCheckpoints();

      if (checkpoints.length === 0) {
        return {
          success: false,
          output: '',
          error: '没有可用的检查点，无法执行撤销操作',
        };
      }

      // 预览模式
      if (!confirm) {
        const targetCheckpoint =
          checkpoints.length > 1 ? checkpoints[1] : checkpoints[0];

        const diff = await manager.getDiff(targetCheckpoint.id);

        const lines = [
          '预览: 撤销将恢复以下文件变更:',
          '',
          `目标检查点: ${targetCheckpoint.commitHash.slice(0, 8)}`,
          `  ${targetCheckpoint.description || targetCheckpoint.trigger}`,
          `  ${new Date(targetCheckpoint.timestamp).toLocaleString()}`,
          '',
        ];

        if (diff.files.length > 0) {
          lines.push('将恢复的文件:');
          for (const file of diff.files.slice(0, 10)) {
            const symbol =
              file.type === 'added'
                ? '+'
                : file.type === 'deleted'
                  ? '-'
                  : 'M';
            lines.push(`  ${symbol} ${file.path}`);
          }
          if (diff.files.length > 10) {
            lines.push(`  ... 还有 ${diff.files.length - 10} 个文件`);
          }
        } else {
          lines.push('(无文件变更)');
        }

        lines.push('');
        lines.push('使用 confirm=true 执行撤销');

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

      // 执行撤销
      const result = await manager.undo();

      if (!result.success) {
        const errorLines = ['撤销失败:'];
        for (const err of result.errors) {
          errorLines.push(`  ${err.file}: ${err.error}`);
        }
        return {
          success: false,
          output: '',
          error: errorLines.join('\n'),
        };
      }

      const lines = [
        '✓ 撤销成功',
        '',
        `恢复了 ${result.restoredFiles.length} 个文件`,
      ];

      if (result.restoredFiles.length > 0 && result.restoredFiles.length <= 5) {
        for (const file of result.restoredFiles) {
          lines.push(`  - ${file}`);
        }
      }

      if (result.previousCommit) {
        lines.push('');
        lines.push(
          `提示: 使用 checkpoint_restore --checkpoint_id ${result.previousCommit.slice(0, 8)} 可以撤销此操作`
        );
      }

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