import disnake
from disnake.ext import commands
from datetime import datetime

from commandes.ticket.data.storage import get_storage
from commandes.ticket.staff_analytics import StaffAnalytics
from utils.premium import check_premium_tier


class StaffLeaderboard(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command(name="staff-leaderboard", description="Affiche le classement du staff")
    @check_premium_tier()
    async def staff_leaderboard(self, interaction: disnake.ApplicationCommandInteraction):
        """Commande pour afficher le classement du staff"""
        await interaction.response.defer(ephemeral=False)
        
        try:
            storage = get_storage()
            analytics = StaffAnalytics(self.bot)
            
            # Get staff list
            staff_list = await analytics.get_staff_list(interaction.guild_id)
            
            if not staff_list:
                await interaction.followup.send("Aucun membre du staff n'a été trouvé.", ephemeral=True)
                return
            
            # Sort by average rating (descending)
            staff_list.sort(key=lambda x: x['average_rating'], reverse=True)
            
            # Create embed
            embed = disnake.Embed(
                title="🏆 Classement du Staff",
                description="Classement des meilleurs membres du staff",
                color=disnake.Color.gold(),
                timestamp=datetime.now()
            )
            
            # Add top 10 staff members
            top_staff = staff_list[:10]
            for i, staff in enumerate(top_staff, 1):
                rating = staff['average_rating']
                count = staff['total_ratings']
                name = staff['name']
                
                # Add emoji based on rating
                if rating >= 4.5:
                    emoji = "🥇"
                elif rating >= 4.0:
                    emoji = "🥈"
                elif rating >= 3.5:
                    emoji = "🥉"
                else:
                    emoji = "⭐"
                
                embed.add_field(
                    name=f"{emoji} #{i} {name}",
                    value=f"Note: {rating:.1f}⭐ ({count} évaluations)",
                    inline=False
                )
            
            # Send embed
            await interaction.followup.send(embed=embed)
            
        except Exception as e:
            print(f"Error in staff_leaderboard command: {e}")
            await interaction.followup.send("Une erreur est survenue lors de la génération du classement.", ephemeral=True)


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