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")

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

def get_log_channel(guild, settings):
    channel_id = settings.get("log_channel_id")
    if channel_id:
        return guild.get_channel(int(channel_id))
    return None

def load_settings():
    if not os.path.exists(SETTINGS_FILE):
        return {}
    try:
        with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        return {}

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

    @commands.Cog.listener()
    async def on_message_delete(self, message):
        if message.author.bot: return
        settings = dict(load_settings()).get(str(message.guild.id), {})
        
        log_chan = get_log_channel(message.guild, settings)
        if log_chan:
            embed = disnake.Embed(
                title="🗑️ Message Supprimé",
                description=f"**Auteur :** {message.author.mention}\n**Salon :** {message.channel.mention}",
                color=0xFFA500,
                timestamp=disnake.utils.utcnow()
            )
            embed.add_field(name="Contenu", value=message.content or "*(Image ou Embed)*")
            await log_chan.send(embed=embed)

    @commands.Cog.listener()
    async def on_member_remove(self, member):
        settings = dict(load_settings()).get(str(member.guild.id), {})
        log_chan = get_log_channel(member.guild, settings)
        if log_chan:
            embed = disnake.Embed(
                title="📤 Départ d'un membre",
                description=f"{member.mention} ({member.id}) a quitté le serveur.",
                color=0xFF0000,
                timestamp=disnake.utils.utcnow()
            )
            await log_chan.send(embed=embed)

    @commands.Cog.listener()
    async def on_member_ban(self, guild, user):
        settings = dict(load_settings()).get(str(guild.id), {})
        log_chan = get_log_channel(guild, settings)
        if log_chan:
            embed = disnake.Embed(
                title="🔨 Bannissement",
                description=f"**Utilisateur :** {user.mention} ({user.id}) a été banni.",
                color=0x000000,
                timestamp=disnake.utils.utcnow()
            )
            await log_chan.send(embed=embed)

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