"""
set_webhook.py
==============

PURPOSE
-------
A small COMMAND-LINE helper you run ONCE (and whenever your URL changes) to
tell Telegram where to send updates. This is the step that "turns the bot on".

Until you register a webhook, Telegram has no idea your server exists and your
bot will appear dead. After registering, every message a user sends is POSTed
to your /webhook route automatically.

HOW TO RUN IT
-------------
From the project folder, inside your cPanel Python app's virtualenv terminal
(or locally with your .env filled in):

    python set_webhook.py set        # register the webhook
    python set_webhook.py info       # show current webhook status
    python set_webhook.py delete     # unregister (stop receiving updates)

WHAT "set" SENDS TO TELEGRAM
----------------------------
It calls Telegram's setWebhook method with:
    url          = WEBHOOK_URL  (your https://domain/webhook)
    secret_token = WEBHOOK_SECRET (echoed back to us for verification)
"""

import sys

import requests

# Reuse the exact same config the running bot uses, so there's no chance of
# the URL/secret drifting out of sync.
from config import (
    TELEGRAM_API_BASE,
    WEBHOOK_URL,
    WEBHOOK_SECRET,
    HTTP_TIMEOUT,
)


def set_webhook() -> None:
    """Register WEBHOOK_URL with Telegram so updates start flowing in."""
    if not WEBHOOK_URL:
        print("ERROR: WEBHOOK_URL is not set. Add it to your .env / env vars.")
        return

    payload = {
        "url": WEBHOOK_URL,
        # Telegram will only deliver these update types. "message" covers text;
        # "callback_query" covers inline-button taps.
        "allowed_updates": ["message", "callback_query"],
        # Drop any messages that piled up while the webhook was off.
        "drop_pending_updates": True,
    }

    # Attach the secret token if we have one (strongly recommended).
    if WEBHOOK_SECRET:
        payload["secret_token"] = WEBHOOK_SECRET

    response = requests.post(
        f"{TELEGRAM_API_BASE}/setWebhook",
        json=payload,
        timeout=HTTP_TIMEOUT,
    )
    data = response.json()

    if data.get("ok"):
        print(f"✅ Webhook set to: {WEBHOOK_URL}")
    else:
        print(f"❌ Failed to set webhook: {data}")


def webhook_info() -> None:
    """Ask Telegram what webhook (if any) is currently configured."""
    response = requests.get(
        f"{TELEGRAM_API_BASE}/getWebhookInfo",
        timeout=HTTP_TIMEOUT,
    )
    data = response.json()

    if not data.get("ok"):
        print(f"❌ Could not fetch webhook info: {data}")
        return

    info = data["result"]
    print("Current webhook status:")
    print(f"  URL                 : {info.get('url') or '(none set)'}")
    print(f"  Pending updates     : {info.get('pending_update_count', 0)}")
    # last_error_message is the #1 clue when a webhook 'looks set' but the bot
    # is silent — it tells you exactly why Telegram's last delivery failed.
    if info.get("last_error_message"):
        print(f"  Last delivery error : {info['last_error_message']}")
    else:
        print("  Last delivery error : (none)")


def delete_webhook() -> None:
    """Remove the webhook so Telegram stops sending updates."""
    response = requests.post(
        f"{TELEGRAM_API_BASE}/deleteWebhook",
        json={"drop_pending_updates": True},
        timeout=HTTP_TIMEOUT,
    )
    data = response.json()
    if data.get("ok"):
        print("✅ Webhook deleted.")
    else:
        print(f"❌ Failed to delete webhook: {data}")


# This makes the file runnable from the command line. sys.argv[1] is the first
# word you type after the filename (set / info / delete).
if __name__ == "__main__":
    # If no command is given, default to showing usage.
    command = sys.argv[1] if len(sys.argv) > 1 else "help"

    if command == "set":
        set_webhook()
    elif command == "info":
        webhook_info()
    elif command == "delete":
        delete_webhook()
    else:
        print(__doc__)  # Print this file's top docstring as help text.
