import disnake
from disnake.ext import commands
from datetime import datetime
from collections import deque
from utils.premium import check_premium_tier

class SnipeCommands(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        # Dictionary to store deleted messages per channel
        # Key: channel_id, Value: deque of deleted messages (max 10 per channel)
        self.deleted_messages = {}

    @commands.Cog.listener()
    async def on_message_delete(self, message):
        """Track deleted messages for the snipe command"""
        if message.author.bot:
            return
        
        channel_id = message.channel.id
        
        # Initialize deque for this channel if it doesn't exist
        if channel_id not in self.deleted_messages:
            self.deleted_messages[channel_id] = deque(maxlen=10)
        
        # Store message details
        message_data = {
            'content': message.content,
            'author': message.author,
            'timestamp': datetime.now(),
            'attachments': [attachment.url for attachment in message.attachments],
            'embeds': len(message.embeds)
        }
        
        self.deleted_messages[channel_id].appendleft(message_data)

    @commands.slash_command(name="snipe", description="Voir les derniers messages supprimés d'un salon")
    @check_premium_tier()
    async def snipe(self, interaction: disnake.ApplicationCommandInteraction, 
                    nombre: int = commands.Param(1, description="Nombre de messages à afficher (1-10, par défaut: 1)")):
        """Retrieve deleted messages from the current channel"""
        channel_id = interaction.channel.id
        
        # Validate the number parameter
        if nombre < 1 or nombre > 10:
            await interaction.response.send_message(
                "❌ Le nombre doit être entre 1 et 10.", 
                ephemeral=True
            )
            return
        
        # Check if we have any deleted messages for this channel
        if channel_id not in self.deleted_messages or not self.deleted_messages[channel_id]:
            await interaction.response.send_message(
                "❌ Aucun message supprimé trouvé dans ce salon.", 
                ephemeral=True
            )
            return
        
        # Get the requested number of messages
        messages = list(self.deleted_messages[channel_id])[:nombre]
        
        # Create embed for displaying deleted messages
        embed = disnake.Embed(
            title=f"🗑️ Messages supprimés ({len(messages)} sur {len(self.deleted_messages[channel_id])} disponibles)",
            color=disnake.Color.red()
        )
        
        for i, msg_data in enumerate(messages, 1):
            author = msg_data['author']
            content = msg_data['content'] if msg_data['content'] else "*Message sans texte*"
            timestamp = msg_data['timestamp'].strftime("%H:%M:%S")
            
            # Truncate long messages
            if len(content) > 1000:
                content = content[:997] + "..."
            
            field_name = f"#{i} - {author.display_name} ({timestamp})"
            field_value = content
            
            # Add attachment info if present
            if msg_data['attachments']:
                field_value += f"\n📎 {len(msg_data['attachments'])} pièce(s) jointe(s)"
            if msg_data['embeds'] > 0:
                field_value += f"\n📊 {msg_data['embeds']} embed(s)"
            
            embed.add_field(
                name=field_name,
                value=field_value,
                inline=False
            )
        
        embed.set_footer(text=f"Canal: #{interaction.channel.name}")
        
        await interaction.response.send_message(embed=embed)

    @commands.slash_command(name="snipeclear", description="Effacer l'historique des messages supprimés pour ce salon")
    @check_premium_tier()
    async def snipeclear(self, interaction: disnake.ApplicationCommandInteraction):
        """Clear the deleted messages history for the current channel"""
        channel_id = interaction.channel.id
        
        if channel_id in self.deleted_messages:
            self.deleted_messages[channel_id].clear()
            await interaction.response.send_message(
                "✅ Historique des messages supprimés effacé pour ce salon.",
                ephemeral=True
            )
        else:
            await interaction.response.send_message(
                "❌ Aucun historique à effacer pour ce salon.",
                ephemeral=True
            )

def setup(bot):
    bot.add_cog(SnipeCommands(bot))
