import discord
import logging
import os
import time
import asyncio
import requests
import base64
import subprocess
import json
import ffmpeg
import pyttsx3
from datetime import timedelta
from dotenv import load_dotenv
from random import randint, choice, random


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)

tts_engine = pyttsx3.init()
is_sleeping = False
crash_out_time = time.time()
mood = 5 # if this reaches 0 he snaps for at you lol
words = ["gleep", "glorp", "zorp", "gnarp", "gorg", "alien", "alienz", "goog", "slorp", "gorg"]
emojis = ["👽", "🔥", "🗣️"]
yes_no_answers = [
	"zis post waz fakt checkt **TRU** bai rel alienz",
	"yez",
	"gleep ✅",
	"zorp ❌",
	"naur",
	"zis post waz fakt checkt **FALS** bai rel alienz",
	"EW NAUR YUCKY",
	"yea"
]
sad_answers = [
	"naur, i'm sorry :(",
	"naurrr 🥺",
	"plz naur D:",
	"\*sad alien noises\* 😔"
]
happy_answers = [
	"yai!!! :D",
	"yipee",
	"yahoo",
	"gleep :)"
]
swear_words = ["fuck", "shit", "cunt", "bitch", "fucking", "fag", "nigg"]
hi = ["hi", "hi ", "hey ", "hello "]
hello = ["hii :3", "hewwo :3", "heyy :D"]
why_question_answers = [
	"cuz you smell like SHIT",
	"cuz you SUCK",
	"cuz you're veri pretti :3",
	"cuz i luv uuuu",
	"cuz i HATE you",
	"cuz u smel rly gud :D",
	"idfk don't ask me :/",
	"cuz i made it happen",
	"cuz it's fact",
	"it's a universal law"
]
when_question_answers = [
	"now",
	"in 5 seconds",
	'in an hour',
	"in a day",
	"in 3 days",
	"in a week",
	"in 2 weeks",
	"in a month",
	"in 6 months",
	"in a year",
	"in 2 years",
	"in 5 years",
	"in 10 years",
	"in a 100 years",
	"in so long you won't be alive anymore",
	"later"
]
crash_out_responses = [
	"...",
	"the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end",
	"https://tenor.com/view/susan-woodings-susan-woodings-the-walten-files-twf-gif-24185478",
	"........",
	". . . ",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"...",
	"i was crazy once. they locked me in a room. a rubber room. a rubber room with rats. and rats make me crazy.",
	"not. right. now.",
	"GOD JUST SHUT UP, PLEASE. I BEG OF YOU"
]
thanks_responses = [
	"no problem!!! :D",
	"you are welcomz",
	'hehe :3'
]


class MusicMenu(discord.ui.Select):
	def __init__(self):
		options = [discord.SelectOption(label=a.rsplit(".", 1)[0]) for a in os.listdir("music")] + [discord.SelectOption(label="random song", description="gleep glorp wil chuz a son for u!!!!", value="RANDOM")]
		super().__init__(max_values=1, min_values=1, placeholder="chuz songz", options=options)

	async def callback(self, interaction: discord.Interaction):
		chosen_song = self.values[0] + ".mp3" if self.values[0] != "RANDOM" else choice(os.listdir("music"))

		if self.values[0] == "RANDOM":
			await interaction.response.send_message(content="i choz {chosen_song.rsplit('.', 1)[0]} forr uuuu :3\ngimme a sec while i send it...")
		else:
			await interaction.response.send_message(content="gimme a sec while i send it...")
		
		file = os.path.join("music/", chosen_song)
		await send_voice_message(file, interaction.channel)

class MusicView(discord.ui.View):
	def __init__(self):
		super().__init__()
		self.add_item(MusicMenu())


async def send_tts_message(message: str, channel: discord.TextChannel):
	tts_engine.save_to_file(message, "voice-message.mp3")
	tts_engine.runAndWait()
	await send_voice_message("voice-message.mp3", channel)
	if os.path.exists("voice-message.mp3"): os.remove("voice-message.mp3")

async def send_voice_message(file_path: str, channel: discord.TextChannel):
	bot_token = os.getenv('TOKEN')
	# Convert MP3 to OGG (Opus) using ffmpeg
	ogg_filename = "voice-message.ogg"
	try:
		subprocess.run([
			"ffmpeg",
			"-y",
			"-i", file_path,
			"-c:a", "libopus",
			"-b:a", "64k",
			"-ar", "48000",
			ogg_filename
		], check=True, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)

		# Extract metadata using ffprobe
		def get_audio_metadata(file_path):
			""" Extracts audio duration and waveform data using ffprobe. """
			audio = ffmpeg.probe(file_path)

			# Generate a simple waveform (instead of real analysis)
			waveform = base64.b64encode(os.urandom(256)).decode('utf-8')
			return round(float(audio["format"]["duration"])), waveform
		
		# Get required metadata
		duration, waveform = get_audio_metadata(ogg_filename)
		file_size = os.path.getsize(ogg_filename)

		# Step 1: Request an upload URL
		url = f"https://discord.com/api/v10/channels/{channel.id}/attachments"
		headers = {
			"Authorization": f"Bot {bot_token}",
			"Content-Type": "application/json",
			#"User-Agent": UserAgent().random
		}
		payload = {
			"files": [{
				"filename": "voice-message.ogg",
				"file_size": file_size,
				"id": 0
			}]
		}
		response = requests.post(url, headers=headers, json=payload)

		if response.status_code != 200:
			print("Failed to get upload URL:", response.text)
			exit()

		upload_data = response.json()["attachments"][0]
		upload_url = upload_data["upload_url"]
		uploaded_filename = upload_data["upload_filename"]

		# Step 2: Upload the audio file
		with open(ogg_filename, "rb") as file:
			upload_response = requests.put(upload_url, headers={"Content-Type": "audio/ogg"}, data=file)

		if upload_response.status_code != 200:
			print("Failed to upload file:", upload_response.text)
			exit()

		# Step 3: Send the voice message
		message_url = f"https://discord.com/api/v10/channels/{channel.id}/messages"
		message_payload = {
			"flags": 8192,  # IS_VOICE_MESSAGE
			"attachments": [{
				"id": "0",
				"filename": "voice-message.ogg",
				"uploaded_filename": uploaded_filename,
				"duration_secs": duration,
				"waveform": waveform
			}]
		}

		message_response = requests.post(message_url, headers=headers, json=message_payload)

		print(message_response.status_code, f"Error Response: \n{json.dumps(message_response.text, indent=4, ensure_ascii=False)}" if message_response.status_code != 200 else "Upload Succesfull!")
	finally:
		if os.path.exists(ogg_filename): os.remove(ogg_filename)


async def sleep_cycle():
	global is_sleeping
	while True:
		await asyncio.sleep(randint(300, 900))  # every 5–15 mins
		if not is_sleeping and random() < 0.3:  # 30% chance to fall asleep
			is_sleeping = True
			await client.change_presence(status=discord.Status.idle)
			print("💤 Bot is sleeping...")
			await asyncio.sleep(randint(60, 180))  # sleep 1–3 mins

			if is_sleeping:
				await client.change_presence(status=discord.Status.online)
				is_sleeping = False
				print("☀️ Bot woke up!")

async def increase_mood(message: discord.Message):
	global mood
	if mood == 0:
		return
	mood += 1

async def decrease_mood(message: discord.Message):
	global mood
	if mood == 0:
		return
	mood -= 1

	if mood == 1:
		await message.channel.send("i can't take this much longer")

	if mood == 0:
		crash_out_time = time.time()
		await message.reply("I CANTZ TAEK IT ANYMOR!!!!")
		await message.channel.send("https://tenor.com/view/crash-out-strangle-over-it-im-done-wtf-gif-5733066100478599257")

admin_role_id = 1412398091549675541

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

@client.event
async def on_ready():
	client.loop.create_task(sleep_cycle())
	#channel = await client.fetch_channel(1431237413845340311)
	#await send_voice_message("test.mp3", channel)
	print("gleep glorp!!!!!! 👽👍")

@client.event
async def on_message(message: discord.Message):
	global mood, is_sleeping
	if time.time()-crash_out_time > 60:
		mood = 5

	if message.author == client.user:
		return
	
	if mood > 0:
		for swear_word in swear_words:
			if message.clean_content.lower().find(swear_word) != -1:
				await message.reply("no swearing")
				await message.channel.send("https://tenor.com/view/xenoverse-goku-super-saiyan-angry-dbz-gif-1416275111944307575")
				await decrease_mood(message)
				return
	
	if client.user.mentioned_in(message):
		response = ""
		content = message.clean_content.removeprefix("@gleep glorp").lower().strip()

		if content.find("wake up") != -1:
			if is_sleeping:
				is_sleeping = False
				await message.reply("AAAAA oh. i am awaken :)")
				await client.change_presence(status=discord.Status.online)
			else:
				await message.reply("i was not sleeps")
			return
		
		if is_sleeping:
			if random() < 0.1:
				await message.reply("💤 \*mumbles in sleep\*")
			return

		if mood <= 0:
			await message.reply(choice(crash_out_responses))
			return

		if content.startswith("kill"):
			if content == "kill yourself":
				await message.reply(choice(sad_answers))
				await decrease_mood(message)
				return
			else:
				

				if message.mention_everyone == True:
					await message.reply("veri funni buckaroo :|")
					return

				if message.guild.get_role(admin_role_id) in message.author.roles:
					try:
						target = message.mentions[1]
						await message.reply("deploying gleep glorp lazor off dume!!!!")
						time.sleep(1)
						await message.channel.send("targor aquire....")
						time.sleep(2)
						await message.channel.send("im jus kiddings!!! im still timing u out tho " + target.mention)
						time.sleep(1)
						await target.timeout(timedelta(minutes=5))
						
					except IndexError:
						await message.reply("you didn't say who to kill")
					except discord.errors.Forbidden:
						await message.reply("i can't >:(")
				else:
					await message.reply("you can't do that you don't have admin dumbass")
				return

		for greeting in hi:
			if message.clean_content.lower().startswith(greeting):
				await message.reply(choice(hello))
				return

		if content.find("goon") != -1:
			response = "gooning is not allowed you fucking weirdo"
			await decrease_mood(message)
		elif content.startswith("play"):
			#song_name = choice(os.listdir("music"))
			#await message.reply("ok ill play " + song_name.rsplit(".", 1)[0])
			#file = os.path.join("music/", song_name)
			#await send_voice_message(file, message.channel)
			await message.reply("here are the songs i have", view=MusicView())
			return
		elif content.startswith("speak "):
			content = content.removeprefix("speak ")
			await send_tts_message(content, message.channel)
			return
		elif content.startswith("say "):
			content = content.removeprefix("say ")
			response = content
		elif content.find("bad alien") != -1:
			response = choice(sad_answers)
			await decrease_mood(message)
		elif content.find("good alien") != -1:
			response = choice(happy_answers)
		elif content.find("why") != -1:
			response = choice(why_question_answers)
		elif content.find("when") != -1:
			response = choice(when_question_answers)
		elif content.startswith("who"):
			response = f"da rel alienz sai it was {choice(message.guild.members).mention}"
		elif content.startswith("do ") or content.startswith("can ") or content.startswith("is ") or content.find("am ") != -1 or content.find("will ") != -1 or content.startswith("are ") or content.find("which") != -1 or content.find("would") != -1 or content.find("does") != -1 or content.startswith("should"):
			response = choice(yes_no_answers)
		elif content.find("ily") != -1 or content.find("love you") != -1 or content.find("i like you") != -1:
			response = choice(happy_answers)
			await increase_mood(message)
		elif content.find("ihy") != -1 or content.find("hate you") != -1 or content.find("detest you") != -1 or content.find("despise you") != -1 or content.find("hate you") != -1 != -1 or content.find("screw you") != -1 or content.find("fuck you") != -1:
			response = choice(sad_answers)
			await decrease_mood(message)
		elif content.find("thanks") != -1 or content.find("thank you") != -1:
			response = choice(thanks_responses)
			await increase_mood(message)
		else:
			if randint(1, 10) != 1:
				for _ in range(randint(1, 8)):
					response += choice(words) + " "

				response = response[:-1] + ("!" * randint(2,4)) + " "

				if randint(1,2) == 1:
					for _ in range(randint(1,3)):
						response += choice(emojis)
			else:
				response = "meow"
		
		await message.reply(response)
	

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