"""
基础消息处理器（不含 AI 能力）。
"""

import botpy
from botpy.message import Message

from src.utils.logger import setup_logger

logger = setup_logger("MessageHandler")


class MessageHandler:
    """消息处理器。"""

    def __init__(self, client):
        self.client = client

    async def handle_at_message(self, message: Message):
        """
        处理 @机器人的消息。

        Args:
            message: 消息对象
        """
        author_name = self._get_author_name(message)
        msg_type = type(message).__name__.replace("Message", "")
        logger.info(
            f"[{msg_type}] {author_name}: {message.content[:30]}{'...' if len(message.content) > 30 else ''}"
        )

        content = message.content.strip()

        if self.client.robot.name:
            content = content.replace(f"@{self.client.robot.name}", "").strip()

        if content.startswith("/"):
            await self._handle_command(message, content)
        else:
            await self._handle_chat(message, content)

    @staticmethod
    def _get_author_name(message: Message) -> str:
        """兼容频道消息、群消息、C2C 私聊消息的作者字段。"""
        author = getattr(message, "author", None)
        if not author:
            return "Unknown"

        return (
            getattr(author, "username", None)
            or getattr(author, "nick", None)
            or getattr(author, "member_openid", None)
            or getattr(author, "user_openid", None)
            or "Unknown"
        )

    async def _handle_command(self, message: Message, content: str):
        """
        处理命令消息。

        Args:
            message: 消息对象
            content: 消息内容
        """
        command = content.split()[0].lower()

        if command == "/help" or command == "/帮助":
            await self._send_help(message)
        elif command == "/ping":
            await self._send_ping(message)
        elif command == "/info" or command == "/信息":
            await self._send_info(message)
        else:
            await self._send_reply(message, f"未知命令: {command}\n发送 /help 查看可用命令")

    async def _handle_chat(self, message: Message, content: str):
        """
        处理普通聊天消息。

        Args:
            message: 消息对象
            content: 消息内容
        """
        if "你好" in content or "hello" in content.lower():
            reply = "你好！我是 QQ 机器人，很高兴为你服务。"
        elif "天气" in content:
            reply = "天气查询功能还在开发中。"
        elif "时间" in content:
            from datetime import datetime

            now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            reply = f"当前时间: {now}"
        else:
            reply = f"收到你的消息: {content}\n发送 /help 查看我能做什么"

        await self._send_reply(message, reply)

    async def _send_help(self, message: Message):
        """发送帮助信息。"""
        help_text = """
QQ 机器人帮助

可用命令:
/help 或 /帮助 - 显示帮助信息
/ping - 测试机器人连通性
/info 或 /信息 - 显示机器人信息

其他功能:
- @我并发送消息，我会回复你
- 输入“你好”可打招呼
- 输入“时间”可查看当前时间
        """.strip()
        await self._send_reply(message, help_text)

    async def _send_ping(self, message: Message):
        """发送 Ping 响应。"""
        await self._send_reply(message, "Pong，机器人运行正常。")

    async def _send_info(self, message: Message):
        """发送机器人信息。"""
        info_text = f"""
机器人信息

名称: {self.client.robot.name}
ID: {self.client.robot.id}
状态: 运行中

基于 QQ 官方 SDK (botpy)
        """.strip()
        await self._send_reply(message, info_text)

    async def _send_reply(self, message: Message, content: str):
        """
        发送回复消息。

        Args:
            message: 原始消息对象
            content: 回复内容
        """
        try:
            await message.reply(content=content)
            logger.info(f"回复: {content[:30]}{'...' if len(content) > 30 else ''}")
        except Exception as e:
            logger.error(f"发送失败: {e}")
            import traceback

            logger.debug(f"详细错误:\n{traceback.format_exc()}")
