import discord
from discord import app_commands
from disnake.ext import commands
import json
import os

# --------- Config ---------
BLACKLIST_FILE = "data/blacklist.json"
AGENTS_FILE = "data/agents.json"
TICKETS_FILE = "data/tickets_blacklist.json"
MAIN_GUILD_ID = 1369669999345537145  # ID du serveur principal

# --------- Utils JSON ---------
def load_json(path, default):
    if not os.path.exists(path):
        with open(path, "w") as f:
            json.dump(default, f, indent=4)
    with open(path, "r") as f:
        return json.load(f)

def save_json(path, data):
    with open(path, "w") as f:
        json.dump(data, f, indent=4)

# Initialisation fichiers
blacklist = load_json(BLACKLIST_FILE, {})
tickets = load_json(TICKETS_FILE, {})

# --------- Cog ---------
class Blacklist(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    def is_agent(self, user_id: int):
        agents = load_json(AGENTS_FILE, {"agents": []})
        return str(user_id) in agents["agents"]

    # ---------- Slash Commands ----------
    @app_commands.command(name="blacklist", description="Blacklist un utilisateur")
    @app_commands.describe(user="Utilisateur à blacklister", reason="Raison")
    async def blacklist_slash(self, interaction: disnake.Interaction, user: disnake.User, reason: str = "Aucune raison fournie"):
        if not self.is_agent(interaction.user.id):
            return await interaction.response.send_message("⛔ Tu n’as pas la permission.", ephemeral=True)

        blacklist[str(user.id)] = {"reason": reason}
        save_json(BLACKLIST_FILE, blacklist)

        try:
            view = TicketButton(user.id)
            await user.send(f"🚫 Tu as été blacklisté.\n**Raison :** {reason}", view=view)
        except:
            return await interaction.response.send_message("Impossible d’envoyer un MP à l’utilisateur.", ephemeral=True)

        await interaction.response.send_message(f"✅ {user.mention} a été ajouté à la blacklist.", ephemeral=True)

    @app_commands.command(name="unblacklist", description="Retire un utilisateur de la blacklist")
    @app_commands.describe(user="Utilisateur à retirer")
    async def unblacklist_slash(self, interaction: disnake.Interaction, user: disnake.User):
        if not self.is_agent(interaction.user.id):
            return await interaction.response.send_message("⛔ Tu n’as pas la permission.", ephemeral=True)

        if str(user.id) in blacklist:
            del blacklist[str(user.id)]
            save_json(BLACKLIST_FILE, blacklist)
            await interaction.response.send_message(f"✅ {user.mention} a été retiré de la blacklist.", ephemeral=True)
        else:
            await interaction.response.send_message("❌ Cet utilisateur n’est pas blacklisté.", ephemeral=True)

    # ---------- Listener pour nouveau MP ou notification ----------
    @commands.Cog.listener()
    async def on_member_join(self, member):
        if str(member.id) in blacklist:
            try:
                view = TicketButton(member.id)
                await member.send(
                    "🚫 Tu es blacklisté de ce serveur affilié. "
                    "Tu peux demander plus d’informations via le serveur principal.",
                    view=view
                )
            except:
                pass

# --------- Boutons ----------
class TicketButton(disnake.ui.View):
    def __init__(self, user_id: int):
        super().__init__(timeout=None)
        self.user_id = user_id

    @disnake.ui.button(label="📩 Ouvrir une demande de déblacklist", style=disnake.ButtonStyle.danger)
    async def open_ticket(self, button: disnake.ui.Button, interaction: disnake.Interaction):
        if interaction.user.id != self.user_id:
            return await interaction.response.send_message("❌ Ce bouton ne t’appartient pas.", ephemeral=True)

        if str(self.user_id) in tickets:
            return await interaction.response.send_message("❌ Tu as déjà ouvert une demande.", ephemeral=True)

        # Création du ticket (en MP avec le bot)
        channel = await interaction.user.create_dm()

        # Sauvegarde
        tickets[str(self.user_id)] = {"dm_channel_id": channel.id}
        save_json(TICKETS_FILE, tickets)

        view = CloseTicketView(self.user_id)
        await channel.send(
            f"📩 Ticket ouvert par {interaction.user.mention}\n"
            "Un agent Omega Kube va bientôt te répondre.",
            view=view
        )

        await interaction.response.send_message("✅ Ton ticket a été créé en MP avec le bot.", ephemeral=True)

class CloseTicketView(disnake.ui.View):
    def __init__(self, user_id: int):
        super().__init__(timeout=None)
        self.user_id = user_id

    @disnake.ui.button(label="❌ Fermer le ticket", style=disnake.ButtonStyle.danger)
    async def close_ticket(self, button: disnake.ui.Button, interaction: disnake.Interaction):
        agents = load_json(AGENTS_FILE, {"agents": []})
        if str(interaction.user.id) not in agents["agents"]:
            return await interaction.response.send_message("⛔ Seuls les agents Omega Kube peuvent fermer un ticket.", ephemeral=True)

        view = ConfirmCloseView(self.user_id)
        await interaction.response.send_message("⚠️ Veux-tu vraiment fermer ce ticket ?", view=view, ephemeral=True)

class ConfirmCloseView(disnake.ui.View):
    def __init__(self, user_id: int):
        super().__init__(timeout=30)
        self.user_id = user_id

    @disnake.ui.button(label="✅ Oui", style=disnake.ButtonStyle.success)
    async def confirm(self, button: disnake.ui.Button, interaction: disnake.Interaction):
        agents = load_json(AGENTS_FILE, {"agents": []})
        if str(interaction.user.id) not in agents["agents"]:
            return await interaction.response.send_message("⛔ Tu n’as pas la permission.", ephemeral=True)

        if str(self.user_id) in tickets:
            del tickets[str(self.user_id)]
            save_json(TICKETS_FILE, tickets)

        await interaction.channel.send("✅ Ticket fermé.")
        await interaction.channel.delete()

    @disnake.ui.button(label="❌ Non", style=disnake.ButtonStyle.secondary)
    async def cancel(self, button: disnake.ui.Button, interaction: disnake.Interaction):
        await interaction.response.send_message("❌ Fermeture annulée.", ephemeral=True)

# --------- Setup Cog ----------
def setup(bot: commands.Bot):
    cog = Blacklist(bot)
    await bot.add_cog(cog)
    await bot.tree.sync(guild=disnake.Object(id=MAIN_GUILD_ID))
