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

/**
 * arcrun_get_component — 取得零件完整合約
 * 呼叫 Component Registry GET /components/:id
 */
export function registerGetComponent(server: McpServer, env: Env, orgNamespace: string) {
  server.tool(
    toolName("get_component"),
    "取得指定零件的完整合約，包含 canonical_id、display_name、category、version、stability、input_schema、output_schema、gherkin_tests、評分統計等。",
    {
      canonical_id: z.string().describe("零件 canonical_id（如 validate_json）"),
    },
    async ({ canonical_id }) => {
      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/${encodeURIComponent(canonical_id)}`,
          { method: "GET" },
        );

        if (response.status === 404) {
          return {
            content: [{ type: "text", text: `零件 '${canonical_id}' 不存在。可用 arcrun_search_components 搜尋相似零件。` }],
            isError: true,
          };
        }

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

        const result = await response.json() as { data?: unknown };
        return {
          content: [{
            type: "text",
            text: JSON.stringify(result.data ?? result, null, 2),
          }],
        };
      } catch (error) {
        return {
          content: [{ type: "text", text: `Internal Error: ${error instanceof Error ? error.message : String(error)}` }],
          isError: true,
        };
      }
    }
  );
}
