import re

from nonebot import get_plugin_config, on_message
from nonebot.rule import Rule
from nonebot_plugin_alconna import Reference, Reply, UniMsg

from nonebot.adapters import Event
from pydantic import BaseModel

from konabot.common.permsys import require_permission


class Config(BaseModel):
    bilifetch_enabled_groups: list[int] = []


config = get_plugin_config(Config)
pattern = (
    r"^(?:(?:av|cv)\d+|BV[a-zA-Z0-9]{10})|"
    r"(?:b23\.tv|bili(?:22|23|33|2233)\.cn|\.bilibili\.com|QQ小程序(?:&amp;#93;|&#93;|\])哔哩哔哩).{0,500}"
)


def _rule(msg: UniMsg) -> bool:
    to_search = msg.exclude(Reply, Reference).dump(json=True)
    to_search2 = msg.exclude(Reply, Reference).extract_plain_text()
    if not re.search(pattern, to_search) and not re.search(pattern, to_search2):
        return False
    return True


matcher_fix = on_message(rule=Rule(_rule) & require_permission("bilifetch"))


@matcher_fix.handle()
async def _(event: Event):
    from nonebot_plugin_analysis_bilibili import handle_analysis

    await handle_analysis(event)
