"""
抽卡命令处理模块

处理单次抽卡命令，包括：
- 参数解析（子池选择）
- 抽卡执行
- SSR/SP奖励处理
- 成就检查
- 消息发送
"""

from typing import Dict, Any
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent
from nonebot.params import CommandArg
from nonebot.adapters.onebot.v11 import Message
import nonebot
import random

from ..config import Config
from ..utils import get_gacha_system
from .. import formatters
from ..api_utils import process_ssr_sp_reward
from ..utils import format_user_mention, build_achievement_notify, get_user_name

logger = nonebot.logger


async def handle_gacha(bot: Bot, event: MessageEvent, state: dict, args: Message = CommandArg()):
    """处理抽卡命令"""
    user_id = str(event.user_id)
    user_name = get_user_name(event)
    
    # 解析子池参数
    sub_pool = args.extract_plain_text().strip()
    
    # 执行抽卡
    gacha_system = get_gacha_system()
    result = await gacha_system.draw(user_id, sub_pool=sub_pool if sub_pool else None)
    
    if not result["success"]:
        await event.finish(result["message"])
    
    rarity, shikigami, image_url = result["rarity"], result["name"], result["image"]
    
    # 发送抽卡结果
    msg = formatters.format_gacha_result(rarity, shikigami, user_id, user_name, image_url)
    await event.send(msg)
    
    # SSR/SP奖励处理
    if rarity in ["SSR", "SP"]:
        group_id = str(event.group_id) if isinstance(event, GroupMessageEvent) else None
        reward_msg = await process_ssr_sp_reward(user_id, user_name, rarity, shikigami, group_id)
        if reward_msg:
            await event.send(reward_msg)
    
    # 成就检查（使用统一编排函数）
    unlocked = await gacha_system.check_achievements(user_id)
    if unlocked:
        achievement_msg = await build_achievement_notify(user_id, unlocked)
        if achievement_msg:
            await event.send(achievement_msg)
    
