"""
Long-polling runner (alternative to the webhook server).

Receives updates directly from Telegram via getUpdates and feeds each one to
the same dispatcher used by the webhook. Useful for running the bot without a
public HTTPS endpoint.

app.py (webhook, served by Passenger in production) and this poller are
mutually exclusive — this process calls deleteWebhook on startup, which would
break a live production webhook if both ever ran at once (e.g. a stray cron
job left running on the production host). To make that impossible to trigger
by accident, this refuses to start unless ALLOW_POLLING=true is set in the
environment; that must stay unset/false on any host where app.py is the live
deployment.

Run:  ALLOW_POLLING=true python -m financegpt_bot.poller
"""

import logging
import sys

from . import config
from .core.router import dispatch
from .services.telegram_api import TelegramAPI

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
log = logging.getLogger("financegpt_bot.poller")


def main() -> None:
    if not config.ALLOW_POLLING:
        log.error(
            "Refusing to start: ALLOW_POLLING is not set to true. "
            "This process deletes the webhook on startup, which would break "
            "the production app.py/Passenger deployment if both ran at once. "
            "Set ALLOW_POLLING=true only for a local/dev run without a "
            "public HTTPS endpoint."
        )
        sys.exit(1)

    api = TelegramAPI()
    # Webhook and long polling are mutually exclusive on Telegram.
    try:
        api.delete_webhook()
    except Exception:
        log.warning("could not delete webhook before polling")

    log.info("FinanceGPT Bot — polling Telegram for updates")
    offset = None
    while True:
        try:
            updates = api.get_updates(offset=offset, timeout=30)
        except Exception:
            log.exception("getUpdates failed; retrying")
            continue

        for update in updates:
            offset = update["update_id"] + 1
            try:
                dispatch(update)
            except Exception:
                log.exception("error while processing update %s", update.get("update_id"))


if __name__ == "__main__":
    main()
