# -*- coding:utf-8 -*-

from cookie import suno_auths
from utils import get_credits
import logging
import asyncio

async def get_token():
    disabled_accounts = set()
    
    while True:
        for i, suno_auth in sorted(suno_auths.items()):
            if suno_auth.is_disabled or i in disabled_accounts:
                continue

            token = suno_auth.get_token()

            try:
                credits_info = await get_credits(token)
                credits = credits_info.get('credits_left', 0)
                logging.info(f"当前账号 {suno_auth.get_session_id()} 积分: {credits}")
                
                if credits > 5:
                    return token
            except Exception as e:
                logging.error(f"账号 {suno_auth.get_session_id()} 获取积分失败: {e}")
                suno_auth.disable()
                disabled_accounts.add(i)
        
        if len(disabled_accounts) == len(suno_auths):
            logging.warning("所有账号都已被禁用,等待 1 小时后重试...")
            await asyncio.sleep(3600)  # 等待1小时 (3600秒)
            # 重置所有账号的禁用状态
            for suno_auth in suno_auths.values():
                suno_auth.enable()
            disabled_accounts.clear()
        else:
            logging.warning("所有可用账号积分已用尽,等待 1 小时后重试...")
            await asyncio.sleep(3600)  # 等待1小时 (3600秒)

# 在程序启动时重置所有账号的禁用状态
def reset_account_status():
    for suno_auth in suno_auths.values():
        suno_auth.enable()

# 确保在主程序中调用此函数
reset_account_status()