"""Telegram Bot 网关。"""

import asyncio
from typing import Any, Optional

from butler.gateway.base import BaseGateway


class TelegramGateway(BaseGateway):
    """Telegram Bot 网关，使用 python-telegram-bot 库。"""

    name = "telegram"

    def __init__(self, bot_token: str, allowed_chats: Optional[list[str]] = None):
        super().__init__()
        self.bot_token = bot_token
        self.allowed_chats = allowed_chats or []
        self._app: Any = None

    async def start(self) -> None:
        """启动 Telegram Bot（polling 模式）。"""
        from telegram.ext import ApplicationBuilder, MessageHandler, filters

        self._app = (
            ApplicationBuilder()
            .token(self.bot_token)
            .build()
        )

        # 注册消息处理器
        self._app.add_handler(
            MessageHandler(filters.TEXT & ~filters.COMMAND, self._on_message)
        )

        # 注册 /start 命令
        from telegram.ext import CommandHandler
        self._app.add_handler(CommandHandler("start", self._on_start))

        await self._app.initialize()
        await self._app.start()
        print("[telegram] Bot started (polling)")
        await self._app.updater.start_polling()

    async def _on_start(self, update: Any, context: Any) -> None:
        """处理 /start 命令。"""
        if update.effective_user:
            await update.message.reply_text(
                "你好！我是 Butler-Shell，你的远程服务器助手。\n"
                "直接用自然语言告诉我你想做什么，比如：\n"
                "- 查看当前目录\n"
                "- 看下磁盘空间\n"
                "- 系统负载怎么样"
            )

    async def _on_message(self, update: Any, context: Any) -> None:
        """收到 Telegram 消息。"""
        if not update.effective_user or not update.message:
            return

        user_id = str(update.effective_user.id)
        text = update.message.text

        # 检查聊天白名单
        if self.allowed_chats and user_id not in self.allowed_chats:
            await update.message.reply_text("抱歉，你没有使用权限。")
            return

        if self._message_handler:
            result = self._message_handler(user_id, text, self.name)
            if asyncio.iscoroutine(result):
                asyncio.ensure_future(result)

    async def send_message(self, user_id: str, text: str) -> None:
        """通过 Telegram 发送消息。"""
        if self._app:
            await self._app.bot.send_message(chat_id=int(user_id), text=text)

    async def stop(self) -> None:
        """停止 Bot。"""
        if self._app:
            try:
                if self._app.updater.running:
                    await self._app.updater.stop()
            except RuntimeError:
                pass
            try:
                await self._app.stop()
                await self._app.shutdown()
            except Exception:
                pass
            print("[telegram] Bot stopped")
