// ═══════════════════════════════════════════════════════════
// Prompt: deploy_checklist
// Pre-deployment verification checklist
// ═══════════════════════════════════════════════════════════

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

export function registerDeployChecklistPrompt(server: McpServer): void {
  server.prompt(
    "deploy_checklist",
    "Pre-deployment review checklist for an MCP server.",
    {
      pipeline_id: z.string().describe("UUID of the pipeline being deployed"),
      target: z.enum(["staging", "production"]).describe("'staging' or 'production'"),
    },
    async ({ pipeline_id, target }) => {
      let pipelineInfo = "Pipeline data unavailable.";
      let testInfo = "Test data unavailable.";
      let stageInfo = "Stage data unavailable.";

      try {
        const pipeline = await api.getPipeline(pipeline_id);
        pipelineInfo = [
          `Pipeline: ${pipeline.name}`,
          `Platform: ${pipeline.platform}`,
          `Current Stage: ${pipeline.currentStage}`,
          `Priority: ${pipeline.priority}`,
          `Template: ${pipeline.template}`,
        ].join("\n");

        try {
          const stages = await api.getPipelineStages(pipeline_id);
          stageInfo = "Stage Status:";
          for (const s of stages) {
            const emoji =
              s.status === "completed"
                ? "✅"
                : s.status === "active"
                  ? "🔄"
                  : s.status === "failed"
                    ? "❌"
                    : "⏳";
            stageInfo += `\n  ${emoji} ${s.stageName} — ${s.status}`;
          }
        } catch { /* ok */ }

        try {
          const tasks = await api.listTasks({ pipelineId: pipeline_id });
          const testTask = tasks.find((t) => t.context?.testResults);
          if (testTask?.context?.testResults) {
            const tr = testTask.context.testResults;
            testInfo = [
              `Total: ${tr.total}`,
              `Passed: ${tr.passed}`,
              `Failed: ${tr.failed}`,
              `Skipped: ${tr.skipped}`,
              `Coverage: ${tr.coveragePercent}%`,
            ].join("\n");
          }
        } catch { /* ok */ }
      } catch (err) {
        pipelineInfo = `Error: ${err instanceof Error ? err.message : String(err)}`;
      }

      const isProduction = target === "production";

      return {
        messages: [
          {
            role: "user" as const,
            content: {
              type: "text" as const,
              text: [
                `# Deploy Checklist: ${target.toUpperCase()}`,
                "",
                `Verifying readiness for **${target}** deployment.`,
                isProduction
                  ? "⚠️ PRODUCTION DEPLOYMENT — Extra rigor required."
                  : "Staging deployment — verify before promoting to production.",
                "",
                "## Pipeline Info",
                pipelineInfo,
                "",
                "## Stage Progress",
                stageInfo,
                "",
                "## Test Results",
                testInfo,
                "",
                "## Pre-Deploy Checklist",
                "",
                "### Code Quality",
                "☐ All tests passing (unit, integration, e2e)",
                "☐ Code review approved by at least 1 reviewer",
                "☐ No critical linting errors",
                "☐ No TODO/FIXME items in critical paths",
                "",
                "### Documentation",
                "☐ README.md complete and accurate",
                "☐ TOOLS.md documents all MCP tools",
                "☐ API changes documented",
                "☐ CHANGELOG updated",
                "",
                "### Configuration",
                "☐ Environment variables documented in .env.example",
                "☐ No hardcoded secrets in codebase",
                "☐ All config values use environment variables",
                `☐ ${target} environment variables set correctly`,
                "",
                "### Security",
                "☐ Input validation on all tool parameters (Zod)",
                "☐ No sensitive data in logs",
                "☐ API keys use scoped permissions",
                "☐ Dependencies scanned for vulnerabilities",
                "",
                ...(isProduction
                  ? [
                      "### Production-Specific",
                      "☐ Staging deploy tested and verified",
                      "☐ Performance benchmarks acceptable",
                      "☐ Rollback plan documented",
                      "☐ Monitoring/alerting configured",
                      "☐ Rate limiting configured",
                      "☐ Error tracking enabled (Sentry/similar)",
                      "",
                    ]
                  : []),
                "### Deployment",
                "☐ Build succeeds with no warnings",
                "☐ Docker image builds and runs locally",
                "☐ Health check endpoint responds",
                `☐ ${target} DNS/routing configured`,
                "",
                "## Recommendation",
                "Based on the above checklist, provide a GO / NO-GO recommendation.",
                "If NO-GO, list the specific items that must be addressed first.",
              ].join("\n"),
            },
          },
        ],
      };
    },
  );
}
