import discord
from discord import app_commands


class VCCommands(app_commands.Group):
    def __init__(self, manager):
        super().__init__(
            name="vc",
            description="Voice channel system"
        )
        self.manager = manager

    # ───────────────── SETUP ─────────────────

    @app_commands.command(
        name="setup",
        description="Create join-to-create voice channel"
    )
    @app_commands.checks.has_permissions(administrator=True)
    async def setup(self, interaction: discord.Interaction):
        guild = interaction.guild

        # Create or reuse category
        category = discord.utils.get(
            guild.categories,
            name=self.manager.category_name
        )
        if not category:
            category = await guild.create_category(
                self.manager.category_name
            )

        # Create trigger VC if not exists
        existing = discord.utils.get(
            category.voice_channels,
            name=self.manager.join_name
        )
        if not existing:
            await guild.create_voice_channel(
                name=self.manager.join_name,
                category=category
            )

        await interaction.response.send_message(
            "✅ Voice system setup complete.",
            ephemeral=True
        )

    # ───────────────── ERROR HANDLING ─────────────────

    @setup.error
    async def setup_error(
        self,
        interaction: discord.Interaction,
        error: app_commands.AppCommandError
    ):
        if isinstance(error, app_commands.errors.MissingPermissions):
            await interaction.response.send_message(
                "❌ You must have **Administrator** permission to run this command.",
                ephemeral=True
            )
        else:
            # Never leak tracebacks to users
            await interaction.response.send_message(
                "❌ An unexpected error occurred while running this command.",
                ephemeral=True
            )