import requests
import random
import string
import json
from time import sleep
from requests.adapters import HTTPAdapter

# -------------------------- 配置信息 --------------------------
REGISTER_URL = "https://my.wavwo.com/SProUsers/userRegister"
# 单次运行创建账号数量
CREATE_NUM = 2147483647
# 请求延迟范围（秒）
DELAY_RANGE = (0.001, 0.002)
# 固定TOKEN（失效后重新抓包获取）
TOKEN = "fhhvtqyktl90eb576aa4da20f750f8269b81fb8e96"
# 邮箱域名池
EMAIL_DOMAINS = ["example.com", "test.com", "mail.com", "demo.com"]
# 自定义账号前缀
ACCOUNT_PREFIX = "RTE"
# 起始编号（每次运行可手动修改，或读取文件自动延续）
START_NUM = 3208
# 邀请码（先尝试加入请求，若提示参数错误则说明接口暂不支持）
INVITE_CODE = "lrdpsP7w"
# -----------------------------------------------------------------------

def generate_password(min_len=8, max_len=16):
    """生成随机密码"""
    allowed_chars = string.ascii_letters + string.digits
    return ''.join(random.choices(allowed_chars, k=random.randint(min_len, max_len)))

def generate_valid_email(account):
    """生成合规邮箱"""
    domain = random.choice(EMAIL_DOMAINS)
    return f"{account}@{domain}"

def create_account(account_name):
    """创建单个账号"""
    password = generate_password()
    mail = generate_valid_email(account_name)

    headers = {
        "User-Agent": f"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{random.randint(120, 125)}.0.0.0 Safari/537.36",
        "Referer": "https://my.wavwo.com/",
        "Origin": "https://my.wavwo.com",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Accept": "*/*",
        "Accept-Language": "zh-CN,zh;q=0.9"
    }

    # 构造请求数据，加入邀请码字段尝试
    params_data = {
        "name": account_name,
        "password": password,
        "mail": mail,
        "inviteCode": INVITE_CODE  # 尝试添加邀请码，若报错则说明接口无此字段
    }
    data = {
        "params": json.dumps(params_data, separators=(',', ':')),
        "token": TOKEN
    }

    try:
        session = requests.Session()
        session.mount("https://", HTTPAdapter(max_retries=1))
        response = session.post(REGISTER_URL, data=data, headers=headers, timeout=20)
        resp_text = response.text.strip()

        if "账号已存在" in resp_text:
            print(f"⚠️ 账号[{account_name}]已存在，跳过")
            return None
        elif "参数错误" in resp_text:
            print(f"❌ 账号[{account_name}]创建失败，参数错误（可能TOKEN失效或邀请码字段不支持）")
            # 若因邀请码报错，自动去掉该字段重试
            params_data.pop("inviteCode")
            data["params"] = json.dumps(params_data, separators=(',', ':'))
            response = session.post(REGISTER_URL, data=data, headers=headers, timeout=20)
            resp_text = response.text.strip()
            if "注册成功" in resp_text:
                print(f"✅ 去掉邀请码后，账号[{account_name}]创建成功 - 密码：{password} - 邮箱：{mail}")
                return {"name": account_name, "password": password, "mail": mail}
            else:
                print(f"❌ 重试后仍失败：{resp_text}")
                return None
        elif "注册成功" in resp_text or "创建成功" in resp_text:
            print(f"✅ 账号[{account_name}]创建成功 - 密码：{password} - 邮箱：{mail} - 邀请码：{INVITE_CODE}")
            return {"name": account_name, "password": password, "mail": mail}
        else:
            print(f"ℹ️ 账号[{account_name}]响应未知：{resp_text}")
            return None
    except Exception as e:
        print(f"❌ 账号[{account_name}]创建异常：{str(e)}")
        return None

def batch_create_accounts():
    """批量创建自定义名称账号"""
    success_list = []
    current_num = START_NUM
    print(f"=== 开始批量创建{CREATE_NUM}个账号，前缀[{ACCOUNT_PREFIX}]，起始编号[{START_NUM}] ===")
    
    for i in range(CREATE_NUM):
        account_name = f"{ACCOUNT_PREFIX}{current_num}"
        print(f"\n--- 第{i+1}个账号：{account_name} ---")
        sleep(random.uniform(*DELAY_RANGE))
        res = create_account(account_name)
        if res:
            success_list.append(res)
        current_num += 1  # 编号每次加1
    
    # 保存最后编号，下次可直接使用
    with open("last_num.txt", "w", encoding="utf-8") as f:
        f.write(str(current_num))
    print(f"\n=== 任务完成！成功创建{len(success_list)}个账号 ===")
    print(f"下次运行建议将START_NUM设为[{current_num}]")
    
    with open("created_accounts.txt", "w", encoding="utf-8") as f:
        for acc in success_list:
            f.write(f"账号：{acc['name']} | 密码：{acc['password']} | 邮箱：{acc['mail']}\n")
    print("成功账号已保存到created_accounts.txt")

if __name__ == "__main__":
    try:
        import requests
    except ImportError:
        print("请先安装依赖：pip install requests")
    else:
        # 可选：自动读取上次最后编号，实现连续创建
        try:
            with open("last_num.txt", "r", encoding="utf-8") as f:
                START_NUM = int(f.read().strip())
                print(f"检测到上次最后编号：{START_NUM}，将从该编号继续创建")
        except FileNotFoundError:
            print("未检测到历史编号，将从起始编号[{START_NUM}]开始创建")
        batch_create_accounts()
