import discord
from discord import app_commands
from audio import (
    play_audio,
    stop_audio,
    set_volume,
    join_voice,
    leave_voice,
    pause_audio,
    resume_audio,
    repeat_modes,
    generate_recommendations
    )


async def setup_commands(client, guild_id=None):
    @client.tree.command(name="join", description="Join the user's current voice channel.")
    async def join(interaction: discord.Interaction):
        await join_voice(interaction)

    @client.tree.command(name="leave", description="Leave the current voice channel.")
    async def leave(interaction: discord.Interaction):
        await leave_voice(interaction)

    @client.tree.command(name="play", description="Play a song by title or artist.")
    async def play(interaction: discord.Interaction, query: str):
        await play_audio(interaction, query)

    @client.tree.command(name="stop", description="Stop playback and clear the queue.")
    async def stop(interaction: discord.Interaction):
        await stop_audio(interaction)

    @client.tree.command(name="pause", description="Pause the current song.")
    async def pause(interaction: discord.Interaction):
        await pause_audio(interaction)

    @client.tree.command(name="resume", description="Resume the paused song.")
    async def resume(interaction: discord.Interaction):
        await resume_audio(interaction)

    @client.tree.command(name="repeat", description="Set the repeat mode for playback.")
    @app_commands.describe(mode="Repeat mode: 'one', 'all', or 'off'")
    async def repeat(interaction: discord.Interaction, mode: str):
        guild_id = interaction.guild.id
        valid_modes = ["one", "all", "off"]

        if mode not in valid_modes:
            await interaction.response.send_message(f"❌ **Invalid mode. Use one of: {', '.join(valid_modes)}.**")
            return

        repeat_modes[guild_id] = mode
        await interaction.response.send_message(f"🔄 **Repeat mode set to:** {mode.capitalize()}.")

    @client.tree.command(name="volume", description="Set playback volume.")
    async def volume(interaction: discord.Interaction, level: int):
        await set_volume(interaction, level)

    @client.tree.command(name="recommend", description="Get song recommendations based on your listening history.")
    async def recommend(interaction: discord.Interaction):
        user_id = interaction.user.id
        recommendations = generate_recommendations(user_id)

        embed = discord.Embed(
            title="🎵 Recommended Songs",
            description="\n".join(recommendations),
            color=discord.Color.green()
        )
        await interaction.response.send_message(embed=embed)

    await client.tree.sync()