/**
 * 创建检查点工具
 */

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 checkpointCreateTool: ToolWithMetadata = {
  name: 'checkpoint_create',
  description: loadDescription('checkpoint_create'),
  metadata: {
    name: 'checkpoint_create',
    category: 'core',
    description: '创建一个新的工作区检查点快照',
    keywords: [
      'checkpoint',
      'create',
      'snapshot',
      'save',
      '检查点',
      '快照',
      '保存',
    ],
    deferLoading: true,
  },
  parameters: {
    name: {
      type: 'string',
      description: '检查点名称 (可选)',
      required: false,
    },
    description: {
      type: 'string',
      description: '检查点描述 (可选)',
      required: false,
    },
  },
  execute: async (params: Record<string, unknown>): Promise<ToolResult> => {
    const name = params.name as string | undefined;
    const description = params.description as string | undefined;

    try {
      const manager = getCheckpointManager();

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

      await manager.initialize();

      const checkpoint = await manager.createCheckpoint({
        name,
        description,
        trigger: 'manual',
      });

      const lines = [
        `✓ 检查点已创建`,
        `  ID: ${checkpoint.id}`,
        `  Commit: ${checkpoint.commitHash.slice(0, 8)}`,
      ];

      if (checkpoint.name) {
        lines.push(`  名称: ${checkpoint.name}`);
      }
      if (checkpoint.filesChanged > 0) {
        lines.push(`  文件变更: ${checkpoint.filesChanged} 个`);
      }
      lines.push(`  时间: ${new Date(checkpoint.timestamp).toLocaleString()}`);

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