import {
  EmbedBuilder,
  type MessageCreateOptions,
} from 'discord.js';
import { PRIORITY_CONFIG, STAGE_DISPLAY, COLORS, type Priority } from '../config.js';
import type { Pipeline, PipelineStageRecord } from '../api-client.js';

/**
 * Build a pipeline status embed showing current stage, progress bar, and key info.
 */
export function buildPipelineStatusEmbed(
  pipeline: Pipeline,
  stages?: PipelineStageRecord[],
): MessageCreateOptions {
  const priority = pipeline.priority as Priority;
  const pConfig = PRIORITY_CONFIG[priority];
  const stageDisplay = STAGE_DISPLAY[pipeline.currentStage] ?? pipeline.currentStage;

  // Build progress bar from stages
  const progressBar = stages ? buildProgressBar(stages) : '';

  // Duration since started
  const duration = formatDuration(Date.now() - new Date(pipeline.startedAt).getTime());

  // SLA info
  let slaStr = 'No SLA';
  if (pipeline.slaDeadline) {
    const remaining = new Date(pipeline.slaDeadline).getTime() - Date.now();
    slaStr = remaining > 0
      ? `${formatDuration(remaining)} remaining`
      : '🚨 **BREACHED**';
  }

  const statusEmoji: Record<string, string> = {
    active: '🟢',
    paused: '⏸️',
    completed: '✅',
    failed: '❌',
    archived: '📦',
  };

  const embed = new EmbedBuilder()
    .setTitle(`${statusEmoji[pipeline.status] ?? '❓'} Pipeline: ${pipeline.name}`)
    .setDescription(
      progressBar
        ? `**Progress:**\n${progressBar}`
        : `Platform: ${pipeline.platform}`,
    )
    .addFields(
      { name: 'Status', value: capitalize(pipeline.status), inline: true },
      { name: 'Current Stage', value: stageDisplay, inline: true },
      { name: 'Priority', value: `${pConfig.emoji} ${pConfig.label}`, inline: true },
      { name: 'Platform', value: pipeline.platform ?? 'N/A', inline: true },
      { name: 'Template', value: pipeline.template, inline: true },
      { name: 'Running For', value: duration, inline: true },
      { name: 'SLA', value: slaStr, inline: true },
    )
    .setColor(getStatusColor(pipeline.status))
    .setFooter({ text: `Pipeline ID: ${pipeline.id}` })
    .setTimestamp();

  return { embeds: [embed] };
}

/**
 * Build a compact pipeline list embed for /factory pipelines.
 */
export function buildPipelineListEmbed(pipelines: Pipeline[]): MessageCreateOptions {
  if (pipelines.length === 0) {
    const embed = new EmbedBuilder()
      .setTitle('📊 Active Pipelines')
      .setDescription('No active pipelines found.')
      .setColor(COLORS.neutral)
      .setTimestamp();
    return { embeds: [embed] };
  }

  const lines = pipelines.map((p) => {
    const priority = p.priority as Priority;
    const pConfig = PRIORITY_CONFIG[priority];
    const stageDisplay = STAGE_DISPLAY[p.currentStage] ?? p.currentStage;
    const statusEmoji = p.status === 'active' ? '🟢' : p.status === 'paused' ? '⏸️' : '❓';
    return `${statusEmoji} **${p.name}** — ${stageDisplay} ${pConfig.emoji}`;
  });

  const embed = new EmbedBuilder()
    .setTitle(`📊 Active Pipelines (${pipelines.length})`)
    .setDescription(lines.join('\n'))
    .setColor(COLORS.info)
    .setTimestamp();

  return { embeds: [embed] };
}

/**
 * Build a stage-changed notification embed for #factory-feed.
 */
export function buildStageChangedEmbed(data: {
  pipelineId: string;
  pipelineName: string;
  fromStage: string;
  toStage: string;
  triggeredBy: string;
}): MessageCreateOptions {
  const fromDisplay = STAGE_DISPLAY[data.fromStage] ?? data.fromStage;
  const toDisplay = STAGE_DISPLAY[data.toStage] ?? data.toStage;

  const embed = new EmbedBuilder()
    .setTitle(`🔄 Stage Transition`)
    .setDescription(
      `**${data.pipelineName}**\n${fromDisplay} → ${toDisplay}`,
    )
    .addFields(
      { name: 'Triggered By', value: data.triggeredBy, inline: true },
    )
    .setColor(COLORS.info)
    .setFooter({ text: `Pipeline ID: ${data.pipelineId}` })
    .setTimestamp();

  return { embeds: [embed] };
}

// ─── Helpers ──────────────────────────────────

const STAGE_ORDER = [
  'intake', 'scaffolding', 'building', 'testing',
  'review', 'staging', 'production', 'published',
];

function buildProgressBar(stages: PipelineStageRecord[]): string {
  const stageMap = new Map(stages.map((s) => [s.stageName, s]));
  return STAGE_ORDER.map((name) => {
    const stage = stageMap.get(name);
    if (!stage) return `⬜ ${name}`;
    switch (stage.status) {
      case 'completed': return `✅ ${name}`;
      case 'active':    return `🔵 **${name}**`;
      case 'failed':    return `❌ ${name}`;
      case 'skipped':   return `⏭️ ${name}`;
      default:          return `⬜ ${name}`;
    }
  }).join('\n');
}

function getStatusColor(status: string): number {
  switch (status) {
    case 'active':    return COLORS.info;
    case 'completed': return COLORS.success;
    case 'failed':    return COLORS.danger;
    case 'paused':    return COLORS.warning;
    default:          return COLORS.neutral;
  }
}

function capitalize(s: string): string {
  return s.charAt(0).toUpperCase() + s.slice(1);
}

function formatDuration(ms: number): string {
  const totalMinutes = Math.floor(ms / 60_000);
  if (totalMinutes < 60) return `${totalMinutes}m`;
  const hours = Math.floor(totalMinutes / 60);
  const minutes = totalMinutes % 60;
  if (hours < 24) return `${hours}h ${minutes}m`;
  const days = Math.floor(hours / 24);
  return `${days}d ${hours % 24}h`;
}
