import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { toolName } from "../brand.js";
import { Env } from "../types.js";

/**
 * arcrun_get_component_guide — 取得零件開發指引
 * 呼叫 Component Registry GET /components/guide
 * AI 在開發新零件前應先讀取此指引
 */
export function registerGetComponentGuide(server: McpServer, env: Env, orgNamespace: string) {
  server.tool(
    toolName("get_component_guide"),
    "取得 arcrun 零件開發指引（Markdown 格式）。包含 TinyGo 白名單 import、禁止行為、component.contract.yaml 完整範例、本地測試指令。開發新零件前必須先讀取此指引。",
    {},
    async () => {
      try {
        if (!env.COMPONENT_REGISTRY) {
          return {
            content: [{ type: "text", text: "Error: COMPONENT_REGISTRY service binding is not configured." }],
            isError: true,
          };
        }

        const response = await env.COMPONENT_REGISTRY.fetch(
          "http://component-registry/components/guide",
          { method: "GET" },
        );

        if (!response.ok) {
          return {
            content: [{ type: "text", text: `Error fetching guide: ${await response.text()}` }],
            isError: true,
          };
        }

        const guide = await response.text();
        return {
          content: [{ type: "text", text: guide }],
        };
      } catch (error) {
        return {
          content: [{ type: "text", text: `Internal Error: ${error instanceof Error ? error.message : String(error)}` }],
          isError: true,
        };
      }
    }
  );
}
