// ═══════════════════════════════════════════════════════════
// Review Tool: factory_request_review — MCP App modal trigger
// ═══════════════════════════════════════════════════════════

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import * as api from "../api-client.js";
import { buildReviewModalHtml } from "../modals/host.js";

export function registerReviewTools(server: McpServer): void {
  // ───────────────────────────────────────
  // factory_request_review — serves an MCP App UI
  // ───────────────────────────────────────
  server.tool(
    "factory_request_review",
    "Open an interactive review modal for an MCP server pipeline. " +
      "Renders a rich HTML UI for human-in-the-loop feedback with approve/reject buttons, " +
      "score dimensions, and contextual information.",
    {
      pipeline_id: z.string().uuid().describe("UUID of the pipeline to review"),
      modal_type: z
        .enum([
          "traffic-light",
          "tinder-swipe",
          "report-card",
          "thermometer",
          "spotlight",
          "ranking-arena",
          "speed-round",
          "emoji-scale",
          "before-after",
          "priority-poker",
          "mission-briefing",
          "judges-scorecard",
          "quick-pulse",
          "decision-tree",
          "hot-take",
          "side-by-side",
          "checklist-ceremony",
          "confidence-meter",
          "voice-of-customer",
          "retrospective-board",
          "slot-machine",
          "mood-ring",
          "war-room",
          "applause-meter",
          "crystal-ball",
        ])
        .default("traffic-light")
        .describe("Type of review modal to show. Default: traffic-light"),
      display_type: z
        .enum(["inline", "sidecar"])
        .default("sidecar")
        .describe("How to display: inline in chat or sidecar panel. Default: sidecar"),
    },
    async ({ pipeline_id, modal_type, display_type }) => {
      try {
        // Fetch pipeline context for the modal
        const pipeline = await api.getPipeline(pipeline_id);

        let testResults = undefined;
        let stages = undefined;
        try {
          stages = await api.getPipelineStages(pipeline_id);
        } catch { /* optional */ }

        // Build the modal context
        const context = {
          modalType: modal_type,
          modalVersion: "1.0.0",
          sessionId: crypto.randomUUID(),
          pipelineId: pipeline.id,
          pipelineName: pipeline.name,
          itemId: pipeline.id,
          itemName: pipeline.name,
          theme: "dark" as const,
          accentColor: "#4488FF",
        };

        // Generate the HTML for the modal
        const htmlContent = buildReviewModalHtml(context, pipeline, modal_type);

        return {
          content: [
            {
              type: "text" as const,
              text: `🔍 Opening ${modal_type} review for **${pipeline.name}**...`,
            },
            {
              type: "resource" as const,
              resource: {
                uri: `ui://factory-review-${pipeline.id}`,
                mimeType: "text/html" as const,
                text: htmlContent,
              },
            },
          ],
          _meta: {
            goose: {
              toolUI: {
                displayType: display_type,
                name: `Review: ${pipeline.name}`,
                renderer: "mcp-ui",
              },
            },
          },
        };
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        return {
          content: [
            {
              type: "text" as const,
              text: `❌ Error opening review modal: ${msg}`,
            },
          ],
          isError: true,
        };
      }
    },
  );
}
