import disnake
from disnake.ext import commands
import json
import os
from datetime import datetime

# Chemins ABSOLUS
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(BASE_DIR, "..", "..", "data")
SETTINGS_FILE = os.path.join(DATA_DIR, "security_settings.json")
WHITELIST_FILE = os.path.join(DATA_DIR, "whitelist.json")

# Créer le dossier data/ s'il n'existe pas
os.makedirs(DATA_DIR, exist_ok=True)

def is_whitelisted(guild_id, user_id):
    if not os.path.exists(WHITELIST_FILE): return False
    try:
        with open(WHITELIST_FILE, "r", encoding='utf-8') as f:
            data = json.load(f)
            return user_id in data.get(str(guild_id), [])
    except: return False

class AntiRaid(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.join_cache = {} 

    @commands.Cog.listener()
    async def on_member_join(self, member):
        if member.bot: return
        
        # 1. WHITELIST
        if is_whitelisted(member.guild.id, member.id): return

        # 2. LECTURE DYNAMIQUE
        if not os.path.exists(SETTINGS_FILE): return
        with open(SETTINGS_FILE, "r", encoding='utf-8') as f:
            settings = json.load(f).get(str(member.guild.id), {})

        if not settings.get("anti_raid"): return

        guild_id = member.guild.id
        now = datetime.now()

        if guild_id not in self.join_cache: self.join_cache[guild_id] = []
        self.join_cache[guild_id].append(now)
        self.join_cache[guild_id] = [t for t in self.join_cache[guild_id] if (now - t).seconds < 10]

        if len(self.join_cache[guild_id]) > settings.get("raid_threshold", 3):
            await self.handle_raid(member.guild, settings)

    async def handle_raid(self, guild, settings):
        if settings.get("auto_ban"):
            # Logique d'auto-ban des derniers membres ici
            pass
            
        log_channel_id = settings.get("log_channel_id")
        if log_channel_id:
            channel = guild.get_channel(int(log_channel_id))
            if channel:
                embed = disnake.Embed(title="🚨 ALERTE RAID", description=f"Vague de {len(self.join_cache[guild.id])} membres !", color=0xFF0000)
                await channel.send(embed=embed)

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