# webhook.py
from aiohttp import web
from telegram import Update
from telegram.ext import Application, ExtBot
import logging
import json

logger = logging.getLogger(__name__)

async def webhook_handler(request):
    """هندلر اصلی وب‌هوک تلگرام"""
    try:
        data = await request.json()
        update = Update.de_json(data, bot)
        await application.process_update(update)
        return web.Response(status=200)
    except Exception as e:
        logger.error(f"خطا در وب‌هوک: {e}")
        return web.Response(status=500)

async def root_handler(request):
    """هندلر صفحه اصلی (برای تست و جلوگیری از 404)"""
    return web.Response(
        text=json.dumps({
            "status": "ok",
            "bot": "Music Bot",
            "message": "Webhook endpoint is /webhook"
        }, indent=2),
        content_type="application/json",
        status=200
    )

async def health_handler(request):
    """هندلر سلامت (برای monitoring)"""
    return web.Response(
        text=json.dumps({
            "status": "healthy",
            "timestamp": __import__('datetime').datetime.now().isoformat()
        }, indent=2),
        content_type="application/json",
        status=200
    )

async def setup_webhook(app: Application, webhook_url: str, port: int, listen: str = "0.0.0.0"):
    """راه‌اندازی وب‌هوک"""
    global application, bot
    application = app
    bot = app.bot
    
    # تنظیم وب‌هوک در تلگرام
    await bot.set_webhook(webhook_url)
    logger.info(f"✅ وب‌هوک تنظیم شد: {webhook_url}")
    
    # راه‌اندازی سرور aiohttp
    web_app = web.Application()
    web_app.router.add_post("/webhook", webhook_handler)
    web_app.router.add_get("/", root_handler)
    web_app.router.add_get("/health", health_handler)
    
    runner = web.AppRunner(web_app)
    await runner.setup()
    site = web.TCPSite(runner, listen, port)
    await site.start()
    logger.info(f"🚀 سرور وب‌هوک روی پورت {port} اجرا شد")
    logger.info(f"📍 اندپوینت‌ها: /webhook (POST), /health (GET), / (GET)")
    
    return runner