#!/usr/bin/env python3
"""
Setup webhook for the Telegram bot.
Run this once to register your webhook URL with Telegram.

Usage:
    python setup_webhook.py https://yourdomain.com/webhook
    
Or set WEBHOOK_URL in .env and run:
    python setup_webhook.py
"""
import asyncio
import os
import sys
from dotenv import load_dotenv

load_dotenv()


async def main():
    from aiogram import Bot
    from aiogram.client.default import DefaultBotProperties
    from aiogram.enums import ParseMode

    token = os.getenv("BOT_TOKEN", "")
    if not token:
        print("ERROR: BOT_TOKEN not set in .env")
        sys.exit(1)

    # Get webhook URL from argument or env
    webhook_url = ""
    if len(sys.argv) > 1:
        webhook_url = sys.argv[1].rstrip("/")
    else:
        webhook_url = os.getenv("WEBHOOK_URL", "").rstrip("/")

    if not webhook_url:
        print("ERROR: Provide webhook URL as argument or set WEBHOOK_URL in .env")
        print("Example: python setup_webhook.py https://yourdomain.com")
        sys.exit(1)

    webhook_secret = os.getenv("WEBHOOK_SECRET", "")
    webhook_path = "/webhook"
    full_url = webhook_url.rstrip("/") + webhook_path

    bot = Bot(token=token, default=DefaultBotProperties(parse_mode=ParseMode.HTML))

    print(f"Setting webhook to: {full_url}")
    result = await bot.set_webhook(
        url=full_url,
        secret_token=webhook_secret or None,
        drop_pending_updates=True,
    )
    if result:
        print("Webhook set successfully!")
    else:
        print("Failed to set webhook!")
        await bot.session.close()
        sys.exit(1)

    # Verify
    info = await bot.get_webhook_info()
    print(f"\nWebhook info:")
    print(f"  URL: {info.url}")
    print(f"  Pending updates: {info.pending_update_count}")
    if info.last_error_date:
        print(f"  Last error: {info.last_error_message} ({info.last_error_date})")
    else:
        print(f"  No errors")

    await bot.session.close()


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