using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.EventArgs;
using OpenAI.Chat;

namespace Bot.modules;

public class Politico
{
    private readonly HashSet<string> _channels = [];
    private readonly ChatClient? _chatClient;
    private readonly Dictionary<DiscordUser, List<ChatMessage>> _userHistory = new();
    
    public Politico(IEnumerable<string> channels, string? openAiKey = null, string model = "gpt-4o")
    {
        if (openAiKey == null) return;
        _chatClient = new ChatClient(model, openAiKey);
        foreach (var channel in channels)
        {
            _channels.Add(channel);
        }
    }
    
    public async Task MessageCreatedHandler(DiscordClient c, MessageCreatedEventArgs e)
    {
        if (e.Author.IsCurrent || !_channels.Contains(e.Channel.Name)) return;
        if (Random.Shared.NextDouble() < 0.99f && !e.MentionedUsers.Contains(c.CurrentUser)) return;
        if (_chatClient == null) return;
        
        var user = e.Author;
        var m = await e.Guild.GetMemberAsync(e.Author.Id);
        var name = m.DisplayName;
        var messages = _userHistory.TryGetValue(user, out var value) ? value : 
        [
            new SystemChatMessage("Take on the persona of Robocop, and answer as him. " +
                                  "Answers should be plausibly something Robocop would say in his movies. " +
                                  "You may optionally use direct quotes from Robocop in the movies in your responses if you can work them in naturally. " +
                                  "Do not include quotation marks in your response.  Short answers are mandatory, 50 words or less." +
                                  "The topic of the channel is US and international politics.  The goal is to create absurdist humor contrasting Robocop's personality" +
                                  "against modern day politics to create hilariously politically incorrect answers." +
                                  "You are required to take a side in any debate or policy matter, you are not allowed to be neutral." +
                                  "Controversy, especially if it is non-nonsensical is highly desirable."),
        ];
        
        messages.Add(new UserChatMessage(e.Message.Content));
        await e.Channel.TriggerTypingAsync();
        var resp = await _chatClient.CompleteChatAsync(messages);
        var respText = resp.Value.Content.Last().Text;
        
        await e.Message.RespondAsync(respText);
        messages.Add(new AssistantChatMessage(respText));
        _userHistory[user] = messages;
    }
}