const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');

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 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(0x7c3aed)
      .setTitle('AeThex Network Status')
      .setDescription('Current status of the AeThex Federation')
      .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 },
        ...realmFields,
        { name: 'Sentinel Status', value: client.heatMap.size > 0 ? `⚠️ Monitoring ${client.heatMap.size} user(s)` : '🛡️ All Clear', inline: false },
        { name: 'Active Tickets', value: `${client.activeTickets.size}`, inline: true },
        { name: 'Federation Mappings', value: `${client.federationMappings.size}`, inline: true }
      )
      .setFooter({ text: 'AeThex Unified Bot' })
      .setTimestamp();
    
    await interaction.reply({ embeds: [embed] });
  },
};
