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

const MAX_FILE_BYTES = 256 * 1024;

const ReadSkillFileParams = Type.Object({
  name: Type.String({ description: '要读取的 skill 名称' }),
  path: Type.String({ description: '附属文件的相对路径，如 references/playwright-tests.md' }),
});

export function createReadSkillFileTool(skillLoader: SkillLoaderService): AgentToolWithMeta<typeof ReadSkillFileParams, unknown> {
  return {
    name: 'read_skill_file',
    label: '读取 Skill 附属文件',
    description: '读取 skill 目录下的附属文件内容。先用 read_skill 获取文件列表，再用此工具按需读取具体文件。',
    parameters: ReadSkillFileParams,
    async execute(_id, params) {
      const filePath = skillLoader.getSkillFilePath(params.name, params.path);
      if (!filePath) {
        return textResult(`无法读取: skill "${params.name}" 不存在或路径 "${params.path}" 无效`);
      }
      try {
        const stat = await fs.stat(filePath);
        if (stat.size > MAX_FILE_BYTES) {
          return textResult(`文件过大 (${(stat.size / 1024).toFixed(1)}KB)，超过 256KB 限制`);
        }
        const content = await fs.readFile(filePath, 'utf-8');
        return textResult(content);
      } catch {
        return textResult(`读取文件失败: ${params.path}`);
      }
    },
  };
}

import { registerSchema } from '../catalog.js';
registerSchema({
  name: 'read_skill_file',
  toolset: 'skill',
  description: '读取技能的附属文件内容',
  capability: 'text',
  visibility: 'skill',
});
