﻿"""
ggbro Welcome Bot
Greets new members when they join a server and provides useful info.

Requirements:
    pip install python-socketio[client] requests

Commands:
    /setwelcome <channel_id>  - Set the welcome channel for this server
    /welcome                  - Preview the welcome message
    /serverinfo               - Show server stats
"""

import logging
import os
from ggbro import Bot, SlashCommand

logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(name)s] %(message)s')

# â”€â”€ Configuration â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
BOT_TOKEN = 'YOUR_BOT_TOKEN'
PUBLIC_API_URL = os.getenv('GGBRO_PUBLIC_URL', 'https://ggbro.app')
GATEWAY_URL = os.getenv('GGBRO_GATEWAY_URL', PUBLIC_API_URL)

bot = Bot(token=BOT_TOKEN, api_url=PUBLIC_API_URL, gateway_url=GATEWAY_URL)

# Per-server welcome channel: server_id -> channel_id
welcome_channels: dict[str, str] = {}

# Default welcome channel ID (fallback if not set per-server)
DEFAULT_WELCOME_CHANNEL = ''

# â”€â”€ Register commands â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€

bot.register_commands([
    SlashCommand(name='setwelcome', description='Set the welcome channel for this server', options=[
        {'name': 'channel_id', 'description': 'The channel ID for welcome messages', 'required': True}
    ]),
    SlashCommand(name='welcome', description='Preview the welcome message'),
    SlashCommand(name='serverinfo', description='Show basic server information'),
])

# â”€â”€ Command handlers â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€

@bot.command('setwelcome')
def set_welcome(ctx):
    channel_id = str(ctx.get_option('channel_id', ctx.args) or '').strip()
    if not channel_id:
        ctx.reply('âŒ Please provide a channel ID!\nUsage: `/setwelcome <channel_id>`')
        return

    welcome_channels[ctx.server_id] = channel_id
    ctx.reply(f'âœ… Welcome channel has been set! New members will be greeted there.')


@bot.command('welcome')
def preview_welcome(ctx):
    username = ctx.user.get('username', 'Someone')
    ctx.reply(
        f'ðŸ‘‹ Welcome to the server, **{username}**! ðŸŽ‰\n'
        f'We\'re glad to have you here. Check out the channels and say hi!\n'
        f'Use `/serverinfo` to learn more about this server.'
    )


@bot.command('serverinfo')
def server_info(ctx):
    try:
        servers = bot.get_servers()
        server = next((s for s in servers if s.get('id') == ctx.server_id), None)
        if server:
            name = server.get('name', 'Unknown')
            member_count = server.get('member_count', '?')
            ctx.reply(
                f'ðŸ“Š **Server Info**\n'
                f'**Name:** {name}\n'
                f'**Members:** {member_count}\n'
                f'**Server ID:** `{ctx.server_id}`'
            )
        else:
            ctx.reply('âŒ Could not retrieve server information.')
    except Exception as e:
        logging.error('serverinfo error: %s', e)
        ctx.reply('âŒ Failed to fetch server info.')


# â”€â”€ Events â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€

@bot.event('member:joined')
def on_member_join(data):
    server_id = data.get('serverId', '')
    username = data.get('username', 'Someone')

    # Find the welcome channel for this server
    channel_id = welcome_channels.get(server_id, DEFAULT_WELCOME_CHANNEL)
    if not channel_id:
        # Try to use the first text channel in the server
        try:
            channels = bot.get_channels(server_id)
            text_channels = [c for c in channels if c.get('type', 'text') == 'text']
            if text_channels:
                channel_id = text_channels[0]['id']
        except Exception:
            return

    if channel_id:
        bot.send_message(channel_id,
            f'ðŸ‘‹ Welcome to the server, **{username}**! ðŸŽ‰\n'
            f'We\'re glad to have you here. Check out the channels and say hi!'
        )


@bot.event('ready')
def on_ready():
    print('âœ… Welcome Bot is online!')


# â”€â”€ Start â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€

if __name__ == '__main__':
    bot.run()
