/**
 * Skill 搜索工具
 *
 * 搜索可用的 Skills，帮助用户发现适合的 Skill。
 */

import type { ToolWithMetadata } from '../types.js';
import { getSkillRegistry } from '../../skills/registry.js';

/**
 * Skill 搜索工具
 */
export const skillSearchTool: ToolWithMetadata = {
  name: 'skill_search',
  description: '搜索可用的 Skills，根据关键词或分类查找合适的 Skill',
  parameters: {
    query: {
      type: 'string',
      description: '搜索关键词',
      required: false,
    },
    category: {
      type: 'string',
      description: '按分类筛选',
      required: false,
    },
    list_all: {
      type: 'boolean',
      description: '列出所有可用的 Skills',
      required: false,
    },
  },
  metadata: {
    name: 'skill_search',
    category: 'agent',
    description: '搜索可用的 Skills',
    keywords: ['skill', 'search', 'find', '技能', '搜索', '查找'],
    deferLoading: false,
  },
  async execute(params) {
    const { query, category, list_all } = params as {
      query?: string;
      category?: string;
      list_all?: boolean;
    };

    const registry = getSkillRegistry();

    // 列出所有 Skills
    if (list_all) {
      const skills = registry.getEnabled();
      const stats = registry.getStats();

      if (skills.length === 0) {
        return {
          success: true,
          output: '当前没有可用的 Skills。',
        };
      }

      // 按分类分组
      const byCategory = new Map<string, typeof skills>();
      const uncategorized: typeof skills = [];

      for (const skill of skills) {
        if (skill.category) {
          if (!byCategory.has(skill.category)) {
            byCategory.set(skill.category, []);
          }
          byCategory.get(skill.category)!.push(skill);
        } else {
          uncategorized.push(skill);
        }
      }

      let output = `📚 可用的 Skills (共 ${stats.total} 个)\n\n`;

      for (const [cat, catSkills] of byCategory) {
        output += `## ${cat}\n`;
        for (const skill of catSkills) {
          output += `- **${skill.name}**: ${skill.description}`;
          if (skill.source !== 'builtin') {
            output += ` [${skill.source}]`;
          }
          output += '\n';
        }
        output += '\n';
      }

      if (uncategorized.length > 0) {
        output += '## 其他\n';
        for (const skill of uncategorized) {
          output += `- **${skill.name}**: ${skill.description}`;
          if (skill.source !== 'builtin') {
            output += ` [${skill.source}]`;
          }
          output += '\n';
        }
      }

      output += `\n来源统计: 内置 ${stats.bySource.builtin || 0}, 用户 ${stats.bySource.user || 0}, 项目 ${stats.bySource.project || 0}`;

      return {
        success: true,
        output,
        metadata: { stats },
      };
    }

    // 按分类筛选
    if (category) {
      const skills = registry.getByCategory(category);

      if (skills.length === 0) {
        const categories = registry.getCategories();
        return {
          success: true,
          output: `分类 "${category}" 下没有 Skills。\n\n可用分类: ${categories.join(', ')}`,
        };
      }

      let output = `📁 分类 "${category}" 下的 Skills:\n\n`;
      for (const skill of skills) {
        output += `- **${skill.name}**: ${skill.description}\n`;
        if (skill.parameters) {
          const paramNames = Object.keys(skill.parameters);
          output += `  参数: ${paramNames.join(', ')}\n`;
        }
      }

      return {
        success: true,
        output,
        metadata: { category, count: skills.length },
      };
    }

    // 关键词搜索
    if (query) {
      const results = registry.search(query, 10);

      if (results.length === 0) {
        return {
          success: true,
          output: `没有找到匹配 "${query}" 的 Skills。\n\n使用 skill_search({ list_all: true }) 查看所有可用的 Skills。`,
        };
      }

      let output = `🔍 搜索 "${query}" 的结果:\n\n`;
      for (const { skill, score, matchReason } of results) {
        output += `- **${skill.name}** (${score}分): ${skill.description}\n`;
        output += `  匹配: ${matchReason}`;
        if (skill.category) {
          output += ` | 分类: ${skill.category}`;
        }
        output += '\n';
      }

      return {
        success: true,
        output,
        metadata: { query, resultCount: results.length },
      };
    }

    // 默认显示统计和分类
    const stats = registry.getStats();
    const categories = registry.getCategories();

    let output = `📊 Skills 概览\n\n`;
    output += `总数: ${stats.total} (启用: ${stats.enabled})\n`;
    output += `来源: 内置 ${stats.bySource.builtin || 0}, 用户 ${stats.bySource.user || 0}, 项目 ${stats.bySource.project || 0}\n\n`;

    if (categories.length > 0) {
      output += `可用分类:\n`;
      for (const cat of categories) {
        output += `- ${cat} (${stats.byCategory[cat]} 个)\n`;
      }
    }

    output += `\n使用方法:\n`;
    output += `- skill_search({ list_all: true }) - 列出所有 Skills\n`;
    output += `- skill_search({ query: "关键词" }) - 搜索 Skills\n`;
    output += `- skill_search({ category: "分类名" }) - 按分类筛选`;

    return {
      success: true,
      output,
      metadata: { stats },
    };
  },
};
