import asyncio
import random
from typing import cast

from loguru import logger
from nonebot import get_bot, on_request
import nonebot
from nonebot.adapters.onebot.v11.event import FriendRequestEvent
from nonebot.adapters.onebot.v11.bot import Bot as OnebotBot
from nonebot_plugin_apscheduler import scheduler

from konabot.common.nb.is_admin import cfg as adminConfig
from konabot.common.username import manager

add_request = on_request()

@add_request.handle()
async def _(req: FriendRequestEvent):
    bot = cast(OnebotBot, get_bot(str(req.self_id)))
    ok_member_ls: set[int] = set()
    for group in adminConfig.admin_qq_group:
        members = await bot.get_group_member_list(group_id=group)
        ok_member_ls |= cast(set[int], set((m.get("user_id") for m in members)))
    if req.user_id in ok_member_ls:
        await asyncio.sleep(random.randint(5, 10))
        await req.approve(bot)
        logger.info(f"已经自动同意 {req.user_id} 的好友请求")

@scheduler.scheduled_job("cron", minute="*/5")
async def _():
    logger.info("尝试更新群成员信息")
    await manager.update()

driver = nonebot.get_driver()

@driver.on_bot_connect
async def _():
    logger.info("有 Bot 连接，5 秒后试着更新群成员信息")
    await asyncio.sleep(5)
    await manager.update()
