from flask import Flask, request, abort

import telebot
from telebot import types

from config import Config
from db import init_db, db
from services import Services
from handlers import register_handlers


if not Config.BOT_TOKEN:
    raise RuntimeError("BOT_TOKEN is not set.")


app = Flask(__name__)

bot = telebot.TeleBot(Config.BOT_TOKEN, parse_mode=None)
services = Services(bot)

register_handlers(bot, services)

init_db()


@app.route("/", methods=["GET"])
def index():
    return "Telegram bot is running.", 200


@app.route(f"/webhook/{Config.WEBHOOK_PATH}", methods=["POST"])
def webhook():
    if Config.WEBHOOK_SECRET:
        header_secret = request.headers.get("X-Telegram-Bot-Api-Secret-Token")
        if header_secret != Config.WEBHOOK_SECRET:
            abort(403)

    if request.headers.get("Content-Type") != "application/json":
        abort(400)

    update = telebot.types.Update.de_json(request.get_data().decode("utf-8"))
    bot.process_new_updates([update])

    return "ok", 200


@app.teardown_appcontext
def cleanup_db(exception=None):
    db.remove()


application = app


if __name__ == "__main__":
    # For local testing with polling.
    # On production/cPanel use webhook.
    try:
        bot.remove_webhook()
    except Exception:
        pass

    bot.infinity_polling()