import asyncio
import logging
import sys

from aiogram import Bot, Dispatcher
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from aiohttp import web

from config import settings
from handlers import start, marathons, link
from middlewares.logging import LoggingMiddleware

# Configure logging to stdout with DEBUG level
logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    handlers=[
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger(__name__)

# Set aiogram logging level
logging.getLogger("aiogram").setLevel(logging.INFO)

# Health check state
bot_running = False


async def health_handler(request):
    """Health check endpoint"""
    if bot_running:
        return web.json_response({"status": "ok", "service": "telegram-bot"})
    return web.json_response({"status": "starting"}, status=503)


async def start_health_server():
    """Start health check HTTP server"""
    app = web.Application()
    app.router.add_get("/health", health_handler)
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, "0.0.0.0", 8080)
    await site.start()
    logger.info("Health check server started on port 8080")
    return runner


async def main():
    global bot_running

    logger.info("="*50)
    logger.info("Starting Game Marathon Bot...")
    logger.info(f"API_URL: {settings.API_URL}")
    logger.info(f"BOT_TOKEN: {settings.TELEGRAM_BOT_TOKEN[:20]}...")
    logger.info("="*50)

    # Start health check server
    health_runner = await start_health_server()

    bot = Bot(
        token=settings.TELEGRAM_BOT_TOKEN,
        default=DefaultBotProperties(parse_mode=ParseMode.HTML)
    )

    # Get bot username for deep links
    bot_info = await bot.get_me()
    settings.BOT_USERNAME = bot_info.username
    logger.info(f"Bot info: @{settings.BOT_USERNAME} (id={bot_info.id})")

    dp = Dispatcher()

    # Register middleware
    dp.message.middleware(LoggingMiddleware())
    logger.info("Logging middleware registered")

    # Register routers
    logger.info("Registering routers...")
    dp.include_router(start.router)
    dp.include_router(link.router)
    dp.include_router(marathons.router)
    logger.info("Routers registered: start, link, marathons")

    # Mark bot as running
    bot_running = True

    # Start polling
    logger.info("Deleting webhook and starting polling...")
    await bot.delete_webhook(drop_pending_updates=True)
    logger.info("Polling started! Waiting for messages...")
    try:
        await dp.start_polling(bot)
    finally:
        bot_running = False
        await health_runner.cleanup()


if __name__ == "__main__":
    asyncio.run(main())
