import asyncio
import sys
import os
import signal
import logging
# pyrefly: ignore [missing-import]
from aiohttp import web

# --- Logging Setup (Errors Only) ---
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger("Main")

# Health Check for Render/Production
async def handle_health(request):
    return web.Response(text="Bot is running!")

async def start_health_server():
    app = web.Application()
    app.router.add_get("/", handle_health)
    port = int(os.environ.get("PORT", 10000))
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, '0.0.0.0', port)
    await site.start()
    logger.info(f"Health Check Server started on port {port}")

async def start_bot():
    # pyrefly: ignore [missing-import]
    from telethon import TelegramClient
    from config import API_ID, API_HASH
    from database.manager import DatabaseManager
    from handlers.user import register_user_handlers
    from handlers.admin import register_admin_handlers
    from utils.api_helpers import get_session

    logger.info("Initializing production services...")
    
    db = DatabaseManager()
    await db.initialize()

    # Using a professional session name
    client = TelegramClient('mri_store_session', API_ID, API_HASH)
    
    # Register Handlers
    register_user_handlers(client)
    register_admin_handlers(client)

    await client.start()
    me = await client.get_me()
    logger.info(f"Logged in as: {me.first_name} (ID: {me.id})")

    # Start Health Server in background
    asyncio.create_task(start_health_server())

    # Graceful Shutdown Logic
    async def stop():
        logger.info("Shutting down gracefully...")
        try:
            await client.disconnect()
            session = await get_session()
            await session.close()
            logger.info("All services stopped.")
        except Exception as e:
            logger.error(f"Error during shutdown: {e}")
        finally:
            # Standard exit
            sys.exit(0)
            
    # Note: signal handlers are tricky on Windows, using try-except for KeyboardInterrupt
    
    try:
        await client.run_until_disconnected()
    except Exception as e:
        logger.error(f"Critical error in bot loop: {e}")
    finally:
        await stop()

if __name__ == "__main__":
    try:
        asyncio.run(start_bot())
    except KeyboardInterrupt:
        logger.info("Bot stopped by user (Ctrl+C)")
    except Exception as e:
        logger.error(f"Unexpected error: {e}")
