# remottxrea/bot/main_bot.py

import asyncio
from pyrogram import Client
from pyrogram.types import Message

from config import main_config
from bot.command_router import CommandRouter


router = CommandRouter()


def create_app() -> Client:
    """
    Create Pyrogram Client after config is injected.
    """

    if not main_config.BOT_TOKEN:
        raise ValueError("BOT_TOKEN is not set")

    if not main_config.API_ID:
        raise ValueError("API_ID is not set")

    if not main_config.API_HASH:
        raise ValueError("API_HASH is not set")
    
    return Client(
        name="remottxrea_bot",
        bot_token=main_config.BOT_TOKEN,
        api_id=main_config.API_ID,
        api_hash=main_config.API_HASH
    )


async def startup():
    await router.registry.runner.load_all()
    await router.registry.runner.start_watcher()
    print("🚀 Realtime session watcher enabled")


def run():
    """
    Entry point for external execution (bot.py)
    """

    app = create_app()

    @app.on_message()
    async def on_message(client: Client, message: Message):
        await router.dispatch(client, message)

    app.loop.run_until_complete(startup())
    app.run()


if __name__ == "__main__":
    run()