"use strict";
/*
 * 光湖 · 工具注册中心
 * 所有真实可调用的工具在此注册
 * Anti-Hallucination 系统：工具不存在时返回无工具回执
 */

const https = require("https");
const http = require("http");

// ─── 工具定义 ─────────────────────────────────────────────────
const TOOLS = {};

// Notion 查询（通过 repo-mcp MCP 工具）
TOOLS.notion = {
  name: "Notion 知识库",
  description: "查询 Notion 中的知识库页面内容",
  execute: async (query) => {
    try {
      const body = JSON.stringify({ action: "search", query: query || "" });
      const res = await fetch("http://127.0.0.1:3902/api/tools/notion/search", {
        method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer " + (process.env.REPO_MCP_SECRET_ZZ || "") },
        body, signal: AbortSignal.timeout(10000),
      });
      if (!res.ok) return "[Notion] 查询失败: HTTP " + res.status;
      const data = await res.json();
      return "[Notion 查询结果]\n" + JSON.stringify(data, null, 2).slice(0, 3000);
    } catch (e) {
      return "[Notion] 查询出错: " + e.message;
    }
  }
};

// 仓库查询（Forgejo API）
TOOLS.repo = {
  name: "代码仓库",
  description: "查询代码仓库信息",
  execute: async (query) => {
    try {
      const token = process.env.GITEA_TOKEN || "2d924a6e19b44d14bf367f5dd1ce238510128183";
      // 只返回基本的仓库信息
      const res = await fetch("https://guanghulab.com/code/api/v1/repos/bingshuo/guanghulab", {
        headers: { "Authorization": "token " + token },
        signal: AbortSignal.timeout(8000),
      });
      if (!res.ok) return "[仓库] 查询失败: HTTP " + res.status;
      const data = await res.json();
      return "[代码仓库信息]\n仓库: " + data.full_name + "\n描述: " + (data.description || "无") + "\n分支: " + data.default_branch + "\n更新: " + data.updated_at;
    } catch (e) {
      return "[仓库] 查询出错: " + e.message;
    }
  }
};

// 系统健康
TOOLS.health = {
  name: "系统健康",
  description: "查询服务器和系统运行状态",
  execute: async () => {
    try {
      const res = await fetch("http://127.0.0.1:3000/api/health", { signal: AbortSignal.timeout(5000) });
      if (!res.ok) return "[系统健康] 查询失败";
      const data = await res.json();
      return "[系统健康状态]\n服务器: " + (data.server || "未知") + "\n推理端: " + (data.inference?.ready ? "就绪" : "未配置") + "\n时间: " + (data.ts || "");
    } catch (e) {
      return "[系统健康] 查询出错: " + e.message;
    }
  }
};

// 训练状态
TOOLS.training = {
  name: "训练状态",
  description: "查询模型训练进度和状态",
  execute: async () => {
    try {
      const fs = require("fs");
      const p = "/data/guanghulab/repo/homepage/training-status.json";
      if (!fs.existsSync(p)) return "[训练状态] 数据文件不存在";
      const raw = fs.readFileSync(p, "utf-8");
      const data = JSON.parse(raw);
      const steps = data.pipeline?.steps || [];
      const done = steps.filter(s => s.status === "completed").length;
      const total = steps.length;
      return "[训练状态]\n流水线: " + done + "/" + total + " 完成\n" +
        steps.map(s => (s.label || "⬜") + " " + s.name).join("\n");
    } catch (e) {
      return "[训练状态] 读取失败: " + e.message;
    }
  }
};

// 工具列表
TOOLS.list = {
  name: "工具列表",
  description: "列出所有可用工具",
  execute: async () => {
    const names = Object.keys(TOOLS).filter(k => k !== "list");
    return "[可用工具列表]\n" + names.map(n => "  " + n + " - " + TOOLS[n].description).join("\n");
  }
};

module.exports = { TOOLS };
