from modules.logging import logWrite
from modules.utils import configGet
from pyrogram.types import BotCommand, BotCommandScopeChat
from pyrogram.errors import bad_request_400

def commands_register(app):

    # Registering user commands
    commands_list = []
    for command in configGet("commands"):
        commands_list.append(BotCommand(command, configGet("commands")[command]))
    app.set_bot_commands(commands_list)

    # Registering admin commands
    commands_admin_list = []
    for command in configGet("commands"):
        commands_admin_list.append(BotCommand(command, configGet("commands")[command]))
        
    for command in configGet("commands_admin"):
        commands_admin_list.append(BotCommand(command, configGet("commands_admin")[command]))

    for admin in configGet("admins"):
        try:
            app.set_bot_commands(commands_admin_list, scope=BotCommandScopeChat(chat_id=admin))
        except bad_request_400.PeerIdInvalid:
            pass

    try:
        app.set_bot_commands(commands_admin_list, scope=BotCommandScopeChat(chat_id=configGet("owner")))
    except bad_request_400.PeerIdInvalid:
        logWrite(f"Could not register commands for bot owner. Perhaps user has not started the bot yet.")

    # Registering admin group commands
    commands_group_admin_list = []
    for command in configGet("commands_group_admin"):
        commands_group_admin_list.append(BotCommand(command, configGet("commands_group_admin")[command]))
    try:
        app.set_bot_commands(commands_group_admin_list, scope=BotCommandScopeChat(chat_id=configGet("admin_group")))
    except bad_request_400.ChannelInvalid:
        logWrite(f"Could not register commands for admin group. Bot is likely not in the group.")

    # Registering destination group commands
    commands_group_destination_list = []
    for command in configGet("commands_group_destination"):
        commands_group_destination_list.append(BotCommand(command, configGet("commands_group_destination")[command]))
    try:
        app.set_bot_commands(commands_group_destination_list, scope=BotCommandScopeChat(chat_id=configGet("destination_group")))
    except bad_request_400.ChannelInvalid:
        logWrite(f"Could not register commands for destination group. Bot is likely not in the group.")