/**
 * 恢复检查点工具
 */

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 checkpointRestoreTool: ToolWithMetadata = {
  name: 'checkpoint_restore',
  description: loadDescription('checkpoint_restore'),
  metadata: {
    name: 'checkpoint_restore',
    category: 'core',
    description: '恢复到指定的检查点',
    keywords: [
      'checkpoint',
      'restore',
      'rollback',
      'undo',
      '检查点',
      '恢复',
      '回滚',
      '撤销',
    ],
    deferLoading: true,
  },
  parameters: {
    checkpoint_id: {
      type: 'string',
      description: '要恢复的检查点 ID 或 commit hash',
      required: true,
    },
    files: {
      type: 'string',
      description: '只恢复指定文件，多个文件用逗号分隔 (可选)',
      required: false,
    },
    dry_run: {
      type: 'boolean',
      description: '预览模式，不实际执行恢复',
      required: false,
    },
  },
  execute: async (params: Record<string, unknown>): Promise<ToolResult> => {
    const checkpointId = params.checkpoint_id as string;
    const filesStr = params.files as string | undefined;
    const dryRun = params.dry_run as boolean | undefined;

    if (!checkpointId) {
      return {
        success: false,
        output: '',
        error: '请指定要恢复的检查点 ID',
      };
    }

    try {
      const manager = getCheckpointManager();

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

      await manager.initialize();

      // 验证检查点存在
      const checkpoint = await manager.getCheckpoint(checkpointId);
      if (!checkpoint) {
        return {
          success: false,
          output: '',
          error: `找不到检查点: ${checkpointId}`,
        };
      }

      // 解析文件列表
      const files = filesStr
        ? filesStr.split(',').map((f) => f.trim()).filter(Boolean)
        : undefined;

      // 执行恢复
      const result = await manager.rollback({
        target: checkpointId,
        files,
        dryRun,
      });

      if (dryRun) {
        const lines = [
          `预览: 恢复到检查点 ${checkpoint.commitHash.slice(0, 8)}`,
          '',
          '将恢复以下文件:',
        ];

        for (const file of result.restoredFiles) {
          lines.push(`  - ${file}`);
        }

        lines.push('');
        lines.push('(使用 dry_run=false 执行实际恢复)');

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

      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 = [
        `✓ 已恢复到检查点 ${checkpoint.commitHash.slice(0, 8)}`,
        '',
        `恢复了 ${result.restoredFiles.length} 个文件:`,
      ];

      for (const file of result.restoredFiles.slice(0, 10)) {
        lines.push(`  - ${file}`);
      }

      if (result.restoredFiles.length > 10) {
        lines.push(`  ... 还有 ${result.restoredFiles.length - 10} 个文件`);
      }

      if (result.previousCommit) {
        lines.push('');
        lines.push(`提示: 可以使用 checkpoint_restore 恢复到 ${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),
      };
    }
  },
};
