import asyncio, hmac, logging
from flask import Flask, request, abort
from aiogram import Bot, Dispatcher
from aiogram.types import Update
from app.config import BOT_TOKEN, WEBHOOK_SECRET
from app.handlers import router
from database.db import init_db

logging.basicConfig(level=logging.INFO)
app = Flask(__name__)
init_db()
dispatcher = Dispatcher()
dispatcher.include_router(router)

@app.get("/")
def health():
    return {"service": "Shiba Manga Bot", "status": "ok"}

@app.post("/telegram")
def telegram_webhook():
    if not WEBHOOK_SECRET:
        abort(503)
    supplied = request.headers.get("X-Telegram-Bot-Api-Secret-Token", "")
    if not hmac.compare_digest(supplied, WEBHOOK_SECRET):
        abort(403)
    if not BOT_TOKEN:
        abort(503)
    payload = request.get_json(silent=True)
    if not payload:
        abort(400)
    async def process():
        bot = Bot(BOT_TOKEN)
        try:
            update = Update.model_validate(payload, context={"bot": bot})
            await dispatcher.feed_update(bot, update)
        finally:
            await bot.session.close()
    try:
        asyncio.run(process())
    except Exception:
        logging.exception("Webhook update failed")
        # Return 200 to avoid Telegram retry storms; details are in logs.
    return {"ok": True}
