using Bot.modules;
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.EventArgs;
using IniParser;

namespace Bot
{
    internal static class RobertBot
    {
        private static async Task Main(string[] args)
        {
            // Config setup
            var botToken = Environment.GetEnvironmentVariable("BOT_TOKEN");
            if (botToken == null)
            {
                await Console.Error.WriteLineAsync("Missing BOT_TOKEN environment variable");
                Environment.Exit(1);
            }
            var openAiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
            var configParser = new FileIniDataParser();
            var config = configParser.ReadFile(Path.Combine(AppContext.BaseDirectory, "config.ini"));
            
            // Module setup
            var messageHandlers = new List<Func<DiscordClient, MessageCreatedEventArgs, Task>>();
            
            // TFC Setup
            if (config["TextFreeChannels"]["active"] == "true")
            {
                var textFreeChannelList = config["TextFreeChannels"]["channels"].Split(",").ToList();
                var textFreeChannels = new TextFreeChannels(textFreeChannelList, openAiKey);
                messageHandlers.Add(textFreeChannels.MessageCreatedHandler);
            }

            // Politico Setup
            if (config["Politico"]["active"] == "true")
            {
                var politicoChannelList = config["Politico"]["channels"].Split(",").ToList();
                var politico = new Politico(politicoChannelList, openAiKey);
                messageHandlers.Add(politico.MessageCreatedHandler);
            }
            
            // Bot client setup
            var builder = DiscordClientBuilder.CreateDefault(botToken, DiscordIntents.AllUnprivileged | DiscordIntents.MessageContents);
            builder.ConfigureEventHandlers(b =>
            {
                foreach (var h in messageHandlers) {b.HandleMessageCreated(h);}
            });

            DiscordActivity status = new("You.", DiscordActivityType.Watching);
            var client = builder.Build();
            
            // RobertMart Setup
            
            if (config["RobertMart"]["active"] == "true")
            {
                var robertMartChannelList = config["RobertMart"]["channels"].Split(",").ToList();
                var robertMart = new RobertMartClient(client, robertMartChannelList.Select(ulong.Parse).ToList(), openAiKey);
                robertMart.SendScheduledMessage();
            }
            
            await client.ConnectAsync();
            await Task.Delay(-1);
        }
    }
}