import { Type } from '@sinclair/typebox';
import * as fs from 'fs/promises';
import * as path from 'path';
import { AgentToolWithMeta, textResult } from '../common.js';
import { SkillLoaderService } from '../../service/skill_loader.js';

const SkillManageParams = Type.Object({
  action: Type.Union([
    Type.Literal('create'),
    Type.Literal('edit'),
    Type.Literal('delete'),
  ], { description: '操作类型' }),
  name: Type.String({ description: 'skill 名称' }),
  content: Type.Optional(Type.String({ description: 'SKILL.md 完整内容（create/edit 时必填）' })),
});

export function createSkillManageTool(skillLoader: SkillLoaderService): AgentToolWithMeta<typeof SkillManageParams, unknown> {
  const skillsDir = skillLoader.getSkillsDir();

  return {
    name: 'skill_manage',
    label: '管理 Skill',
    description: '创建、编辑或删除 skill。创建/编辑时需提供完整的 SKILL.md 内容（含 YAML frontmatter）。',
    parameters: SkillManageParams,
    async execute(_id, params) {
      // 路径安全检查
      const targetDir = path.join(skillsDir, params.name);
      const realSkillsDir = await fs.realpath(skillsDir).catch(() => skillsDir);
      const realTarget = path.resolve(realSkillsDir, params.name);
      if (!realTarget.startsWith(realSkillsDir)) {
        return textResult('错误: 路径安全检查失败');
      }

      if (params.action === 'create' || params.action === 'edit') {
        if (!params.content) {
          return textResult('错误: create/edit 操作需要提供 content');
        }
        const parsed = skillLoader.parseSkillMd(params.content);
        if (!parsed) {
          return textResult('错误: content 不是合法的 SKILL.md 格式（需要 YAML frontmatter 含 name 字段）');
        }
        await fs.mkdir(targetDir, { recursive: true });
        await fs.writeFile(path.join(targetDir, 'SKILL.md'), params.content, 'utf-8');
        await skillLoader.scanSkills();
        return textResult(`Skill "${params.name}" 已${params.action === 'create' ? '创建' : '更新'}`);
      }

      if (params.action === 'delete') {
        await fs.rm(targetDir, { recursive: true, force: true });
        await skillLoader.scanSkills();
        return textResult(`Skill "${params.name}" 已删除`);
      }

      return textResult('错误: 未知操作');
    },
  };
}

import { registerSchema } from '../catalog.js';
registerSchema({
  name: 'skill_manage',
  toolset: 'skill',
  description: '创建、更新或删除技能',
  capability: 'text',
  visibility: 'skill',
});
