const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { getServerMode, getEmbedColor, getModeDisplayName, getModeEmoji } = require('../utils/modeHelper');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('status')
    .setDescription('View network status and bot health'),
  
  async execute(interaction, supabase, client) {
    const guildCount = client.guilds.cache.size;
    const memberCount = client.guilds.cache.reduce((sum, g) => sum + g.memberCount, 0);
    const uptime = Math.floor(process.uptime());
    const hours = Math.floor(uptime / 3600);
    const minutes = Math.floor((uptime % 3600) / 60);
    const seconds = uptime % 60;

    const serverMode = supabase ? await getServerMode(supabase, interaction.guildId) : 'standalone';
    const embedColor = getEmbedColor(serverMode);

    let federatedCount = 0;
    let standaloneCount = 0;

    if (supabase) {
      try {
        const { data: configs } = await supabase
          .from('server_config')
          .select('mode');
        
        if (configs) {
          federatedCount = configs.filter(c => c.mode === 'federated' || !c.mode).length;
          standaloneCount = configs.filter(c => c.mode === 'standalone').length;
        }
      } catch (e) {
        federatedCount = guildCount;
      }
    }
    
    const realmStatus = [];
    const REALM_GUILDS = client.REALM_GUILDS || {};
    
    for (const [realm, guildId] of Object.entries(REALM_GUILDS)) {
      if (!guildId) {
        realmStatus.push({ name: realm.charAt(0).toUpperCase() + realm.slice(1), status: 'Not configured', members: 0 });
        continue;
      }
      
      const guild = client.guilds.cache.get(guildId);
      if (guild) {
        realmStatus.push({ name: realm.charAt(0).toUpperCase() + realm.slice(1), status: 'Online', members: guild.memberCount });
      } else {
        realmStatus.push({ name: realm.charAt(0).toUpperCase() + realm.slice(1), status: 'Offline', members: 0 });
      }
    }
    
    const realmFields = realmStatus.map(r => ({
      name: r.name,
      value: `${r.status === 'Online' ? '🟢' : r.status === 'Offline' ? '🔴' : '⚪'} ${r.status}${r.members > 0 ? ` (${r.members.toLocaleString()})` : ''}`,
      inline: true,
    }));
    
    const embed = new EmbedBuilder()
      .setColor(embedColor)
      .setTitle('⚔️ Warden Status')
      .setDescription(`${getModeEmoji(serverMode)} This server is running in **${getModeDisplayName(serverMode)}** mode`)
      .addFields(
        { name: 'Total Servers', value: `${guildCount}`, inline: true },
        { name: 'Total Members', value: `${memberCount.toLocaleString()}`, inline: true },
        { name: 'Uptime', value: `${hours}h ${minutes}m ${seconds}s`, inline: true },
        { name: 'Federated Servers', value: `🌐 ${federatedCount}`, inline: true },
        { name: 'Standalone Servers', value: `🏠 ${standaloneCount}`, inline: true },
        { name: '\u200b', value: '\u200b', inline: true }
      );

    if (serverMode === 'federated' && realmFields.length > 0) {
      embed.addFields(
        { name: '── Federation Realms ──', value: '\u200b', inline: false },
        ...realmFields
      );
    }

    embed.addFields(
      { name: '── Security ──', value: '\u200b', inline: false },
      { name: 'Sentinel Status', value: client.heatMap?.size > 0 ? `⚠️ Monitoring ${client.heatMap.size} user(s)` : '🛡️ All Clear', inline: true },
      { name: 'Active Tickets', value: `${client.activeTickets?.size || 0}`, inline: true },
      { name: 'Federation Mappings', value: `${client.federationMappings?.size || 0}`, inline: true }
    );

    embed
      .setFooter({ text: `Warden • ${getModeDisplayName(serverMode)} Mode` })
      .setTimestamp();
    
    await interaction.reply({ embeds: [embed] });
  },
};
