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

/**
 * arcrun_publish_component — 提交 TinyGo WASM 零件至 Component Registry
 *
 * AI 工作流：
 * 1. 先呼叫 arcrun_get_component_guide 取得開發指引
 * 2. 依指引用 TinyGo 撰寫零件（stdin/stdout JSON I/O）
 * 3. 編譯為 .wasm，base64 編碼後提交
 * 4. Registry 自動執行沙盒驗收（體積、syscall 掃描、Gherkin 測試）
 */
export function registerPublishComponent(server: McpServer, env: Env, orgNamespace: string) {
  server.tool(
    toolName("publish_component"),
    "提交 TinyGo WASM 零件至 Component Registry。需提供 component.contract.yaml 內容與編譯後的 .wasm base64。提交前請先呼叫 arcrun_get_component_guide 取得開發規範。",
    {
      contract: z.object({
        canonical_id: z.string().describe("零件功能名稱（小寫底線，如 validate_json）"),
        display_name: z.string().describe("顯示名稱（可自由命名）"),
        category: z.enum(["logic", "api", "ui", "style", "anim"]).describe("零件分類"),
        version: z.string().describe("版本（格式 vN，如 v1）"),
        wasi_target: z.literal("preview1"),
        stability: z.enum(["floating", "stable", "pinned"]).default("floating"),
        runtime_compat: z.array(z.string()).describe("相容 runtime，如 [\"cf-workers\",\"wazero\"]"),
        constraints: z.object({
          max_size_kb: z.number().default(2048),
          max_cold_start_ms: z.number().default(50),
          no_network_syscall: z.boolean().default(true),
          io_model: z.literal("stdin_stdout_json"),
        }),
        input_schema: z.record(z.unknown()).describe("JSON Schema"),
        output_schema: z.record(z.unknown()).describe("JSON Schema"),
        gherkin_tests: z.array(z.object({
          scenario: z.string(),
          given: z.string().describe("JSON 字串"),
          then_contains: z.string().describe("預期輸出包含的字串"),
        })).min(2).describe("至少一個 happy path 和一個 error path"),
        description: z.string().optional(),
        tags: z.array(z.string()).optional(),
      }).describe("component.contract.yaml 內容"),
      wasm_base64: z.string().describe("編譯後的 .wasm 檔案 base64 編碼"),
    },
    async ({ contract, wasm_base64 }) => {
      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", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ contract, wasm_base64 }),
        });

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

        const result = await response.json() as Record<string, unknown>;
        return {
          content: [{
            type: "text",
            text: `零件 ${contract.canonical_id} v${contract.version} 提交成功：\n${JSON.stringify(result, null, 2)}`,
          }],
        };
      } catch (error) {
        return {
          content: [{ type: "text", text: `Internal Error: ${error instanceof Error ? error.message : String(error)}` }],
          isError: true,
        };
      }
    }
  );
}
