from nonebot import on_request, get_plugin_config, logger
from nonebot.adapters.onebot.v11 import FriendRequestEvent, Bot
from nonebot.typing import T_State
from .config import Config
import asyncio
import random

# 获取插件配置
plugin_config = get_plugin_config(Config)

# 注册好友请求事件处理器
friend_request = on_request(priority=5, block=True)

@friend_request.handle()
async def handle_friend_request(bot: Bot, event: FriendRequestEvent, state: T_State):
    """处理好友请求，根据配置自动同意并发送欢迎消息"""
    
    # 检查是否启用自动同意
    if not plugin_config.auto_accept_enabled:
        logger.info(f"收到来自 {event.user_id} 的好友请求，但自动同意功能已禁用")
        return
    
    try:
        # 获取请求的标识信息
        flag = event.flag
        
        # 调用OneBot接口处理好友请求(设置为同意)
        await bot.set_friend_add_request(flag=flag, approve=True)
        
        logger.info(f"已自动同意来自 {event.user_id} 的好友请求")
        
        # 如果配置了自动回复消息，则发送欢迎消息
        if plugin_config.auto_reply_message:
            # 添加随机延迟，模拟真人回复
            await asyncio.sleep(random.uniform(2, 5))
            
            try:
                # 发送欢迎消息
                await bot.send_private_msg(
                    user_id=event.user_id,
                    message=plugin_config.auto_reply_message
                )
                logger.info(f"已向新好友 {event.user_id} 发送欢迎消息")
            except Exception as e:
                logger.error(f"向新好友 {event.user_id} 发送欢迎消息失败: {e}")
    
    except Exception as e:
        logger.error(f"处理好友请求失败: {e}") 