import discord
from discord.ext import commands
import asyncio
import time
from collections import defaultdict, deque
import json
import os

class ModerationSystem(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.message_cache = defaultdict(lambda: deque(maxlen=10))  # Posledních 10 zpráv na uživatele
        self.join_cache = deque(maxlen=50)  # Posledních 50 připojení
        self.muted_users = {}  # Uložení mutovaných uživatelů
        
        # Nastavení (později přes config)
        self.spam_threshold = 5  # 5 zpráv
        self.spam_time_window = 10  # za 10 sekund
        self.raid_threshold = 5  # 5 uživatelů
        self.raid_time_window = 30  # za 30 sekund
        self.mute_duration = 600  # 10 minut v sekundách

    def load_config(self):
        """Načtení konfigurace moderace"""
        if os.path.exists("moderation_config.json"):
            with open("moderation_config.json", "r") as f:
                config = json.load(f)
                self.spam_threshold = config.get("spam_threshold", 5)
                self.spam_time_window = config.get("spam_time_window", 10)
                self.raid_threshold = config.get("raid_threshold", 5)
                self.raid_time_window = config.get("raid_time_window", 30)
                self.mute_duration = config.get("mute_duration", 600)

    @commands.Cog.listener()
    async def on_ready(self):
        self.load_config()
        print("🛡️ Moderační systém načten!")

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot:
            return
            
        # Anti-spam kontrola
        await self.check_spam(message)

    @commands.Cog.listener()
    async def on_member_join(self, member):
        # Anti-raid kontrola
        await self.check_raid(member)

    async def check_spam(self, message):
        """Kontrola spamu"""
        user_id = message.author.id
        current_time = time.time()
        
        # Přidej zprávu do cache
        self.message_cache[user_id].append({
            'timestamp': current_time,
            'content': message.content.lower(),
            'channel': message.channel.id
        })
        
        recent_messages = [
            msg for msg in self.message_cache[user_id]
            if current_time - msg['timestamp'] <= self.spam_time_window
        ]
        
        # Kontrola počtu zpráv
        if len(recent_messages) >= self.spam_threshold:
            # Kontrola duplicitních zpráv
            contents = [msg['content'] for msg in recent_messages]
            if len(set(contents)) <= 2:  # Max 2 různé zprávy = spam
                await self.handle_spam(message.author, message.guild)
                return

    async def check_raid(self, member):
        """Kontrola raidu"""
        current_time = time.time()
        
        # Přidej připojení do cache
        self.join_cache.append({
            'timestamp': current_time,
            'user_id': member.id
        })
        
        # Kontrola počtu připojení za časové okno
        recent_joins = [
            join for join in self.join_cache
            if current_time - join['timestamp'] <= self.raid_time_window
        ]
        
        if len(recent_joins) >= self.raid_threshold:
            await self.handle_raid(member.guild)

    async def handle_spam(self, user, guild):
        """Zpracování spamu - mute"""
        try:
            # Najdi nebo vytvoř Muted roli
            muted_role = discord.utils.get(guild.roles, name="Muted")
            if not muted_role:
                muted_role = await self.create_muted_role(guild)
            
            # Mute uživatele
            await user.add_roles(muted_role, reason="Anti-spam: Automatický mute")
            
            # Uložení do cache pro automatické unmute
            self.muted_users[user.id] = time.time() + self.mute_duration
            
            # Odeslání zprávy
            embed = discord.Embed(
                title="🔇 Automatický Mute",
                description=f"{user.mention} byl ztišen na 10 minut za spam.",
                color=0xff9900
            )
            
            # Najdi moderátorský kanál nebo použij systémový
            mod_channel = discord.utils.get(guild.channels, name="mod-log")
            if mod_channel:
                await mod_channel.send(embed=embed)
            
            print(f"🔇 {user.name} mutován za spam")
            
            # Naplánuj automatické unmute
            asyncio.create_task(self.auto_unmute(user, guild, self.mute_duration))
            
        except Exception as e:
            print(f"Chyba při mutování: {e}")

    async def handle_raid(self, guild):
        """Zpracování raidu - lockdown"""
        try:
            # Uzamkni všechny textové kanály
            locked_channels = []
            for channel in guild.text_channels:
                if channel.name not in ["mod-log", "admin"]:  # Vynech moderátorské kanály
                    overwrite = channel.overwrites_for(guild.default_role)
                    overwrite.send_messages = False
                    await channel.set_permissions(guild.default_role, overwrite=overwrite)
                    locked_channels.append(channel.name)
            
            # Oznámení
            embed = discord.Embed(
                title="🚨 RAID DETEKOVÁN",
                description=f"Server byl automaticky uzamčen!\n\n**Uzamčené kanály:** {len(locked_channels)}\n**Čas:** <t:{int(time.time())}:F>",
                color=0xff0000
            )
            embed.add_field(
                name="ℹ️ Info",
                value="Pro odemčení použij `!unlock`",
                inline=False
            )
            
            # Pošli do mod kanálu
            mod_channel = discord.utils.get(guild.channels, name="mod-log")
            if mod_channel:
                await mod_channel.send("@here", embed=embed)
            
            print(f"🚨 Server {guild.name} uzamčen - raid detekován")
            
        except Exception as e:
            print(f"Chyba při lockdownu: {e}")

    async def create_muted_role(self, guild):
        """Vytvoření Muted role"""
        muted_role = await guild.create_role(
            name="Muted",
            color=discord.Color.gray(),
            reason="Automatické vytvoření pro moderaci"
        )
        
        # Nastavení permissions pro všechny kanály
        for channel in guild.channels:
            await channel.set_permissions(muted_role, send_messages=False, speak=False)
        
        return muted_role

    async def auto_unmute(self, user, guild, duration):
        """Automatické unmute po určité době"""
        await asyncio.sleep(duration)
        
        try:
            muted_role = discord.utils.get(guild.roles, name="Muted")
            if muted_role and muted_role in user.roles:
                await user.remove_roles(muted_role, reason="Automatické unmute")
                
                # Odstraň z cache
                if user.id in self.muted_users:
                    del self.muted_users[user.id]
                
                print(f"🔊 {user.name} automaticky unmutován")
                
        except Exception as e:
            print(f"Chyba při unmutování: {e}")

    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def unlock(self, ctx):
        """Odemknutí serveru po raidu"""
        try:
            unlocked_channels = []
            for channel in ctx.guild.text_channels:
                overwrite = channel.overwrites_for(ctx.guild.default_role)
                overwrite.send_messages = None  # Reset na default
                await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
                unlocked_channels.append(channel.name)
            
            embed = discord.Embed(
                title="🔓 Server Odemčen",
                description=f"Server byl úspěšně odemčen!\n\n**Odemčené kanály:** {len(unlocked_channels)}",
                color=0x00ff00
            )
            await ctx.send(embed=embed)
            
        except Exception as e:
            await ctx.send(f"❌ Chyba při odemykání: {e}")

    @commands.command()
    @commands.has_permissions(moderate_members=True)
    async def mute(self, ctx, member: discord.Member, duration: int = 10, *, reason="Není specifikován"):
        """Manuální mute uživatele"""
        try:
            muted_role = discord.utils.get(ctx.guild.roles, name="Muted")
            if not muted_role:
                muted_role = await self.create_muted_role(ctx.guild)
            
            await member.add_roles(muted_role, reason=f"Mute od {ctx.author}: {reason}")
            
            # Uložení do cache
            self.muted_users[member.id] = time.time() + (duration * 60)
            
            embed = discord.Embed(
                title="🔇 Uživatel Mutován",
                description=f"{member.mention} byl mutován na {duration} minut.",
                color=0xff9900
            )
            embed.add_field(name="Důvod", value=reason, inline=False)
            embed.add_field(name="Moderátor", value=ctx.author.mention, inline=True)
            
            await ctx.send(embed=embed)
            
            # Automatické unmute
            asyncio.create_task(self.auto_unmute(member, ctx.guild, duration * 60))
            
        except Exception as e:
            await ctx.send(f"❌ Chyba při mutování: {e}")

    @commands.command()
    @commands.has_permissions(moderate_members=True)
    async def unmute(self, ctx, member: discord.Member):
        """Manuální unmute uživatele"""
        try:
            muted_role = discord.utils.get(ctx.guild.roles, name="Muted")
            if muted_role and muted_role in member.roles:
                await member.remove_roles(muted_role, reason=f"Unmute od {ctx.author}")
                
                if member.id in self.muted_users:
                    del self.muted_users[member.id]
                
                embed = discord.Embed(
                    title="🔊 Uživatel Unmutován",
                    description=f"{member.mention} byl unmutován.",
                    color=0x00ff00
                )
                await ctx.send(embed=embed)
            else:
                await ctx.send("❌ Uživatel není mutován.")
                
        except Exception as e:
            await ctx.send(f"❌ Chyba při unmutování: {e}")

    @commands.command()
    @commands.has_permissions(kick_members=True)
    async def kick(self, ctx, member: discord.Member, *, reason="Není specifikován"):
        """Vykopnutí uživatele"""
        try:
            await member.kick(reason=f"Kick od {ctx.author}: {reason}")
            
            embed = discord.Embed(
                title="👢 Uživatel Vykopnut",
                description=f"{member.mention} byl vykopnut ze serveru.",
                color=0xff6600
            )
            embed.add_field(name="Důvod", value=reason, inline=False)
            embed.add_field(name="Moderátor", value=ctx.author.mention, inline=True)
            
            await ctx.send(embed=embed)
            
        except Exception as e:
            await ctx.send(f"❌ Chyba při kopání: {e}")

    @commands.command()
    @commands.has_permissions(ban_members=True)
    async def ban(self, ctx, member: discord.Member, *, reason="Není specifikován"):
        """Zabanování uživatele"""
        try:
            await member.ban(reason=f"Ban od {ctx.author}: {reason}")
            
            embed = discord.Embed(
                title="🔨 Uživatel Zabanován",
                description=f"{member.mention} byl trvale zabanován.",
                color=0xff0000
            )
            embed.add_field(name="Důvod", value=reason, inline=False)
            embed.add_field(name="Moderátor", value=ctx.author.mention, inline=True)
            
            await ctx.send(embed=embed)
            
        except Exception as e:
            await ctx.send(f"❌ Chyba při banování: {e}")

    @commands.command()
    @commands.has_permissions(ban_members=True)
    async def unban(self, ctx, user_id: int):
        """Odbanování uživatele podle ID"""
        try:
            user = await self.bot.fetch_user(user_id)
            await ctx.guild.unban(user, reason=f"Unban od {ctx.author}")
            
            embed = discord.Embed(
                title="✅ Uživatel Odbanován",
                description=f"{user.mention} byl odbanován.",
                color=0x00ff00
            )
            embed.add_field(name="Moderátor", value=ctx.author.mention, inline=True)
            
            await ctx.send(embed=embed)
            
        except Exception as e:
            await ctx.send(f"❌ Chyba při odbanování: {e}")

    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def clear(self, ctx, amount: int = 10):
        """Smazání zpráv"""
        try:
            if amount > 100:
                await ctx.send("❌ Můžeš smazat max 100 zpráv najednou!")
                return
                
            deleted = await ctx.channel.purge(limit=amount + 1)  # +1 pro command zprávu
            
            embed = discord.Embed(
                title="🗑️ Zprávy Smazány",
                description=f"Smazáno {len(deleted)-1} zpráv.",
                color=0x00ff00
            )
            embed.add_field(name="Moderátor", value=ctx.author.mention, inline=True)
            
            msg = await ctx.send(embed=embed)
            await asyncio.sleep(3)
            await msg.delete()
            
        except Exception as e:
            await ctx.send(f"❌ Chyba při mazání: {e}")

    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def warn(self, ctx, member: discord.Member, *, reason="Není specifikován"):
        """Varování uživatele"""
        try:
            # Uložení varování (můžeš rozšířit o databázi)
            embed = discord.Embed(
                title="⚠️ Varování",
                description=f"{member.mention} obdržel varování.",
                color=0xffff00
            )
            embed.add_field(name="Důvod", value=reason, inline=False)
            embed.add_field(name="Moderátor", value=ctx.author.mention, inline=True)
            
            await ctx.send(embed=embed)
            
            # Pošli DM uživateli
            try:
                dm_embed = discord.Embed(
                    title="⚠️ Varování",
                    description=f"Obdržel jsi varování na serveru **{ctx.guild.name}**",
                    color=0xffff00
                )
                dm_embed.add_field(name="Důvod", value=reason, inline=False)
                await member.send(embed=dm_embed)
            except:
                await ctx.send("⚠️ Nepodařilo se poslat DM uživateli.")
                
        except Exception as e:
            await ctx.send(f"❌ Chyba při varování: {e}")

    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def modstats(self, ctx):
        """Statistiky moderace"""
        embed = discord.Embed(
            title="📊 Moderační Statistiky",
            color=0x5865F2
        )
        
        embed.add_field(
            name="🔇 Mutovaní uživatelé",
            value=str(len(self.muted_users)),
            inline=True
        )
        
        embed.add_field(
            name="📝 Sledované zprávy",
            value=str(len(self.message_cache)),
            inline=True
        )
        
        embed.add_field(
            name="⚙️ Nastavení",
            value=f"Spam: {self.spam_threshold} zpráv/{self.spam_time_window}s\nRaid: {self.raid_threshold} joins/{self.raid_time_window}s",
            inline=False
        )
        
        embed.set_footer(
            text=f"BuzzHost Moderace | Prefix: {current_prefix}",
            icon_url=ctx.bot.user.avatar.url if ctx.bot.user.avatar else None
        )
        
        await ctx.send(embed=embed)
        
async def setup(bot):
    await bot.add_cog(ModerationSystem(bot))