# vorto_utils/auth.py - Authorization management utilities
from datetime import datetime, timedelta


def calculate_auth_time(auth_bucket, account, months=0, days=0):
    """计算授权到期时间

    Args:
        auth_bucket: 授权桶名 (如 's_nkfsj_auth')
        account: 账号标识
        months: 增加月数（可为负数）
        days: 增加天数（可为负数）

    Returns:
        str: 新的到期日期字符串 YYYY-MM-DD

    Examples:
        >>> calculate_auth_time('s_nkfsj_auth', '13800138000', months=1)
        '2026-04-15'
        >>> calculate_auth_time('s_nkfsj_auth', '13800138000', days=7)
        '2026-03-22'
    """
    import middleware

    dqsj = datetime.now().strftime("%Y-%m-%d")
    accountVip = middleware.bucketGet(auth_bucket, account)

    if accountVip and accountVip > dqsj:
        start_date = datetime.strptime(accountVip, "%Y-%m-%d")
    else:
        start_date = datetime.now()

    new_expire = start_date + timedelta(days=30 * months + days)
    return new_expire.strftime("%Y-%m-%d")


def process_authorization(sender, auth_bucket, account, account_info, months, update_ql_callback=None):
    """处理授权

    Args:
        sender: middleware.Sender 对象
        auth_bucket: 授权桶名 (如 's_nkfsj_auth')
        account: 账号标识
        account_info: 账号信息字典
        months: 授权月数
        update_ql_callback: 更新青龙的回调函数 update_ql_env(account, account_info)

    Returns:
        bool: 是否成功

    Examples:
        >>> def update_ql(acc, info):
        ...     return True
        >>> process_authorization(sender, 's_nkfsj_auth', '13800138000', {}, 1, update_ql)
        True
    """
    import middleware
    from vorto_utils.account import mask_account

    try:
        new_expire = calculate_auth_time(auth_bucket, account, months=months)
        middleware.bucketSet(auth_bucket, account, new_expire)

        if update_ql_callback:
            update_ql_callback(account, account_info)

        sender.reply(
            f"=====授权成功=====\n"
            f"📱 账号: {mask_account(account)}\n"
            f"📅 到期: {new_expire}\n"
            f"=================="
        )
        return True
    except Exception as e:
        sender.reply(f"授权异常: {str(e)}")
        return False


def get_user_points(user_id):
    """获取用户积分 (从 dd_sign_points 桶)

    Args:
        user_id: 用户ID

    Returns:
        int: 用户积分，失败返回 0
    """
    import middleware
    try:
        points = middleware.bucketGet('dd_sign_points', str(user_id))
        return int(points) if points else 0
    except Exception as e:
        print(f"获取用户积分失败: {str(e)}")
        return 0


def update_user_points(user_id, new_points):
    """更新用户积分到 dd_sign_points 桶

    Args:
        user_id: 用户ID
        new_points: 新的积分值

    Returns:
        bool: 是否成功
    """
    import middleware
    try:
        middleware.bucketSet('dd_sign_points', str(user_id), str(int(new_points)))
        return True
    except Exception as e:
        print(f"更新用户积分失败: {str(e)}")
        return False


def process_coin_payment(sender, userid, auth_bucket, account, account_info, months, coin_per_month, auth_callback):
    """积分支付处理

    Args:
        sender: middleware.Sender 对象
        userid: 用户ID
        auth_bucket: 授权桶名 (如 's_nkfsj_auth')
        account: 账号标识
        account_info: 账号信息
        months: 授权月数
        coin_per_month: 每月所需积分
        auth_callback: 授权回调函数 auth_callback(account, account_info, months)

    Returns:
        bool: 是否成功

    Examples:
        >>> def auth_cb(acc, info, m):
        ...     return True
        >>> process_coin_payment(sender, 'user123', 's_nkfsj_auth', '13800138000', {}, 1, 100, auth_cb)
        True
    """
    try:
        required = months * coin_per_month
        user_coins = get_user_points(userid)

        if user_coins < required:
            sender.reply(
                f"=====积分不足=====\n"
                f"❌ 当前: {user_coins}\n"
                f"💰 需要: {required}\n"
                f"=================="
            )
            return False

        new_balance = user_coins - required
        if not update_user_points(userid, new_balance):
            sender.reply("❌ 积分扣除失败，请联系管理员")
            return False

        if auth_callback(account, account_info, months):
            sender.reply(
                f"=====积分兑换成功=====\n"
                f"✅ 扣除: {required}\n"
                f"💰 剩余: {new_balance}\n"
                f"=================="
            )
            return True

        # 授权失败回滚积分
        update_user_points(userid, user_coins)
        return False
    except Exception as e:
        sender.reply(f"积分兑换异常: {str(e)}")
        return False
