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

export function registerListComponents(server: McpServer, env: Env, orgNamespace: string) {
  server.tool(
    toolName("list_components"),
    "列出當前命名空間下所有已發佈的零件，可選擇按 tag 篩選。",
    { tag: z.string().optional().describe("按 tag 名稱篩選（選填）") },
    async ({ tag }) => {
      try {
        if (!env.KBDB) {
          return { content: [{ type: "text", text: "Error: KBDB service binding unavailable" }], isError: true };
        }
        let componentIds: string[] | null = null;
        if (tag) {
          const tagResp = await kbdbFetch(env, `/records/search?template=resource_tag&user_id=${encodeURIComponent(orgNamespace)}&tag_name=${encodeURIComponent(tag)}&resource_type=component`);
          if (!tagResp.ok) {
            return { content: [{ type: "text", text: `Error querying tags: ${await tagResp.text()}` }], isError: true };
          }
          const tagData = await tagResp.json<{ records: Array<{ slots: { resource_id: string } }> }>();
          componentIds = tagData.records.map(r => r.slots.resource_id);
          if (componentIds.length === 0) return { content: [{ type: "text", text: JSON.stringify([], null, 2) }] };
        }
        const resp = await kbdbFetch(env, `/records/search?template=component_metadata&user_id=${encodeURIComponent(orgNamespace)}`);
        if (!resp.ok) {
          return { content: [{ type: "text", text: `Error querying components: ${await resp.text()}` }], isError: true };
        }
        const data = await resp.json<{ records: Array<{ slots: { component_id: string; name: string; published_at: string; org_namespace: string } }> }>();
        let components = data.records.map(r => r.slots);
        if (componentIds !== null) components = components.filter(c => componentIds!.includes(c.component_id));
        return { content: [{ type: "text", text: JSON.stringify(components, null, 2) }] };
      } catch (error) {
        return { content: [{ type: "text", text: `Internal Error: ${error instanceof Error ? error.message : String(error)}` }], isError: true };
      }
    }
  );
}
