#!/usr/bin/env python3
"""One-time Telegram webhook registration for cPanel WSGI mode.

Only the bot token and staff IDs are configured in config.py. Pass the actual hosting
subdomain URL on the command line; the webhook secret is generated automatically.
"""
import asyncio
import os
import re
import sys
from urllib.parse import urlparse

import config
from telegram import Bot, Update


def resolve_url() -> str:
    if len(sys.argv) > 1:
        url = sys.argv[1].strip()
    else:
        url = os.environ.get("SPG_WEBHOOK_PUBLIC_URL", "").strip()
    parsed = urlparse(url) if url else None
    if not parsed or parsed.scheme != "https" or not parsed.netloc or parsed.path.rstrip("/") != "/webhook" or parsed.query or parsed.fragment:
        raise SystemExit(
            "Usage: python setup_webhook.py https://YOUR-SUBDOMAIN.example.com/webhook\n"
            "Use the real HTTPS subdomain you assigned to this cPanel Python app. No need to edit config.py for this URL."
        )
    if not re.fullmatch(r"[A-Za-z0-9.-]+(?::[0-9]{1,5})?", parsed.netloc):
        raise SystemExit("Invalid hostname in webhook URL")
    return url.rstrip("/")


async def main() -> None:
    token = config.BOT_TOKEN.strip()
    if not token or token == "PASTE_SUPPORT_BOT_TOKEN_HERE":
        raise SystemExit("Set BOT_TOKEN in config.py first")
    if not any(isinstance(x, int) and x > 0 for x in config.OWNER_IDS):
        raise SystemExit("Set OWNER_IDS in config.py first")
    url = resolve_url()
    secret = config.get_or_create_webhook_secret()
    bot = Bot(token=token)
    await bot.initialize()
    try:
        ok = await bot.set_webhook(
            url=url,
            secret_token=secret,
            allowed_updates=Update.ALL_TYPES,
            drop_pending_updates=False,
            # Conservative default for shared hosting; increase only after measured capacity tests.
            max_connections=20,
        )
        info = await bot.get_webhook_info()
        print("setWebhook:", ok)
        print("Webhook URL:", info.url)
        print("Pending updates:", info.pending_update_count)
        print("Last error:", info.last_error_message or "none")
        print("Secret token: generated and saved privately; value not printed.")
    finally:
        await bot.shutdown()


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