"""
Corre el bot en modo "long polling": el script le pregunta a Telegram
en loop si hay mensajes nuevos, en vez de esperar que Telegram le
avise por webhook. No necesita servidor web, dominio, ni Passenger —
solo un proceso Python corriendo en background.

Uso:
    python bot_polling.py

Para dejarlo corriendo en el hosting incluso después de cerrar la
terminal SSH, usá nohup:
    nohup python3 bot_polling.py > bot.log 2>&1 &
    disown
"""
import time

import database as db
import telegram_client as tg
from config import validar_config
from bot_handlers import manejar_mensaje

validar_config()
db.init_db()

print("Bot arrancando en modo polling... (Ctrl+C para detener)")

# Por las dudas, nos aseguramos de que no haya un webhook configurado
# (Telegram no permite webhook y polling al mismo tiempo).
try:
    tg.eliminar_webhook()
except Exception as e:
    print(f"Aviso: no se pudo eliminar webhook previo (puede que no hubiera): {e}")

offset = None

while True:
    try:
        updates = tg.obtener_updates(offset=offset, timeout=30)
        for update in updates:
            offset = update["update_id"] + 1
            try:
                manejar_mensaje(update)
            except Exception as e:
                print(f"Error procesando un mensaje: {e}")
    except KeyboardInterrupt:
        print("\nBot detenido.")
        break
    except Exception as e:
        print(f"Error de conexión, reintentando en 5s: {e}")
        time.sleep(5)
