"""
提取首字母

...谁需要啊！！！
"""

import functools

from loguru import logger
from nonebot import on_message
from nonebot.rule import KeywordsRule, Rule
from nonebot.adapters.onebot.v11.bot import Bot as OBBot
from nonebot.adapters.onebot.v11.event import MessageEvent as OBMessageEvent
from nonebot.adapters.onebot.v11.message import MessageSegment as OBMessageSegment
from nonebot_plugin_alconna import Text, UniMsg
from nonebot_plugin_alconna.uniseg.adapters.onebot11.builder import Onebot11MessageBuilder
from pypinyin import pinyin, Style as PinyinStyle

from konabot.common.longtask import DepLongTaskTarget
from konabot.common.apis.ali_content_safety import AlibabaGreen


keywords = ("szmtq", "tqszm", "提取首字母", "首字母提取", )
rule = Rule(KeywordsRule(*keywords))


cmd_tqszm = on_message(rule=rule)

@cmd_tqszm.handle()
async def _(target: DepLongTaskTarget, msg: UniMsg, evt: OBMessageEvent | None = None, bot: OBBot | None = None):
    texts = ""
    command_occurred = False
    is_reply_mode = False

    if evt is not None and bot is not None:
        reply = await Onebot11MessageBuilder().extract_reply(evt, bot)
        if reply is not None:
            is_reply_mode = True
            for seg in reply.data.get('msg', []):
                if isinstance(seg, OBMessageSegment) and seg.type == 'text':
                    segtext: str = seg.data.get('text', '')
                    texts += segtext

    if is_reply_mode:
        for seg in msg:
            if isinstance(seg, Text):
                if all(seg.text.strip() != k for k in keywords):
                    return
    else:
        for seg in msg:
            if isinstance(seg, Text):
                if command_occurred:
                    texts += seg.text
                    continue
                if any(seg.text.startswith(w) for w in keywords):
                    command_occurred = True
                    texts += next(
                        seg.text.removeprefix(w) for w in keywords
                        if seg.text.startswith(w)
                    ).removeprefix(" ")

    result = pinyin(texts, style=PinyinStyle.FIRST_LETTER, errors=lambda x: x)
    print(result)
    result_text = functools.reduce(lambda x, y: x + y, [
        p[0] for p in result if len(p) > 0
    ], "")

    if not await AlibabaGreen.detect(result_text):
        logger.info(f"对首字母序列的检测未通过安全测试 RAW={texts} FORMATTED={result_text}")

    await target.send_message(result_text, at=False)

