import re
import nonebot

from nonebot.adapters.onebot.v11 import Bot as OBBot


class UsernameManager:
    grouped_data: dict[int, dict[int, str]]
    individual_data: dict[int, str]

    def __init__(self) -> None:
        self.grouped_data = {}
        self.individual_data = {}

    async def update(self):
        for bot in nonebot.get_bots().values():
            if isinstance(bot, OBBot):
                for user in await bot.get_friend_list():
                    uid = user["user_id"]
                    nickname = user["nickname"]
                    self.individual_data[uid] = nickname
                for group in await bot.get_group_list():
                    gid = group["group_id"]
                    for member in await bot.get_group_member_list(group_id=gid):
                        uid = member["user_id"]
                        card = member.get("card", "")
                        nickname = member.get("nickname", "")
                        if card:
                            self.grouped_data.setdefault(gid, {})[uid] = card
                        if nickname:
                            self.individual_data[uid] = nickname

    def get(self, qqid: int, groupid: int | None = None) -> str:
        if groupid is not None and groupid in self.grouped_data:
            n = self.grouped_data[groupid].get(qqid)
            if n is not None:
                return n
        if qqid in self.individual_data:
            return self.individual_data[qqid]
        return str(qqid)


manager = UsernameManager()

def get_username(qqid: int | str, group: int | str | None = None):
    if isinstance(group, str):
        group = None if not re.match(r"^\d+$", group) else int(group)
    if isinstance(qqid, str):
        if re.match(r"^\d+$", qqid):
            qqid = int(qqid)
        else:
            return qqid
    return manager.get(qqid, group)

