// ═══════════════════════════════════════════════════════════
// Prompt: whats_needs_attention
// Prioritized summary of everything pending
// ═══════════════════════════════════════════════════════════

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

export function registerNeedsAttentionPrompt(server: McpServer): void {
  server.prompt(
    "whats_needs_attention",
    "Summary of everything needing human attention right now, prioritized by urgency.",
    {
      scope: z
        .string()
        .optional()
        .describe("Filter scope: 'all' | 'my-tasks' | 'critical-only'. Default: all"),
    },
    async ({ scope }) => {
      const effectiveScope = scope || "all";

      let pendingTasks = "No pending task data.";
      let blockerInfo = "No blocker data.";
      let pipelineInfo = "No pipeline data.";
      let statsInfo = "No stats available.";

      try {
        // Fetch pending tasks
        const taskParams: { status: "pending"; priority?: "critical"; assigneeId?: string; limit: number; sort: string } = {
          status: "pending",
          limit: 20,
          sort: "-priority,-sla_deadline",
        };
        if (effectiveScope === "critical-only") taskParams.priority = "critical";
        if (effectiveScope === "my-tasks") taskParams.assigneeId = "me";

        const tasks = await api.listTasks(taskParams);
        if (tasks.length > 0) {
          const slaBreached = tasks.filter((t) => t.slaBreached);
          const critical = tasks.filter((t) => t.priority === "critical");
          const high = tasks.filter((t) => t.priority === "high");

          pendingTasks = `${tasks.length} pending task(s):`;
          if (slaBreached.length > 0) {
            pendingTasks += `\n\n🚨 SLA BREACHED (${slaBreached.length}):`;
            for (const t of slaBreached) {
              pendingTasks += `\n  - ${t.title} (${t.id})`;
              pendingTasks += `\n    Pipeline: ${t.pipelineId} | Stage: ${t.stageName}`;
            }
          }
          if (critical.length > 0) {
            pendingTasks += `\n\n🔴 CRITICAL (${critical.length}):`;
            for (const t of critical.filter((t) => !t.slaBreached)) {
              pendingTasks += `\n  - ${t.title} (${t.id})`;
            }
          }
          if (high.length > 0) {
            pendingTasks += `\n\n🟡 HIGH (${high.length}):`;
            for (const t of high) {
              pendingTasks += `\n  - ${t.title} (${t.id})`;
            }
          }
          const remaining = tasks.filter((t) => t.priority !== "critical" && t.priority !== "high" && !t.slaBreached);
          if (remaining.length > 0) {
            pendingTasks += `\n\n🔵 OTHER (${remaining.length}):`;
            for (const t of remaining) {
              pendingTasks += `\n  - ${t.title} [${t.priority}]`;
            }
          }
        } else {
          pendingTasks = "✅ No pending tasks — you're all clear!";
        }
      } catch (err) {
        pendingTasks = `Error fetching tasks: ${err instanceof Error ? err.message : String(err)}`;
      }

      try {
        const blockers = await api.getBlockers();
        if (blockers.length > 0) {
          blockerInfo = `${blockers.length} blocker(s):`;
          for (const b of blockers) {
            blockerInfo += `\n  ⛔ ${b.title} — ${b.blockReason}`;
            blockerInfo += `\n    Pipeline: ${b.pipelineName} | Blocked: ${b.hoursBlocked.toFixed(1)}h`;
            if (b.suggestedAction) blockerInfo += `\n    💡 ${b.suggestedAction}`;
          }
        } else {
          blockerInfo = "✅ Nothing blocked!";
        }
      } catch (err) {
        blockerInfo = `Error fetching blockers: ${err instanceof Error ? err.message : String(err)}`;
      }

      try {
        const pipelines = await api.listPipelines({ status: "active", limit: 20 });
        if (pipelines.length > 0) {
          pipelineInfo = `${pipelines.length} active pipeline(s):`;
          for (const p of pipelines) {
            pipelineInfo += `\n  ${p.name} — ${p.currentStage} [${p.priority}]`;
          }
        } else {
          pipelineInfo = "No active pipelines.";
        }
      } catch (err) {
        pipelineInfo = `Error: ${err instanceof Error ? err.message : String(err)}`;
      }

      try {
        const stats = await api.getTaskStats();
        statsInfo = [
          `Pending: ${stats.pending}`,
          `In Progress: ${stats.inProgress}`,
          `Blocked: ${stats.blocked}`,
          `Avg Wait: ${stats.avgWaitTimeMinutes} min`,
          `SLA Breaches: ${stats.slaBreaches}`,
        ].join(" | ");
      } catch { /* ok */ }

      return {
        messages: [
          {
            role: "user" as const,
            content: {
              type: "text" as const,
              text: [
                `# What Needs Attention (scope: ${effectiveScope})`,
                "",
                "Here is a prioritized summary of everything requiring human attention.",
                "Review and act on the most urgent items first.",
                "",
                `## 📊 Quick Stats`,
                statsInfo,
                "",
                "## 📥 Pending Tasks",
                pendingTasks,
                "",
                "## ⛔ Blockers",
                blockerInfo,
                "",
                "## ▶️ Active Pipelines",
                pipelineInfo,
                "",
                "## 💡 Suggested Actions",
                "Based on the above, here's what I recommend tackling first:",
                "1. Address any SLA breaches immediately",
                "2. Review critical-priority tasks",
                "3. Unblock any stuck pipelines",
                "4. Process remaining pending approvals",
                "",
                "What would you like to do first?",
              ].join("\n"),
            },
          },
        ],
      };
    },
  );
}
