"""cPanel/Passenger WSGI adapter for the Telegram bot.

The Telegram polling loop runs in a background thread while Passenger serves
simple health responses. Set BOT_TOKEN and ADMIN_ID in cPanel's Python App
configuration before restarting the application.
"""
import os
import threading
import asyncio
import logging

logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"))
_started = False
_lock = threading.Lock()


def _run_bot():
    # Import only after Passenger has loaded the application's environment.
    from bot import main
    asyncio.run(main())


def application(environ, start_response):
    global _started
    with _lock:
        if not _started:
            if not os.getenv("BOT_TOKEN") or not os.getenv("ADMIN_ID"):
                body = b"Bot configuration missing: set BOT_TOKEN and ADMIN_ID in cPanel."
                start_response("500 Internal Server Error", [("Content-Type", "text/plain; charset=utf-8"), ("Content-Length", str(len(body)))])
                return [body]
            thread = threading.Thread(target=_run_bot, name="telegram-bot", daemon=True)
            thread.start()
            _started = True
    body = b"Telegram bot service is running under Passenger."
    start_response("200 OK", [("Content-Type", "text/plain; charset=utf-8"), ("Content-Length", str(len(body)))])
    return [body]
