const { Client, GatewayIntentBits, Collection } = require('discord.js');
require('dotenv').config();
const fs = require('fs');
const path = require('path');

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
        GatewayIntentBits.GuildMembers,
        GatewayIntentBits.GuildVoiceStates
    ]
});

client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');

try {
    const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
    for (const file of commandFiles) {
        const filePath = path.join(commandsPath, file);
        const command = require(filePath);
        client.commands.set(command.name, command);
    }
} catch (error) {
    console.error('Error loading commands:', error);
}

client.once('ready', () => {
    console.log('Bot is online!');
});

// Sets to keep track of "tranq" and "coma" users
const tranqUsers = new Set();
const comaUsers = new Set();

// Path to the JSON file to store baboon users
const baboonUsersPath = path.join(__dirname, 'baboon_users.json');

// Load baboon users from the JSON file
let baboonUsers = {};
if (fs.existsSync(baboonUsersPath)) {
    baboonUsers = JSON.parse(fs.readFileSync(baboonUsersPath, 'utf8'));
}

client.on('messageCreate', async message => {
    if (tranqUsers.has(message.author.id) || comaUsers.has(message.author.id)) {
        await message.delete();
        return;
    }

    if (!message.content.startsWith('~') || message.author.bot) return;

    const args = message.content.slice(1).split(/ +/);
    const commandName = args.shift().toLowerCase();

    if (!client.commands.has(commandName)) return;

    const command = client.commands.get(commandName);

    try {
        console.log(`Passing comaUsers and tranqUsers sets to ${commandName} command with sizes: comaUsers=${comaUsers.size}, tranqUsers=${tranqUsers.size}`);
        await command.execute(message, args, tranqUsers, comaUsers);
    } catch (error) {
        console.error(error);
        message.reply('There was an error trying to execute that command!');
    }
});

client.on('guildMemberRemove', async member => {
    const channelId = '826225570219687956'; // Channel ID to send the message
    const roleId = '1160622954082738347';  // Baboon role ID

    if (member.roles.cache.has(roleId)) {
        const channel = member.guild.channels.cache.get(channelId);
        if (channel) {
            channel.send('The baboon has made an escape!');
        } else {
            console.error(`Channel with ID ${channelId} not found`);
        }

        // Store the user ID in the baboon users list
        baboonUsers[member.id] = true;
        fs.writeFileSync(baboonUsersPath, JSON.stringify(baboonUsers, null, 2), 'utf8');
    }
});

client.on('guildMemberAdd', async member => {
    const channelId = '826225570219687956'; // Channel ID to send the message
    const roleId = '1160622954082738347';  // Baboon role ID

    // Check if the user is in the baboon users list
    if (baboonUsers[member.id]) {
        const role = member.guild.roles.cache.get(roleId);
        if (role) {
            try {
                await member.roles.add(role);
                console.log(`Reapplied baboon role to ${member.user.tag}`);

                const channel = member.guild.channels.cache.get(channelId);
                if (channel) {
                    channel.send(`A loose baboon has been recaptured!`);
                } else {
                    console.error(`Channel with ID ${channelId} not found`);
                }
            } catch (error) {
                console.error(`Failed to reapply baboon role to ${member.user.tag}`, error);
            }
        } else {
            console.error('Baboon role not found');
        }
    }
});

client.login(process.env.DISCORD_TOKEN);
