from nonebot import on_command, get_loaded_plugins, logger
from nonebot.rule import fullmatch, Rule
from nonebot.adapters.onebot.v11.event import MessageEvent
from nonebot.plugin import Plugin
from nonebot_plugin_saa import Text, MessageFactory
import asyncio

ALLOWED_USER = 1424473282

async def _check_user(event: MessageEvent) -> bool:
    """检查用户是否有权限使用该命令"""
    return event.user_id == ALLOWED_USER

cmd = on_command(
    "指令列表",
    rule=Rule(_check_user) & fullmatch(("指令列表", "命令列表", "help list", "cmd list")),
    priority=1,
    block=True
)

def format_plugin_info(plugin: Plugin) -> str:
    """格式化插件信息"""
    info = []
    if hasattr(plugin, "metadata") and plugin.metadata:
        meta = plugin.metadata
        if hasattr(meta, "name") and meta.name:
            info.append(f"插件名称: {meta.name}")
        if hasattr(meta, "description") and meta.description:
            info.append(f"功能描述: {meta.description}")
        if hasattr(meta, "usage") and meta.usage:
            info.append(f"使用方法: {meta.usage}")
    return "\n".join(info) if info else f"插件: {plugin.name}"

@cmd.handle()
async def handle_command_list():
    try:
        plugins = get_loaded_plugins()
    except Exception as e:
        logger.error(f"获取插件列表失败: {e}")
        await cmd.finish("获取指令列表失败，请稍后再试")
        return

    msg_parts = ["当前支持的指令列表：\n"]
    
    for plugin in sorted(plugins, key=lambda p: p.name):
        plugin_info = format_plugin_info(plugin)
        if plugin_info:
            msg_parts.append(f"\n{plugin_info}\n{'='*30}")
    
    await MessageFactory([Text("\n".join(msg_parts))]).send(
        at_sender=True,
        reply=True
    ) 