"""Basic webhook bot example.

Start the server, then configure your pararam.io bot's webhook URL
to point to http://<your-host>:8080/<url_key>
where <url_key> is the first 8 characters of your bot secret.

Environment variables:
    BOT_SECRET - Full bot secret from pararam.io bot settings
"""

import asyncio
import logging
import os

from pararamio_bot import WebhookAction, WebhookMessage, WebhookServer, extract_url_key

logging.basicConfig(level=logging.INFO)


async def handle_message(message: WebhookMessage) -> None:
    print(
        f'[message] @{message.user_unique_name} in chat #{message.chat_id}: {message.text}'
    )
    if message.reply_no:
        print(f'  (reply to #{message.reply_no}: {message.reply_text})')
    if message.attachments:
        print(f'  attachments: {message.attachments}')


async def handle_action(action: WebhookAction) -> None:
    print(
        f'[action] user #{action.user_id} clicked "{action.action}" '
        f'with params={action.params}'
    )


async def main() -> None:
    bot_secret = os.environ['BOT_SECRET']
    url_key = extract_url_key(bot_secret)

    async with WebhookServer(bot_secret=bot_secret, port=8080) as server:
        server.on_message(handle_message)
        server.on_action(handle_action)

        print(f'Bot webhook server running on :8080/{url_key}, press Ctrl+C to stop')
        # Keep running until interrupted
        try:
            await asyncio.Event().wait()
        except asyncio.CancelledError:
            pass


if __name__ == '__main__':
    asyncio.run(main())
