# vorto_utils/monitor.py - Authorization monitoring and cleanup utilities
from datetime import datetime


def check_auth_status(config_bucket, user_bucket, auth_bucket, token_bucket, plugin_name, delete_ql_callback=None):
    """检测授权状态并清理过期账号

    Args:
        config_bucket: 配置桶名 (如 's_nkfsj')
        user_bucket: 用户账号列表桶名 (如 's_nkfsj_user')
        auth_bucket: 授权桶名 (如 's_nkfsj_auth')
        token_bucket: Token桶名 (如 's_nkfsj_token')
        plugin_name: 插件名称
        delete_ql_callback: 删除青龙变量的回调函数 delete_ql_env(account)

    Returns:
        str: 检测结果消息

    Examples:
        >>> def delete_ql(acc):
        ...     return True
        >>> result = check_auth_status('s_nkfsj', 's_nkfsj_user', 's_nkfsj_auth', 's_nkfsj_token', '牛卡福', delete_ql)
        >>> print(result)
        '✅ 检测完成，共 10 个账号，发送 2 条通知，清理 1 个过期账号'
    """
    import middleware
    from vorto_utils.account import mask_account

    notify = middleware.bucketGet(config_bucket, 'notify') or ''
    if not notify:
        return "❌ 未配置通知渠道"

    channels = [c.strip() for c in notify.split(',') if c.strip()]
    all_users = middleware.bucketAllKeys(user_bucket)
    if not all_users:
        return "❌ 没有用户"

    # 确保 all_users 是列表
    if isinstance(all_users, str):
        all_users = [k.strip() for k in all_users.split(',') if k.strip()]

    notify_days = int(middleware.bucketGet(config_bucket, 'notify_days') or '3')
    current_date = datetime.now().date()
    total, notified, cleaned = 0, 0, 0

    for raw_user_id in all_users:
        try:
            user_id = str(raw_user_id).strip()
            accounts = eval(middleware.bucketGet(user_bucket, user_id) or '[]')

            to_notify = []
            to_clean = []

            for acc in accounts:
                auth_time_str = middleware.bucketGet(auth_bucket, acc)

                if not auth_time_str:
                    to_clean.append({'account': acc, 'auth_time': '未授权', 'days_left': 0})
                    continue

                try:
                    auth_date = datetime.strptime(auth_time_str, "%Y-%m-%d").date()
                    days_left = (auth_date - current_date).days

                    if days_left <= 0:
                        to_clean.append({'account': acc, 'auth_time': auth_time_str, 'days_left': days_left})
                    elif days_left <= notify_days:
                        to_notify.append({'account': acc, 'auth_time': auth_time_str, 'days_left': days_left})
                except:
                    to_clean.append({'account': acc, 'auth_time': auth_time_str, 'days_left': 0})

            total += len(accounts)

            # 清理过期账号
            if to_clean:
                for exp_acc in to_clean:
                    account = exp_acc['account']
                    if delete_ql_callback:
                        delete_ql_callback(account)
                    middleware.bucketDel(token_bucket, account)
                    if account in accounts:
                        accounts.remove(account)
                    middleware.bucketDel(auth_bucket, account)
                    cleaned += 1

                if accounts:
                    middleware.bucketSet(user_bucket, user_id, str(accounts))
                else:
                    middleware.bucketDel(user_bucket, user_id)

            # 推送提醒
            if to_notify:
                notify_list = "\n".join([
                    f"📱 {mask_account(a['account'])} 剩余{a['days_left']}天({a['auth_time']})"
                    for a in to_notify
                ])
                msg = (
                    f"====={plugin_name}账号检测=====\n"
                    f"⚠️ 即将过期:\n{notify_list}\n"
                    f"💡 发送\"{plugin_name}管理\"续费\n"
                    f"=================="
                )
                for ch in channels:
                    try:
                        middleware.push(imType=ch, groupCode='', userID=user_id, title="", content=msg)
                        notified += 1
                    except:
                        pass
        except:
            pass

    return f"✅ 检测完成，共 {total} 个账号，发送 {notified} 条通知，清理 {cleaned} 个过期账号"
