require('dotenv').config();
const fs = require('node:fs');
const deepl = require('deepl-node');
const path = require('node:path');
const deploy = require('./src/discord/deploy_command.js')
const update  = require('./src/pterodactyl/displayer.js');
const clean = require('./src/pterodactyl/cleaner.js');
const { Client, GatewayIntentBits, Collection, Events, Partials } = require('discord.js');
const { initDatabase, createTables, cleanExpiredCodes } = require('./src/core/database.js');
const { startConsoleMonitoring, forceWebSocketReconnect } = require('./src/monitoring/consoleMonitor.js');
const { initPalworldBridge } = require('./src/bridge/palworld-bridge.js');
const { startRAMMonitoring } = require('./src/monitoring/ramMonitor.js');

const client = new Client({ intents:
	[
		GatewayIntentBits.GuildMembers,
		GatewayIntentBits.GuildMessages,
		GatewayIntentBits.GuildMessageReactions,
		GatewayIntentBits.MessageContent,
		GatewayIntentBits.Guilds
	],
	partials: [Partials.Message, Partials.Channel, Partials.Reaction, Partials.User],
});

const headers = {
    "Accept": "application/json",
    "Content-Type": "application/json",
    "Authorization": "Bearer " + process.env.PTERODACTYL_API_TOKEN
};
const numbers=["𝟎","𝟏","𝟐","𝟑","𝟒","𝟓","𝟔","𝟕","𝟖","𝟗","𝟏𝟎","𝟏𝟏","𝟏𝟐","𝟏𝟑","𝟏𝟖","𝟏𝟕","𝟏𝟖","𝟏𝟗","𝟐𝟎","𝟐𝟏","𝟐𝟐","𝟐𝟑","𝟐𝟒","𝟐𝟓","𝟐𝟔","𝟐𝟕","𝟐𝟖","𝟐𝟗","𝟑𝟎","𝟑𝟏","𝟑𝟐"];

const translator = process.env.DEEPL_TOKEN ? new deepl.Translator(process.env.DEEPL_TOKEN) : null;

client.commands = new Collection();
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);

for (const folder of commandFolders) {
	const commandsPath = path.join(foldersPath, folder);
	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);
		// Set a new item in the Collection with the key as the command name and the value as the exported module
		if ('data' in command && 'execute' in command) {
			client.commands.set(command.data.name, command);
		} else {
			console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
		}
	}
}

client.once('ready', async () => {
  client.user.setPresence({ activities: [{ name: 'Rygain', type: 'WATCHING' }], status: 'online' });
  console.log('Bot started !');
  
  try {
    await initDatabase();
    await createTables();
    
    // Nettoyer les codes expirés au démarrage
    await cleanExpiredCodes();
    console.log('🧹 Codes expirés nettoyés');
    
    console.log('📦 Système de liaison activé');
    
    // Initialiser le pont Palworld-Discord
    const bridgeChannelId = process.env.BRIDGE_CHANNEL_ID || '1467491354924814411';
    console.log(`🔧 Configuration du pont: Salon ${bridgeChannelId}`);
    
    // Vérifier que le salon existe
    try {
      const bridgeChannel = await client.channels.fetch(bridgeChannelId);
      if (bridgeChannel) {
        console.log(`✅ Salon du pont trouvé: #${bridgeChannel.name}`);
        initPalworldBridge(client, bridgeChannelId);
      } else {
        console.error(`❌ Salon du pont introuvable (ID: ${bridgeChannelId})`);
      }
    } catch (channelError) {
      console.error(`❌ Erreur lors de la récupération du salon du pont:`, channelError.message);
      console.error(`⚠️ Le pont Discord-Palworld est désactivé`);
    }
    
    startConsoleMonitoring(client, process.env.PTERODACTYL_API_TOKEN);
    
    // Démarrer la surveillance RAM avec callback de reconnexion WebSocket
    startRAMMonitoring(forceWebSocketReconnect);
    console.log('✅ Surveillance RAM activée (seuil: 19 Go)');
  } catch (error) {
    console.error('⚠️ Erreur lors de l\'initialisation de la base de données');
    console.error('⚠️ Le système de liaison est désactivé');
    console.error('⚠️ Les autres fonctionnalités du bot restent actives');
  }
  
  deploy(process.env.DISCORD_TOKEN);
  clean(client);
});

client.on(Events.InteractionCreate, async interaction => {
	if (!interaction.isChatInputCommand()) return;

	// Vérifier que la commande provient du bon serveur
	if (interaction.guildId !== process.env.GUILD_ID) {
		return interaction.reply({ 
			content: 'Ce bot ne peut être utilisé que sur un serveur spécifique.', 
			ephemeral: true 
		});
	}

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

	if (!command) {
		console.error(`No command matching ${interaction.commandName} was found.`);
		return;
	}

	try {
		if (interaction.commandName === 'server-stats') {
			await command.execute(interaction, process.env.PALWORLD_API_TOKEN);
		} else if (interaction.commandName === 'trad') {
			await command.execute(interaction, translator);
		} else if (interaction.commandName === 'start-server' || interaction.commandName === 'reboot-server' || interaction.commandName === 'server-clean') {
			await command.execute(interaction, headers);
		} else {
			await command.execute(interaction);
		}
	} catch (error) {
		console.error(error);
		if (interaction.replied || interaction.deferred) {
			await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
		} else {
			await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
		}
	}
});

client.login(process.env.DISCORD_TOKEN);

setInterval(()=>{update(headers,numbers,client,process.env.PALWORLD_API_TOKEN)}, 300000);