/**
 * Skill 工具
 *
 * 允许 Agent 调用预定义的 Skill 来执行特定任务。
 * Skill 是可复用的提示模板，不同于 Agent（独立执行单元）。
 */

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

/**
 * 获取 Skill 工具动态描述
 */
function getSkillDescription(): string {
  const registry = getSkillRegistry();
  const skills = registry.getEnabled();

  if (skills.length === 0) {
    return '执行 Skill（当前没有可用的 Skill）';
  }

  // 按分类分组
  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 description = '执行预定义的 Skill 来完成特定任务。\n\n可用的 Skills:\n';

  for (const [category, categorySkills] of byCategory) {
    description += `\n[${category}]\n`;
    for (const skill of categorySkills) {
      description += `- ${skill.name}: ${skill.description}\n`;
    }
  }

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

  description += `
使用示例:
- skill({ skill_name: "code-review", params: { code: "..." } })
- skill({ skill_name: "generate-tests", params: { code: "...", framework: "vitest" } })`;

  return description;
}

/**
 * Skill 工具
 */
export const skillTool: ToolWithMetadata = {
  name: 'skill',
  description: getSkillDescription(),
  parameters: {
    skill_name: {
      type: 'string',
      description: 'Skill 名称',
      required: true,
    },
    params: {
      type: 'object',
      description: 'Skill 参数（根据具体 Skill 定义）',
      required: false,
    },
  },
  metadata: {
    name: 'skill',
    category: 'agent',
    description: '执行预定义的 Skill',
    keywords: ['skill', 'template', 'prompt', '技能', '模板', '提示'],
    deferLoading: false,
  },
  async execute(params) {
    const { skill_name, params: skillParams = {} } = params as {
      skill_name: string;
      params?: Record<string, unknown>;
    };

    const registry = getSkillRegistry();

    // 检查 Skill 是否存在
    const skill = registry.get(skill_name);
    if (!skill) {
      // 尝试搜索相似的 Skill
      const suggestions = registry.search(skill_name, 3);
      let errorMsg = `Skill 不存在: ${skill_name}`;

      if (suggestions.length > 0) {
        errorMsg += '\n\n你可能想要的 Skill:\n';
        for (const { skill: s, matchReason } of suggestions) {
          errorMsg += `- ${s.name}: ${s.description} (${matchReason})\n`;
        }
      }

      return {
        success: false,
        output: '',
        error: errorMsg,
      };
    }

    // 执行 Skill（渲染模板）
    const result = registry.execute(skill_name, skillParams, {
      workdir: process.cwd(),
    });

    if (!result.success) {
      return {
        success: false,
        output: '',
        error: result.error || 'Skill 执行失败',
      };
    }

    // 返回渲染后的提示
    return {
      success: true,
      output: result.prompt || '',
      metadata: {
        skill: skill_name,
        category: skill.category,
        source: skill.source,
      },
    };
  },
};

/**
 * 更新 Skill 工具描述
 */
export function updateSkillDescription(): void {
  (skillTool as { description: string }).description = getSkillDescription();
}
