/**
 * 列出检查点工具
 */

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 checkpointListTool: ToolWithMetadata = {
  name: 'checkpoint_list',
  description: loadDescription('checkpoint_list'),
  metadata: {
    name: 'checkpoint_list',
    category: 'core',
    description: '列出所有可用的检查点',
    keywords: [
      'checkpoint',
      'list',
      'show',
      'history',
      '检查点',
      '列表',
      '历史',
    ],
    deferLoading: true,
  },
  parameters: {
    limit: {
      type: 'number',
      description: '最多显示的检查点数量 (默认 10)',
      required: false,
    },
  },
  execute: async (params: Record<string, unknown>): Promise<ToolResult> => {
    const limit = (params.limit as number) || 10;

    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: true,
          output: '暂无检查点',
        };
      }

      const displayCheckpoints = checkpoints.slice(0, limit);
      const lines = [`共 ${checkpoints.length} 个检查点:\n`];

      for (const cp of displayCheckpoints) {
        const date = new Date(cp.timestamp).toLocaleString();
        const hash = cp.commitHash.slice(0, 8);
        const name = cp.name ? ` "${cp.name}"` : '';
        const files = cp.filesChanged > 0 ? ` (${cp.filesChanged} files)` : '';

        lines.push(`  ${hash}${name}${files}`);
        lines.push(`    ${cp.description || cp.trigger}`);
        lines.push(`    ${date}`);
        lines.push('');
      }

      if (checkpoints.length > limit) {
        lines.push(`  ... 还有 ${checkpoints.length - limit} 个检查点`);
      }

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