import random
import asyncio
import aiohttp
from loguru import logger

from tonutils.client import ToncenterV3Client
from tonutils.utils import to_amount
from tonutils.wallet import WalletV4R2

# 日志尽量减少 IO
logger.add("wallet_log_{time:YYYY-MM-DD}.log", rotation="1 day", retention="30 days")

API_KEY = "AFMEX4F23ZRPOUIAAAAPHGIE5QECWZA5M75E54VD72O5IJEGP5IW3LOTXO7Z4QOX7MV6JQQ"
IS_TESTNET = False

headers = {
    "accept": "*/*",
    "authorization": "Bearer AFPJTKEBPOX3AIYAAAAKA2HWOTRNJP5MUCV5DMDCZAAOCPSAYEYS3CILNQVLF2HWKED6US",
    "content-type": "application/json",
    "user-agent": "Mozilla/5.0",
}

# 全局复用 Toncenter client
client = ToncenterV3Client(is_testnet=IS_TESTNET, rps=10, max_retries=1)


async def get_balance(session, address: str):
    url = f"https://tonapi.io/v2/accounts/{address}"

    for _ in range(8):  # 降低重试次数提升速度
        try:
            async with session.get(url, headers=headers, timeout=3) as r:
                data = await r.json()
                return to_amount(int(data.get("balance", 0)))
        except Exception:
            await asyncio.sleep(0.05)  # 小延迟即可
    return None


async def handle_wallet(session, idx: int):
    wallet, public_key, private_key, mnemonic = WalletV4R2.create(client)
    address = wallet.address.to_str(
        is_user_friendly=True,
        is_url_safe=True,
        is_bounceable=False,
        is_test_only=False
    )

    balance = await get_balance(session, address)

    if balance:
        logger.info(f"[{idx}] Balance={balance} | {address} | Mnemonic={' '.join(mnemonic)}")
    else:
        print(f"[{idx}] 余额查询失败 | {address}，余额：{balance}")


async def worker(worker_id, session, queue):
    while True:
        idx = await queue.get()
        await handle_wallet(session, idx)
        queue.task_done()


async def main():
    queue = asyncio.Queue()

    # 单一 Session 复用，性能最优
    async with aiohttp.ClientSession() as session:

        # 启动固定数量 Worker，提高并行效率
        workers = [asyncio.create_task(worker(i, session, queue)) for i in range(20)]

        counter = 0
        while True:
            counter += 1
            await queue.put(counter)

            # 控制生成速度
            await asyncio.sleep(0.01)

        for w in workers:
            w.cancel()


if __name__ == "__main__":
    asyncio.run(main())
#  .\xray.exe -c .\1_5000_client_am_ip_1v1.json