# vorto_utils/admin.py - Administrator authorization utilities
import json


def admin_auth_all_accounts(sender, user_bucket, auth_bucket, token_bucket, update_ql_callback):
    """管理员批量授权所有用户

    Args:
        sender: middleware.Sender 对象
        user_bucket: 用户账号列表桶名 (如 's_nkfsj_user')
        auth_bucket: 授权桶名 (如 's_nkfsj_auth')
        token_bucket: Token桶名 (如 's_nkfsj_token')
        update_ql_callback: 更新青龙的回调函数 update_ql_env(account, account_info)

    Examples:
        >>> def update_ql(acc, info):
        ...     return True
        >>> admin_auth_all_accounts(sender, 's_nkfsj_user', 's_nkfsj_auth', 's_nkfsj_token', update_ql)
    """
    import middleware
    from vorto_utils.auth import calculate_auth_time

    all_users_keys = middleware.bucketAllKeys(user_bucket)
    if isinstance(all_users_keys, str):
        all_users_keys = [k.strip() for k in all_users_keys.split(',') if k.strip()]

    all_users = [
        {'id': str(k).strip(), 'accounts': eval(middleware.bucketGet(user_bucket, str(k).strip()) or '[]')}
        for k in all_users_keys
    ] if all_users_keys else []

    if not all_users:
        sender.reply("❌ 无用户")
        return

    total_accs = sum(len(u['accounts']) for u in all_users)
    sender.reply(
        f"=====授权所有用户=====\n"
        f"👥 用户数: {len(all_users)}\n"
        f"📊 账号数: {total_accs}\n"
        f"------------------\n"
        f"请输入授权天数:\n"
        f"(正数增加天数，负数减少天数)\n"
        f"回复\"q\"退出"
    )

    days_input = sender.input(120000, 1, False)
    if not days_input or days_input.lower() == 'q':
        sender.reply("✅ 已取消授权")
        return

    try:
        days = int(days_input)
    except ValueError:
        sender.reply("❌ 无效的天数")
        return

    action_text = f"增加 {days} 天" if days > 0 else f"减少 {abs(days)} 天"
    sender.reply(
        f"=====确认授权=====\n"
        f"👥 用户数: {len(all_users)}\n"
        f"📊 账号数: {total_accs}\n"
        f"⏰ 操作: {action_text}\n"
        f"------------------\n"
        f"⚠️ 此操作影响所有用户\n"
        f"回复\"y\"确认\n"
        f"回复其他取消"
    )

    confirm = sender.input(120000, 1, False)
    if not confirm or confirm.lower() != 'y':
        sender.reply("✅ 已取消授权")
        return

    success = 0
    fail = 0
    for u in all_users:
        for acc in u['accounts']:
            try:
                info = json.loads(middleware.bucketGet(token_bucket, acc))
                new_auth_time = calculate_auth_time(auth_bucket, acc, days=days)
                middleware.bucketSet(auth_bucket, acc, new_auth_time)
                if update_ql_callback:
                    update_ql_callback(acc, info)
                success += 1
            except:
                fail += 1

    sender.reply(
        f"=====授权结果=====\n"
        f"✅ 成功: {success} 个账号\n"
        f"❌ 失败: {fail} 个账号\n"
        f"⏰ 操作: {action_text}\n"
        f"=================="
    )


def admin_auth_by_user(sender, user_bucket, auth_bucket, token_bucket, update_ql_callback):
    """管理员按用户授权

    Args:
        sender: middleware.Sender 对象
        user_bucket: 用户账号列表桶名 (如 's_nkfsj_user')
        auth_bucket: 授权桶名 (如 's_nkfsj_auth')
        token_bucket: Token桶名 (如 's_nkfsj_token')
        update_ql_callback: 更新青龙的回调函数 update_ql_env(account, account_info)

    Examples:
        >>> def update_ql(acc, info):
        ...     return True
        >>> admin_auth_by_user(sender, 's_nkfsj_user', 's_nkfsj_auth', 's_nkfsj_token', update_ql)
    """
    import middleware
    from vorto_utils.auth import calculate_auth_time
    from vorto_utils.account import mask_account

    sender.reply(
        "=====按用户授权=====\n"
        "请输入用户ID:\n"
        "回复\"q\"退出"
    )

    target_id = sender.input(120000, 1, False)
    if not target_id or target_id.lower() == 'q':
        sender.reply("✅ 已退出")
        return

    accounts = eval(middleware.bucketGet(user_bucket, target_id) or '[]')
    if not accounts:
        sender.reply(f"❌ 用户 {target_id} 没有绑定任何账号")
        return

    account_list = f"=====用户 {target_id} 的账号=====\n[0] 选择全部账号\n"
    for i, acc in enumerate(accounts, 1):
        auth_time = middleware.bucketGet(auth_bucket, acc) or '未授权'
        account_list += f"[{i}] {mask_account(acc)} - {auth_time}\n"

    account_list += "------------------\n支持多选，用逗号分隔\n回复\"q\"退出"
    sender.reply(account_list)

    account_choice = sender.input(120000, 1, False)
    if not account_choice or account_choice.lower() == 'q':
        sender.reply("✅ 已取消授权")
        return

    selected = []
    if account_choice == '0':
        selected = accounts.copy()
    else:
        try:
            indices = [int(idx.strip()) - 1 for idx in account_choice.split(',') if idx.strip().isdigit()]
            for index in indices:
                if 0 <= index < len(accounts):
                    selected.append(accounts[index])
        except:
            sender.reply("❌ 无效的选择格式")
            return

    if not selected:
        sender.reply("❌ 未选择任何账号")
        return

    sender.reply(
        f"已选择 {len(selected)} 个账号\n"
        f"请输入授权天数:\n"
        f"(正数增加天数，负数减少天数)\n"
        f"回复\"q\"退出"
    )

    days_input = sender.input(120000, 1, False)
    if not days_input or days_input.lower() == 'q':
        sender.reply("✅ 已取消授权")
        return

    try:
        days = int(days_input)
    except ValueError:
        sender.reply("❌ 无效的天数")
        return

    action_text = f"增加 {days} 天" if days > 0 else f"减少 {abs(days)} 天"
    sender.reply(
        f"=====确认授权=====\n"
        f"📊 账号数: {len(selected)} 个\n"
        f"⏰ 操作: {action_text}\n"
        f"------------------\n"
        f"回复\"y\"确认\n"
        f"回复其他取消"
    )

    confirm = sender.input(120000, 1, False)
    if not confirm or confirm.lower() != 'y':
        sender.reply("✅ 已取消授权")
        return

    success = 0
    fail = 0
    for acc in selected:
        try:
            info = json.loads(middleware.bucketGet(token_bucket, acc))
            new_auth_time = calculate_auth_time(auth_bucket, acc, days=days)
            middleware.bucketSet(auth_bucket, acc, new_auth_time)
            if update_ql_callback:
                update_ql_callback(acc, info)
            success += 1
        except:
            fail += 1

    sender.reply(
        f"=====授权结果=====\n"
        f"✅ 成功: {success} 个账号\n"
        f"❌ 失败: {fail} 个账号\n"
        f"⏰ 操作: {action_text}\n"
        f"=================="
    )
