import dotenv
from twitchio.ext import commands
import os
import redis

dotenv.load_dotenv()

redis_client = redis.Redis(host="localhost", port=6379, db=1)


class SongBot(commands.Bot):
    def __init__(self):
        # Get token from environment variable
        token = os.getenv("TWITCH_TOKEN")
        if not token:
            raise ValueError("TWITCH_TOKEN environment variable is not set")

        # Bot configuration
        super().__init__(
            token=token,
            prefix="!",
            initial_channels=["djsuno"],  # Channel to join
        )

    async def event_ready(self):
        """Called when the bot is ready"""
        print(f"Bot is ready! Logged in as {self.nick}")
        print(f"Connected to channels: {self.connected_channels}")

    async def event_message(self, message):
        """Called for every message in chat"""
        # Ignore messages from the bot itself
        if message.echo:
            return

        # Print all messages for debugging (optional)
        print(f"{message.author.name}: {message.content}")

        # Process commands
        await self.handle_commands(message)

    @commands.command(name="go")
    async def song_request(self, ctx, *, song_info=None):
        """Handle !go command to add songs to the list"""
        if not song_info:
            await ctx.send(f"@{ctx.author.name} Please provide a tag! Usage: !go tag")
            return

        redis_client.incr(f"{song_info}")
        value = int(redis_client.get(f"{song_info}"))
        print(f"@{ctx.author.name} {song_info} has been requested {value} times!")


# Run the bot
if __name__ == "__main__":
    # Create and run the bot
    bot = SongBot()
    bot.run()
