import discord
from discord.ext import commands

from utils.npc_memory import NPCMemory
from utils.npc_handler import NPCHandler

class NPCCog(commands.Cog):
    def __init__(self, bot):
        npc_handler = NPCHandler(NPCMemory())
        self.bot = bot
        self.npc_handler = npc_handler
        self.player_contexts = {}

    @commands.command(name="talk")
    async def talk_to_npc(self, ctx, npc_name: str, *, message: str):
        player_id = str(ctx.author.id)
        if player_id not in self.player_contexts:
            self.player_contexts[player_id] = {
                'id': player_id,
                'level': 1,
                'reputation': 0,
                'recent_actions': [],
                'location': 'Newhaven'
            }
        # Send placeholder message
        thinking_msg = await ctx.send(f"**{npc_name.replace('_', ' ').title()} is thinking...**")
        # Get LLM response
        response = self.npc_handler.chat_with_npc(
            npc_name, message, self.player_contexts[player_id]
        )
        embed = discord.Embed(
            title=f"{npc_name.replace('_', ' ').title()} says...",
            description=response,
            color=discord.Color.blue()
        )
        # Edit the original message with the response
        await thinking_msg.edit(content=None, embed=embed)

    @commands.command(name="npcs")
    async def list_npcs(self, ctx):
        npc_list = "\n".join([f"• {name}" for name in self.npc_handler.npcs.keys()])
        await ctx.send(f"Available NPCs:\n{npc_list}")

    @commands.command(name="quest")
    async def get_quest(self, ctx, npc_name: str):
        player_id = str(ctx.author.id)
        player_level = self.player_contexts.get(player_id, {}).get('level', 1)
        quest = self.npc_handler.generate_quest(npc_name, player_level)
        if quest:
            embed = discord.Embed(
                title=quest["title"],
                description=quest["description"],
                color=discord.Color.gold()
            )
            embed.add_field(name="Reward", value=quest["reward"])
            embed.add_field(name="Difficulty", value=quest["difficulty"])
            await ctx.send(embed=embed)
        else:
            await ctx.send("NPC not found or unable to generate quest.")

async def setup(client):
    await client.add_cog(NPCCog(client))