# froscord/voice/core.py
import discord
from discord.ext import commands

from .commands import VCCommands
from .panel import VoiceControl, voice_embed
from .state import TEMP_VC, TEMP_MUTED


class VoiceSystem(commands.Cog):
    def __init__(
        self,
        bot: commands.Bot,
        join_to_create_name: str,
        category_name: str,
        user_limit: int = 0,
        send_panel: bool = True,
    ):
        self.bot = bot
        self.join_name = join_to_create_name
        self.category_name = category_name
        self.user_limit = user_limit
        self.send_panel = send_panel

        # register slash commands
        self.bot.tree.add_command(VCCommands(self))

    # ───────────────── SAFE REGISTRATION ─────────────────

    async def add_to_bot(self):
        await self.bot.add_cog(self)

    # ───────────────── VOICE EVENT ─────────────────

    @commands.Cog.listener()
    async def on_voice_state_update(self, member, before, after):
        guild = member.guild

        # ───── AUTO UNMUTE (SAFE) ─────
        if (
            before.channel
            and before.channel.id in TEMP_MUTED
            and member.voice is not None
        ):
            muted = TEMP_MUTED[before.channel.id]
            if member.id in muted and after.channel != before.channel:
                try:
                    await member.edit(mute=False)
                except discord.HTTPException:
                    pass

                muted.discard(member.id)
                if not muted:
                    TEMP_MUTED.pop(before.channel.id, None)

        # ───── JOIN → CREATE ─────
        if after.channel and after.channel.name == self.join_name:
        # 🚫 BLOCK duplicate VC creation
            if any(data["owner"] == member.id for data in TEMP_VC.values()):
                return

            category = discord.utils.get(
                guild.categories, name=self.category_name
            )
            if not category:
                category = await guild.create_category(self.category_name)

            base = f"🔊 {member.display_name}'s VC"
            name = base
            count = 1
            while discord.utils.get(category.voice_channels, name=name):
                count += 1
                name = f"{base} #{count}"

            vc = await guild.create_voice_channel(
                name=name,
                category=category,
                user_limit=self.user_limit,
            )

            await member.move_to(vc)

            TEMP_VC[vc.id] = {"owner": member.id, "message": None}

            if self.send_panel:
                msg = await vc.send(
                    embed=voice_embed(vc, member),
                    view=VoiceControl(vc.id),
                )
                TEMP_VC[vc.id]["message"] = msg.id

        # ───── CLEANUP EMPTY VC ─────
        if before.channel and before.channel.id in TEMP_VC:
            if not before.channel.members:
                try:
                    await before.channel.delete()
                except discord.NotFound:
                    pass

                TEMP_VC.pop(before.channel.id, None)
                TEMP_MUTED.pop(before.channel.id, None)