import {
  SlashCommandSubcommandBuilder,
  EmbedBuilder,
  type ChatInputCommandInteraction,
} from 'discord.js';
import { api } from '../api-client.js';
import { COLORS, PRIORITY_CONFIG } from '../config.js';
import { logger } from '../logger.js';

export const data = new SlashCommandSubcommandBuilder()
  .setName('status')
  .setDescription('Quick dashboard summary of the factory');

export async function execute(interaction: ChatInputCommandInteraction): Promise<void> {
  await interaction.deferReply();

  try {
    const summary = await api.getDashboardSummary();

    const embed = new EmbedBuilder()
      .setTitle('🏭 GooseFactory Dashboard')
      .setDescription('Real-time factory status overview')
      .addFields(
        // Pipelines
        {
          name: '📊 Pipelines',
          value: [
            `🟢 Active: **${summary.pipelines.active}**`,
            `⏸️ Paused: **${summary.pipelines.paused}**`,
            `✅ Completed: **${summary.pipelines.completed}**`,
            `❌ Failed: **${summary.pipelines.failed}**`,
          ].join('\n'),
          inline: true,
        },
        // Tasks
        {
          name: '📥 Decision Queue',
          value: [
            `⏳ Pending: **${summary.tasks.pending}**`,
            `🔄 In Progress: **${summary.tasks.inProgress}**`,
            `🚧 Blocked: **${summary.tasks.blocked}**`,
            `⏱️ Avg Wait: **${Math.round(summary.tasks.avgWaitTimeMinutes)}m**`,
            summary.tasks.slaBreaches > 0
              ? `🚨 SLA Breaches: **${summary.tasks.slaBreaches}**`
              : `✅ SLA Breaches: **0**`,
          ].join('\n'),
          inline: true,
        },
        // Agents
        {
          name: '🤖 Agents',
          value: [
            `🟢 Active: **${summary.agents.active}**`,
            `💤 Idle: **${summary.agents.idle}**`,
            `⚠️ Error: **${summary.agents.error}**`,
            `🔴 Offline: **${summary.agents.offline}**`,
          ].join('\n'),
          inline: true,
        },
        // SLA Status
        {
          name: '⏰ SLA Status',
          value: [
            `✅ On Track: **${summary.slaStatus.onTrack}**`,
            `⚠️ Warning: **${summary.slaStatus.warning}**`,
            `🚨 Breached: **${summary.slaStatus.breached}**`,
          ].join('\n'),
          inline: false,
        },
        // Priority breakdown
        {
          name: '🎯 Tasks by Priority',
          value: Object.entries(summary.tasks.byPriority)
            .map(([p, count]) => {
              const cfg = PRIORITY_CONFIG[p as keyof typeof PRIORITY_CONFIG];
              return cfg ? `${cfg.emoji} ${cfg.label}: **${count}**` : `${p}: **${count}**`;
            })
            .join(' · ') || 'None',
          inline: false,
        },
      )
      .setColor(summary.tasks.slaBreaches > 0 ? COLORS.slaBreach : COLORS.info)
      .setFooter({ text: 'GooseFactory' })
      .setTimestamp();

    await interaction.editReply({ embeds: [embed] });
  } catch (error) {
    logger.error('Failed to fetch dashboard summary:', error);
    await interaction.editReply({
      content: `❌ Failed to fetch factory status: ${error instanceof Error ? error.message : 'Unknown error'}`,
    });
  }
}
