#!/usr/bin/env python3
"""
jm 28209           取号+等码，回车换号
jm 28209 --phone   只取号
Windows版
"""
import sys, time, platform, subprocess, threading
from haozhuma import HaozhuClient
from haozhuma.exceptions import HaozhuAPIError

U = "b07aeabae914a8be738de242b362772ba22b6fd42ab909fd4750b3ec6a4a6ca5"
P = "e765b595674aded94ce192c5538759f4eb75f6ec5d3537d596c50822de5c34f9"

def copy(text):
    if platform.system() == "Windows":
        subprocess.run(["clip"], input=text.encode("utf-16le"), check=False)
    elif platform.system() == "Darwin":
        subprocess.run(["pbcopy"], input=text.encode())
    else:
        subprocess.run(["xclip", "-selection", "clipboard"], input=text.encode(), check=False)

def kbhit():
    if platform.system() == "Windows":
        import msvcrt
        return msvcrt.kbhit()
    else:
        import select
        return select.select([sys.stdin], [], [], 0)[0]

def flush_input():
    """清空stdin缓冲区，防止连续换号"""
    if platform.system() == "Windows":
        import msvcrt
        while msvcrt.kbhit():
            msvcrt.getwch()
    else:
        import select
        while select.select([sys.stdin], [], [], 0)[0]:
            sys.stdin.readline()

if __name__ == "__main__":
    import argparse
    pa = argparse.ArgumentParser()
    pa.add_argument("sid")
    pa.add_argument("--phone", action="store_true")
    args = pa.parse_args()

    with HaozhuClient(username=U, password=P) as c:
        if args.phone:
            num = c.get_phone(sid=args.sid)
            copy(num)
            print(f"{num}  ✅已复制")
            sys.exit()

        while True:
            try:
                phone = c.get_phone(sid=args.sid)
            except HaozhuAPIError as e:
                print(f"取号失败: {e}")
                input("回车重试...")
                continue

            copy(phone)
            print(f"号码: {phone}  ✅已复制  (回车换号)")

            result = {"code": "", "done": False}
            def poll():
                try:
                    r = c.poll_message(phone=phone, sid=args.sid, timeout=180, interval=5)
                    result["code"] = r.sms_code or ""
                except:
                    pass
                result["done"] = True

            t = threading.Thread(target=poll, daemon=True)
            t.start()

            spin = "|/-\\"
            i = 0
            while not result["done"]:
                if kbhit():
                    flush_input()
                    print("\n换号...")
                    break
                m, s = divmod(i, 60)
                sys.stdout.write(f"\r  {spin[i % 4]} 等待验证码... {m:02d}:{s:02d}  ")
                sys.stdout.flush()
                time.sleep(1)
                i += 1
            else:
                if result["code"]:
                    copy(result["code"])
                    print(f"\n\n验证码: {result['code']}  ✅已复制")
                    input("回车换号，Ctrl+C退出...")
                else:
                    print("\n\n超时(3分钟)")
                    input("回车换号...")
