from typing import Any, cast
from konabot.common.llm import get_llm
from konabot.common.permsys import perm_manager
from konabot.plugins.handle_text.base import (
    TextHandler,
    TextHandlerEnvironment,
    TextHandleResult,
)


class THQwen(TextHandler):
    name = "qwen"

    async def handle(
        self, env: TextHandlerEnvironment, istream: str | None, args: list[str]
    ) -> TextHandleResult:
        pm = perm_manager()
        if env.event is None or not await pm.check_has_permission(
            env.event, "textfx.qwen"
        ):
            return TextHandleResult(
                code=1,
                ostream="你或当前环境没有使用 qwen 的权限。如有疑问请联系管理员",
            )

        llm = get_llm()
        messages = []

        if istream is not None:
            messages.append({"role": "user", "content": istream})
        if len(args) > 0:
            message = " ".join(args)
            messages.append(
                {
                    "role": "user",
                    "content": message,
                }
            )
        if len(messages) == 0:
            return TextHandleResult(
                code=1,
                ostream="使用方法：qwen <提示词>",
            )

        messages = [
            {
                "role": "system",
                "content": "除非用户要求，请尽可能短点回答。另外，当前环境不支持 Markdown 语法，如果可以，请使用纯文本回答",
            }
        ] + messages
        result = await llm.chat(cast(Any, messages))
        content = result.content
        if content is None:
            return TextHandleResult(
                code=500,
                ostream="问 AI 的时候发生了未知的错误",
            )
        return TextHandleResult(
            code=0,
            ostream=content,
        )
