# vorto_utils/interaction.py - User interaction utilities
from datetime import datetime


def select_accounts(sender, user_bucket, userid, auth_bucket, plugin_name):
    """账号选择交互

    Args:
        sender: middleware.Sender 对象
        user_bucket: 用户账号列表桶名 (如 's_nkfsj_user')
        userid: 用户ID
        auth_bucket: 授权桶名 (如 's_nkfsj_auth')
        plugin_name: 插件名称 (用于提示)

    Returns:
        tuple: (accounts_list, selected_list) 或 (None, None) 表示取消
               accounts_list: 所有账号列表
               selected_list: 选中的账号列表

    Examples:
        >>> accounts, selected = select_accounts(sender, 's_nkfsj_user', 'user123', 's_nkfsj_auth', '牛卡福')
        >>> if selected:
        ...     for account in selected:
        ...         print(account)
    """
    import middleware
    from vorto_utils.account import mask_account

    uservalue = middleware.bucketGet(user_bucket, userid)
    if not uservalue:
        sender.reply(f"=====未绑定账号=====\n❌ 未找到账号\n💡 发送 {plugin_name}登录 绑定\n==================")
        return None, None

    accounts = eval(uservalue)

    # 显示账号列表
    account_list = "\n========选择账号=======\n[0] 全部账号"
    for i, account in enumerate(accounts, 1):
        auth_time = middleware.bucketGet(auth_bucket, account)
        if not auth_time:
            auth_status = '未授权'
        elif auth_time < str(datetime.now().date()):
            auth_status = '已过期'
        else:
            auth_status = f'到期:{auth_time}'
        account_list += f"\n[{i}]{mask_account(account)}({auth_status})"
    account_list += "\n=====================\n支持多选，用逗号分隔\n回复\"q\"退出\n====================="
    sender.reply(account_list)

    # 等待选择
    choice = sender.input(120000, 1, False)
    if not choice or choice.lower() == 'q':
        sender.reply("✅ 已退出")
        return None, None

    # 解析选择
    try:
        if choice == '0':
            return accounts, accounts.copy()
        else:
            selected = [
                accounts[int(idx.strip()) - 1]
                for idx in choice.split(',')
                if idx.strip().isdigit() and 0 <= int(idx.strip()) - 1 < len(accounts)
            ]
            if not selected:
                sender.reply("❌ 未选择有效账号")
                return None, None
            return accounts, selected
    except Exception as e:
        sender.reply(f"❌ 选择失败: {str(e)}")
        return None, None
