from typing import Any, cast

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


async def qq_broadcast(groups: list[str], msg: UniMessage[Any] | str):
    if isinstance(msg, str):
        msg = UniMessage.text(msg)
    bots: dict[str, OBBot] = {}

    # group_id -> bot_id
    availabilities: dict[str, str] = {}

    for bot_id, bot in nonebot.get_bots().items():
        if not isinstance(bot, OBBot):
            continue
        bots[bot_id] = bot
        gl = await bot.get_group_list()
        for g in gl:
            gid = str(g.get("group_id", -1))
            if gid in groups:
                availabilities[gid] = bot_id

    for group in groups:
        if group in availabilities:
            bot = bots[availabilities[group]]
            await bot.send_group_msg(
                group_id=int(group),
                message=cast(Any, await msg.export(bot)),
                auto_escape=False,
            )
