// ═══════════════════════════════════════════════════════════
// Prompt: review_server
// Pull all context needed to review an MCP server
// ═══════════════════════════════════════════════════════════

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

export function registerReviewServerPrompt(server: McpServer): void {
  server.prompt(
    "review_server",
    "Pull all context needed to review an MCP server: code quality, " +
      "test results, docs, deployment readiness. Returns a structured review prompt.",
    { server_name: z.string().describe("Name of the MCP server to review") },
    async ({ server_name }) => {
      let pipelineInfo = "Pipeline data unavailable.";
      let testInfo = "Test results unavailable.";
      let taskInfo = "No pending tasks.";
      let assetInfo = "No assets found.";

      try {
        const pipelines = await api.listPipelines({ search: server_name, limit: 1 });
        if (pipelines.length > 0) {
          const p = pipelines[0];
          pipelineInfo = [
            `Pipeline: ${p.name} (${p.id})`,
            `Platform: ${p.platform}`,
            `Stage: ${p.currentStage}`,
            `Status: ${p.status}`,
            `Priority: ${p.priority}`,
            `Template: ${p.template}`,
            `Created: ${p.createdAt}`,
            `Updated: ${p.updatedAt}`,
          ].join("\n");

          try {
            const stages = await api.getPipelineStages(p.id);
            pipelineInfo += "\n\nStage History:";
            for (const s of stages) {
              const status =
                s.status === "completed" ? "✅" : s.status === "active" ? "🔄" : s.status === "failed" ? "❌" : "⏳";
              pipelineInfo += `\n  ${status} ${s.stageName} (${s.status})`;
              if (s.requiresApproval) pipelineInfo += " ★ GATE";
            }
          } catch { /* ok */ }

          try {
            const tasks = await api.listTasks({ pipelineId: p.id, limit: 20 });
            if (tasks.length > 0) {
              taskInfo = `${tasks.length} task(s):`;
              for (const t of tasks) {
                taskInfo += `\n  [${t.priority}] ${t.title} — ${t.status}`;
                if (t.context?.testResults) {
                  const tr = t.context.testResults;
                  testInfo = [
                    `Tests: ${tr.passed}/${tr.total} passed`,
                    `Coverage: ${tr.coveragePercent}%`,
                    `Failed: ${tr.failed}`,
                    `Skipped: ${tr.skipped}`,
                  ].join("\n");

                  if (tr.failureDetails?.length) {
                    testInfo += "\n\nFailures:";
                    for (const f of tr.failureDetails) {
                      testInfo += `\n  ❌ ${f.testName}: ${f.error}`;
                    }
                  }
                }
              }
            }
          } catch { /* ok */ }

          try {
            const assets = await api.listAssets(p.id);
            if (assets.length > 0) {
              assetInfo = `${assets.length} asset(s):`;
              for (const a of assets) {
                assetInfo += `\n  [${a.type}] ${a.name} (v${a.version})`;
              }
            }
          } catch { /* ok */ }
        } else {
          pipelineInfo = `No pipeline found matching "${server_name}".`;
        }
      } catch (err) {
        pipelineInfo = `Error fetching pipeline: ${err instanceof Error ? err.message : String(err)}`;
      }

      return {
        messages: [
          {
            role: "user" as const,
            content: {
              type: "text" as const,
              text: [
                `# MCP Server Review: ${server_name}`,
                "",
                "You are reviewing an MCP server for quality, completeness, and deployment readiness.",
                "Use the context below to conduct a thorough review.",
                "",
                "## Pipeline Status",
                pipelineInfo,
                "",
                "## Test Results",
                testInfo,
                "",
                "## Pending Tasks",
                taskInfo,
                "",
                "## Assets",
                assetInfo,
                "",
                "## Review Checklist",
                "Please evaluate against these criteria:",
                "1. ☐ Code quality — Clean, maintainable, follows conventions",
                "2. ☐ Test coverage — Adequate coverage with meaningful tests",
                "3. ☐ Error handling — All API calls properly wrapped, graceful failures",
                "4. ☐ Documentation — README complete, TOOLS.md documents all tools",
                "5. ☐ Security — No hardcoded secrets, proper input validation",
                "6. ☐ Performance — No obvious bottlenecks, efficient API calls",
                "7. ☐ Architecture — Clean separation of concerns, extensible design",
                "8. ☐ Deployment readiness — Environment vars documented, configs complete",
                "",
                "## Your Review",
                "For each criterion, indicate PASS, NEEDS WORK, or FAIL with specific feedback.",
                "End with an overall recommendation: APPROVE, NEEDS WORK, or REJECT.",
              ].join("\n"),
            },
          },
        ],
      };
    },
  );
}
