import discord
#from discord import app_commands
from NarratorAi import setScene, setItem, setRollDice
import random
import flask
import bridges
from threading import Thread
import requests

guild_id = 954201387770736751

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)
tree = discord.app_commands.CommandTree(client)



@tree.command(name="roll_die", 
              description="Ask NARC to roll dice for you with flair.",
              guild=discord.Object(id=guild_id)
              )
async def roll_die(interaction, num_sides: str):
    channel = client.get_channel(interaction.channel_id)
    person = interaction.user.display_name
    result = random.randint(1, int(num_sides))
    await interaction.response.defer(ephemeral=False, thinking=False)
    scene = await setRollDice(person, num_sides, result)
    await channel.send(f"*{scene}*")
    await interaction.delete_original_response()


@tree.command(name="give_item", 
              description="Ask NARC for an item.",
              guild=discord.Object(id=guild_id)
              )
async def give_item(interaction, item: str):
    channel = client.get_channel(interaction.channel_id)
    person = interaction.user.display_name
    await interaction.response.defer(ephemeral=False, thinking=False)
    scene = await setItem(item, person)
    await channel.send(f"*{scene}*")
    await interaction.delete_original_response()

@tree.command(name="set_scene", 
              description="Provide a prompt for the narrator to set a scene",
              guild=discord.Object(id=guild_id)
              )
async def set_scene(interaction, prompt: str):
    channel = client.get_channel(interaction.channel_id)
    await interaction.response.defer(ephemeral=False, thinking=False)
    scene = await setScene(prompt=prompt)
    await channel.send(f"*{scene}*")
    await interaction.delete_original_response()



@tree.command(name="narrate", description="This is a command to narrate", guild=discord.Object(id=guild_id))
async def narrate(interaction, text: str):
    channel = client.get_channel(interaction.channel_id)
    await interaction.response.defer(ephemeral=False, thinking=False)
    await channel.send(f"*{text}*")
    await interaction.delete_original_response()

@client.event
async def on_ready():
    await tree.sync(guild=discord.Object(id=guild_id))
    print(f'We have logged in as {client.user}')


channels = {
    1125968295967850559: "our-comforter", #comforter
    954201387770736754: "lounge", #lounge
    1119502004721557554: "town-square", # kweh
    1367978276185964584: "misskey", #misskey
    1167176429797113926: "photos-from-another-star", #photos-from-another-star
    1119508652844404816: "bulletin-board", #bulletin-board
    955394194766192690: "photos-of-the-gang" #photos-of-the-gang
}

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if not message.webhook_id and message.channel.id in channels.keys():
        bridges.send_discord_to_mattermost(message, channel_to=channels[message.channel.id])
        

async def send_custom_message(channel: discord.TextChannel, message, username, user_id, avatar_url=None):
    if user_id:
        print(user_id)
        member = await channel.guild.fetch_member(user_id)
        avatar_url = member.display_avatar.url
        username = member.nick
    elif avatar_url:
        avatar_url = avatar_url
    else:
        avatar_url = ""

    print(avatar_url)
    webhook = await channel.create_webhook(name=username)
    await webhook.send(message, username=username, avatar_url=avatar_url)
    await webhook.delete()

# flask
app = flask.Flask(__name__)

@app.route('/post_message', methods=['POST'])
async def post_message():
    data:dict = flask.request.json
    message = data.get('message')
    username = data.get('username', 'Unknown')
    avatar_url = data.get('avatar_url', None)
    user_id = data.get('discord_id', None)    
    print(data)
    if message == "":
        return flask.jsonify({'error': 'Message cannot be blank.'}), 400

    channel = client.get_channel(data['channel_to'])
    if channel:
        client.loop.create_task(send_custom_message(channel, message, username, user_id, avatar_url))
        #client.loop.create_task(channel.send(message))
        return flask.jsonify({'status': 'Message sent successfully.'}), 200
    else:
        return flask.jsonify({'error': 'Channel not found.'}), 404

def run_flask_app():
    app.run(port=5001)

# Run the Flask app in a separate thread
thread = Thread(target=run_flask_app)
thread.start()


token = "MTMyNzcxNDM3MTEyMzgxMDMwNA.GwLjEd.quGP0FA5gHRe1xLyuYq-ANuJ5cRuRQ6dhJiojI"
client.run(token)


