import asyncio
import logging
from aiogram import Bot, Dispatcher

logger = logging.getLogger("cvc.telegram_gateway")

_bot: Bot | None = None
_dp: Dispatcher | None = None
_polling_task: asyncio.Task | None = None

async def start_telegram_gateway(settings, workspace_mgr):
    global _bot, _dp, _polling_task
    
    if not settings.telegram.bot_token:
        logger.error("Telegram bot_token is missing.")
        return

    _bot = Bot(token=settings.telegram.bot_token)
    _dp = Dispatcher()

    # Import handler to bind routes
    from cvc.adapters.telegram_handler import register_handlers
    register_handlers(_dp, _bot, settings, workspace_mgr)

    logger.info("Telegram gateway starting polling...")
    _polling_task = asyncio.create_task(_dp.start_polling(_bot))

async def stop_telegram_gateway():
    global _bot, _dp, _polling_task
    if _polling_task:
        _polling_task.cancel()
    if _dp:
        await _dp.stop_polling()
    if _bot:
        await _bot.session.close()
