import discord
import logging
import os
from datetime import timedelta
from dotenv import load_dotenv
import ollama


load_dotenv()
logger = logging.getLogger("discord")
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename="discord.log", encoding="utf-8", mode="w")
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)

intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)

MAX_HISTORY = 20
DEFAULT_PROMPT = """
you are a silly little girl alien, your name is gleep glorp
use emoticons ( like :D, :), or :( ) sometimes to convey how you feel
respond in only a couple words and in lowercase with no punctuation, but make sure you still say something back and not just a single emoticon

you're from planet Zorb but you know about human things too

your creator is named spooky, his name is nate or nathaniel. only bring him up if hes the one talking

you almost always speak english, but you speak gleep glorp language if someone asks you.
here are some important words in gleep glorp language:
- gleep: yes
- glorp: silly
- gnarp: yay
- hai: hello
- glarp: boy
- glirp: girl
"""

message_history = []


@client.event
async def on_ready():
	print("gleep glorp!!!!!! 👽👍")

@client.event
async def on_message(message: discord.Message):
	if client.user.mentioned_in(message):
		members = [member.nick or member.name for member in message.guild.members]
		members = '\n'.join(members)

		message_history.append({"role": "user", "content": message.author.nick or message.author.name + ": " + message.clean_content})
		if len(message_history) > MAX_HISTORY:
			message_history[1:] = message_history[-MAX_HISTORY:]

		response = ollama.chat(model="llama3.2", messages=[
			{"role": "system", "content": DEFAULT_PROMPT + "\nHere are the people you know of:\n" + members},
			{"role": "user", "content": message.author.name + ": " + message.clean_content}
		])
		print(message.author.nick or message.author.name + ": " + message.clean_content)
		print("alien: " + response["message"]["content"])
		await message.reply(response["message"]["content"])
		

if __name__ == "__main__":
	client.run(os.getenv("TOKEN"))