import os
import logging
import discord
from dotenv import load_dotenv
from commands import setup_commands

# Load environment variables
load_dotenv()

TOKEN = os.getenv("DISCORD_TOKEN")
GUILD_ID = os.getenv("GUILD_ID")

# Validate Guild ID
if GUILD_ID:
    try:
        GUILD_ID = int(GUILD_ID)
    except ValueError:
        logging.error("Invalid GUILD_ID in .env file. It must be a numeric value.")
        GUILD_ID = None

intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
intents.guilds = True
intents.voice_states = True


class AmberClient(discord.Client):
    def __init__(self):
        super().__init__(intents=intents)
        self.tree = discord.app_commands.CommandTree(self)

    async def on_ready(self):
        logging.info(f"Amber is online as {self.user}")

        # Sync commands after the bot is fully ready
        if GUILD_ID:
            logging.info(f"Setting up commands for guild: {GUILD_ID}")
        else:
            logging.info("Setting up global commands (no guild ID specified).")

        try:
            await setup_commands(self, guild_id=GUILD_ID)
        except Exception as e:
            logging.error(f"Failed to setup commands: {e}")


logging.basicConfig(level=logging.INFO)
client = AmberClient()

if TOKEN:
    client.run(TOKEN)
else:
    logging.error("Bot token not found. Check your .env file.")