import discord
from discord.ext import commands
from discord.ui import Button, View
import json
import os
import asyncio

def load_config(filename):
    if not os.path.exists(filename):
        return {}   
    with open(filename, "r") as f:
        return json.load(f)

class VerifyButton(Button):
    def __init__(self, label="Verify"):
        super().__init__(
            style=discord.ButtonStyle.green,
            label=label,
            custom_id="verify_button"
        )
    
    async def callback(self, interaction):
        role = discord.utils.get(interaction.guild.roles, name="Verified")
        if role:
            await interaction.user.add_roles(role)
            await interaction.response.send_message(
                "✅ Úspěšně ověřeno!",
                ephemeral=True
            )
        else:
            await interaction.response.send_message(
                "❌ Role 'Verified' neexistuje!",
                ephemeral=True
            )

async def send_verify_embed(bot):
    config = load_config("verify_config.json")
    
    # Kontrola, zda konfigurace existuje
    if not config or not config.get("verify_channel_id"):
        print("❌ Verify konfigurace není nastavena!")
        return
        
    channel_id = config.get("verify_channel_id")
    if not channel_id:
        print("❌ verify_channel_id není nastaveno!")
        return
        
    channel = bot.get_channel(int(channel_id))
    if not channel:
        print(f"❌ Kanál s ID {channel_id} nebyl nalezen!")
        return
        
    await channel.purge(limit=5)
    view = View(timeout=None)
    view.add_item(VerifyButton(label=config.get("button_label", "Verify")))
    
    embed_config = config.get("verify_embed", {})
    title = embed_config.get("title", "✅ Ověření účtu")
    description = embed_config.get("description", "Klikni na tlačítko níže pro ověření!")
    color = embed_config.get("color", 5763719)
    
    embed = discord.Embed(title=title, description=description, color=color)
    await channel.send(embed=embed, view=view)
    print("✅ Verify embed odeslán!")

class Verify(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        # Registrace persistentního tlačítka
        persistent_view = View(timeout=None)
        persistent_view.add_item(VerifyButton())
        self.bot.add_view(persistent_view)
        
        # Odeslání verify embedu
        await send_verify_embed(self.bot)
        
        # Spuštění sledování signálu
        self.bot.loop.create_task(self.watch_verify_signal())

    async def watch_verify_signal(self):
        while True:
            await asyncio.sleep(5)
            if os.path.exists("verify_update.signal"):
                await send_verify_embed(self.bot)
                os.remove("verify_update.signal")

    @commands.command()
    @commands.has_permissions(administrator=True)
    async def update_verify(self, ctx):
        """Manuální aktualizace verify embedu"""
        await send_verify_embed(self.bot)
        await ctx.send("✅ Verify systém aktualizován!")

async def setup(bot):
    await bot.add_cog(Verify(bot))