// ═══════════════════════════════════════════════════════════
// Prompt: pipeline_retrospective
// Post-completion analysis and lessons learned
// ═══════════════════════════════════════════════════════════

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

export function registerRetrospectivePrompt(server: McpServer): void {
  server.prompt(
    "pipeline_retrospective",
    "Generate a retrospective analysis of a completed pipeline.",
    {
      pipeline_id: z.string().describe("UUID of the completed pipeline"),
    },
    async ({ pipeline_id }) => {
      let pipelineInfo = "Pipeline data unavailable.";
      let stageTimeline = "Stage timeline unavailable.";
      let taskHistory = "Task history unavailable.";
      let auditTrail = "Audit trail unavailable.";

      try {
        const pipeline = await api.getPipeline(pipeline_id);

        const durationMs = pipeline.completedAt
          ? new Date(pipeline.completedAt).getTime() - new Date(pipeline.startedAt).getTime()
          : new Date().getTime() - new Date(pipeline.startedAt).getTime();
        const durationHours = (durationMs / (1000 * 60 * 60)).toFixed(1);

        pipelineInfo = [
          `Pipeline: ${pipeline.name}`,
          `Platform: ${pipeline.platform}`,
          `Status: ${pipeline.status}`,
          `Priority: ${pipeline.priority}`,
          `Template: ${pipeline.template}`,
          `Duration: ${durationHours} hours`,
          `Started: ${pipeline.startedAt}`,
          pipeline.completedAt ? `Completed: ${pipeline.completedAt}` : "Still in progress",
        ].join("\n");

        try {
          const stages = await api.getPipelineStages(pipeline_id);
          stageTimeline = "Stage-by-stage breakdown:";

          let totalGateTime = 0;
          let totalBuildTime = 0;

          for (const s of stages) {
            const emoji =
              s.status === "completed"
                ? "✅"
                : s.status === "failed"
                  ? "❌"
                  : s.status === "skipped"
                    ? "⏭️"
                    : "⏳";

            const duration = s.durationSeconds
              ? `${(s.durationSeconds / 60).toFixed(0)} min`
              : "—";

            stageTimeline += `\n  ${emoji} ${s.stageName} — ${s.status} (${duration})`;
            if (s.requiresApproval) stageTimeline += " ★ GATE";

            if (s.durationSeconds) {
              if (s.requiresApproval) {
                totalGateTime += s.durationSeconds;
              } else {
                totalBuildTime += s.durationSeconds;
              }
            }
          }

          stageTimeline += `\n\nTime in gates (waiting for human): ${(totalGateTime / 60).toFixed(0)} min`;
          stageTimeline += `\nTime in build stages: ${(totalBuildTime / 60).toFixed(0)} min`;

          if (totalGateTime + totalBuildTime > 0) {
            const gatePercent = Math.round(
              (totalGateTime / (totalGateTime + totalBuildTime)) * 100,
            );
            stageTimeline += `\nHuman bottleneck: ${gatePercent}% of total time`;
          }
        } catch { /* ok */ }

        try {
          const tasks = await api.listTasks({ pipelineId: pipeline_id, limit: 50 });
          if (tasks.length > 0) {
            const approved = tasks.filter((t) => t.decision === "approved").length;
            const rejected = tasks.filter((t) => t.decision === "rejected").length;
            const slaBreached = tasks.filter((t) => t.slaBreached).length;

            taskHistory = [
              `Total tasks: ${tasks.length}`,
              `Approved: ${approved}`,
              `Rejected: ${rejected}`,
              `SLA Breaches: ${slaBreached}`,
            ].join("\n");

            if (rejected > 0) {
              taskHistory += "\n\nRejection reasons:";
              for (const t of tasks.filter((t) => t.decision === "rejected")) {
                taskHistory += `\n  - ${t.title}: ${t.decisionNotes || "No reason given"}`;
              }
            }
          }
        } catch { /* ok */ }

        try {
          const audit = await api.getAuditLog({
            entityType: "pipeline",
            entityId: pipeline_id,
            limit: 30,
          });
          if (audit.length > 0) {
            auditTrail = "Key events:";
            for (const e of audit.slice(0, 20)) {
              auditTrail += `\n  [${new Date(e.createdAt).toLocaleString()}] ${e.action}`;
              if (e.actorName) auditTrail += ` by ${e.actorName}`;
            }
          }
        } catch { /* ok */ }
      } catch (err) {
        pipelineInfo = `Error: ${err instanceof Error ? err.message : String(err)}`;
      }

      return {
        messages: [
          {
            role: "user" as const,
            content: {
              type: "text" as const,
              text: [
                `# Pipeline Retrospective`,
                "",
                "Analyze this pipeline's journey from start to finish.",
                "Identify bottlenecks, what went well, and what to improve.",
                "",
                "## Pipeline Summary",
                pipelineInfo,
                "",
                "## Stage Timeline",
                stageTimeline,
                "",
                "## Task History",
                taskHistory,
                "",
                "## Audit Trail",
                auditTrail,
                "",
                "## Analysis Questions",
                "",
                "### 1. Timeline Analysis",
                "- How long did each stage take?",
                "- Where were the biggest delays?",
                "- Was the human the bottleneck? By how much?",
                "",
                "### 2. Quality Analysis",
                "- How many iterations/rejections occurred?",
                "- What were the common rejection reasons?",
                "- Were there any SLA breaches? Why?",
                "",
                "### 3. What Went Well",
                "- Which stages flowed smoothly?",
                "- Any auto-advanced stages that worked perfectly?",
                "",
                "### 4. What to Improve",
                "- Which gates could be automated or loosened?",
                "- What patterns should agents learn to avoid rejections?",
                "- Should SLA thresholds be adjusted?",
                "",
                "### 5. Recommendations",
                "- Specific improvements for the next pipeline",
                "- New rules or standards to add to the factory",
                "- Template changes to consider",
                "",
                "Please provide a structured retrospective covering all 5 areas.",
              ].join("\n"),
            },
          },
        ],
      };
    },
  );
}
