import discord
from discord.ext import commands
import os
import logging
from dotenv import load_dotenv

import config
from database import db
from web_server import WebServer

# Initialize logger
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("gamble_bot.main")

# Setup Discord intents
intents = discord.Intents.default()
intents.message_content = True
intents.members = True

class GambleBot(commands.Bot):
    def __init__(self):
        super().__init__(
            command_prefix="g!",
            intents=intents,
            help_command=None
        )
        self.web_server = WebServer(self)

    async def setup_hook(self):
        # 1. Connect to Database and Initialize Schema
        await db.connect()
        await db.initialize_schema()

        # Start the WebSocket server bridge
        await self.web_server.start()

        # 2. Load Cogs
        cogs_to_load = [
            "cogs.admin",
            "cogs.economy",
            "cogs.games",
            "cogs.tickets",
            "cogs.events"
        ]
        
        for cog in cogs_to_load:
            try:
                await self.load_extension(cog)
                logger.info(f"Cog successfully loaded: {cog}")
            except Exception as e:
                logger.error(f"Failed to load cog {cog}: {e}", exc_info=True)

        # 3. Register Persistent Panel Views
        from cogs.admin import EconomyPanelView, AdminDashboardView
        self.add_view(EconomyPanelView())
        self.add_view(AdminDashboardView())
        from cogs.games import GambleLobbyView
        self.add_view(GambleLobbyView())
        from cogs.tickets import TicketCreateView, TicketControlView
        self.add_view(TicketCreateView())
        self.add_view(TicketControlView())
        logger.info("Persistent views registered.")

        # 4. Global Slash Command Security Check: Strictly ONLY Server Crown Owner can run ANY slash command!
        async def global_slash_command_check(interaction: discord.Interaction) -> bool:
            if interaction.type == discord.InteractionType.application_command:
                if interaction.guild and interaction.user.id == interaction.guild.owner_id:
                    return True
                await interaction.response.send_message(
                    "❌ **Erişim Reddedildi:** Bu sunucudaki tüm `/` slash komutları **sadece sunucu sahibine (Taç sahibine)** özeldir. Yöneticiler ve yetkililer dahil hiç kimse kullanamaz!",
                    ephemeral=True
                )
                return False
            return True

        self.tree.interaction_check = global_slash_command_check

        # 5. Re-register Dynamic Pending Admin Approval Buttons (Defense-in-depth recovery)
        try:
            from cogs.economy import AdminApprovalView
            # Fetch all pending withdrawals
            pending_query = "SELECT * FROM economy_transactions WHERE status = 'pending' AND type = 'withdraw'"
            pending_txs = await db.fetch(pending_query)
            
            for tx in pending_txs:
                self.add_view(AdminApprovalView(
                    tx_id=tx["id"],
                    user_id=tx["discord_id"],
                    username=tx["game_username"],
                    amount=float(tx["amount"])
                ))
            logger.info(f"Re-registered {len(pending_txs)} pending withdrawal approval views from database.")
        except Exception as e:
            logger.error(f"Error restoring pending approval views: {e}", exc_info=True)

    async def on_ready(self):
        logger.info(f"Bot connected as: {self.user.name} ({self.user.id})")
        
        # Sync slash commands globally and also instant sync to all current guilds
        try:
            # Sync globally
            synced = await self.tree.sync()
            logger.info(f"Successfully synced {len(synced)} application (slash) commands globally.")
            
            # Sync to each guild instantly for development/testing
            for guild in self.guilds:
                self.tree.copy_global_to(guild=guild)
                await self.tree.sync(guild=guild)
                logger.info(f"Instant synced slash commands to guild: {guild.name} ({guild.id})")
        except Exception as e:
            logger.error(f"Failed to sync slash commands: {e}")

        # Refresh live Minecraft bot status display card
        try:
            from web_server import update_bot_status_display, minecraft_ws
            await update_bot_status_display(
                self,
                is_online=(minecraft_ws is not None and not minecraft_ws.closed),
                username="KolicGambleBot",
                server_ip="kolichub.net"
            )
        except Exception as e:
            logger.debug(f"Initial status card update error: {e}")

    async def close(self):
        # Graceful shutdown: stop web server and disconnect DB
        try:
            await self.web_server.stop()
        except Exception as e:
            logger.error(f"Error stopping web server: {e}")
        await db.disconnect()
        await super().close()


def main():
    # Verify token
    token = config.DISCORD_TOKEN
    if not token or token == "YOUR_DISCORD_BOT_TOKEN_HERE":
        logger.critical("Error: DISCORD_TOKEN is not configured in .env file! Exiting...")
        return

    bot = GambleBot()
    
    # Run the bot
    try:
        bot.run(token)
    except Exception as e:
        logger.critical(f"Failed to start the bot: {e}")

if __name__ == "__main__":
    main()
