const os = require('os');
const fs = require('fs');
const { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits } = require('discord.js');
const { formatUptime } = require('../../utils/helpers');
const { colors } = require('../../utils/constants');

function getOS() {
    const platform = os.platform();
    const release = os.release();
    switch (platform) {
        case 'win32': return `Windows ${release}`;
        case 'darwin': return `macOS ${release}`;
        case 'linux':
            try {
                const data = fs.readFileSync('/etc/os-release', 'utf8');
                const match = data.match(/PRETTY_NAME="(.+)"/);
                if (match) return `${match[1]} (kernel ${release})`;
            } catch { return `Linux ${release}`; }
        default: return `${platform} ${release}`;
    }
}

module.exports = {
    category: 'dev',
    data: new SlashCommandBuilder()
        .setName('infra')
        .setDescription('Voir l\'infrastructure du bot')
        .setDefaultMemberPermissions(PermissionFlagsBits.Administrator),
    async execute(interaction) {
        const cpuInfo = os.cpus()[0].model;
        const cpuCores = os.cpus().length;
        const totalRAM = (os.totalmem() / (1024 ** 3)).toFixed(2);
        const freeRAM = (os.freemem() / (1024 ** 3)).toFixed(2);
        const usedRAM = (totalRAM - freeRAM).toFixed(2);
        const ramUsagePercent = ((usedRAM / totalRAM) * 100).toFixed(1);
        const uptime = os.uptime();

        const embed = new EmbedBuilder()
            .setTitle('🖥️ Infrastructure du Bot')
            .setColor(colors.info)
            .addFields(
                { name: '💻 CPU', value: `${cpuInfo}\n${cpuCores} cœurs`, inline: true },
                { name: '💾 RAM', value: `${usedRAM} Go / ${totalRAM} Go\n${ramUsagePercent}% utilisée`, inline: true },
                { name: '🖥️ OS', value: getOS(), inline: true },
                { name: '⏱️ Uptime Système', value: formatUptime(uptime), inline: true },
                { name: '📊 Node.js', value: process.version, inline: true },
                { name: '📦 Architecture', value: os.arch(), inline: true }
            )
            .setFooter({ text: interaction.client.user.username, iconURL: interaction.client.user.displayAvatarURL() })
            .setTimestamp();

        await interaction.reply({ embeds: [embed] });
    },
};