Spaces:
Paused

File size: 45,581 Bytes
cc440c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
"""
codex.py - ChatGPT 自动注册 + CPA OAuth 喂养工具
注册部分: curl_cffi 纯 HTTP 方式 (参考 chatgpt_register.py)
CPA 部分: Selenium 浏览器自动化
"""

import os
import re
import uuid
import json
import random
import string
import time
import csv
import threading
from urllib.parse import urlparse, parse_qs

from curl_cffi import requests as curl_requests

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

# ================= 代理轮换配置 =================

def _load_working_proxies():
    """从文件加载可用代理列表"""
    try:
        proxy_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "working_proxies.txt")
        if os.path.exists(proxy_file):
            with open(proxy_file, "r", encoding="utf-8") as f:
                proxies = [line.strip() for line in f if line.strip()]
            print(f"[*] 已加载 {len(proxies)} 个可用代理")
            return proxies
    except Exception as e:
        print(f"[!] 加载代理文件失败: {e}")
    return []

# 可用代理列表
_PROXY_LIST = _load_working_proxies()
_proxy_index = 0
_proxy_lock = threading.Lock()

def get_next_proxy():
    """获取下一个代理(轮换),优先选择 papipa.cc.cd 后缀的代理"""
    global _proxy_index
    with _proxy_lock:
        if not _PROXY_LIST:
            return None
        
        # 分离优先代理和普通代理
        priority_proxies = [p for p in _PROXY_LIST if "papipa.cc.cd" in p]
        other_proxies = [p for p in _PROXY_LIST if "papipa.cc.cd" not in p]
        
        # 优先使用 papipa.cc.cd 代理
        if priority_proxies:
            proxy = priority_proxies[_proxy_index % len(priority_proxies)]
            print(f"[*] 使用优先代理 (papipa.cc.cd): {proxy}")
        else:
            proxy = other_proxies[_proxy_index % len(other_proxies)] if other_proxies else _PROXY_LIST[_proxy_index % len(_PROXY_LIST)]
        
        _proxy_index += 1
        return proxy


def random_delay_between_accounts():
    """每5个账号后随机休眠 30秒~3分钟"""
    delay = random.randint(30, 180)  # 30秒到180秒(3分钟)
    mins = delay // 60
    secs = delay % 60
    print(f"\n[*] 已注册5个账号,随机休眠 {mins}分{secs}秒 后继续...")
    time.sleep(delay)


# ================= 加载配置 =================

def load_config():
    """从 config.json 加载配置,环境变量优先级更高"""
    config = {
        "total_accounts": 5,
        "duckmail_api_base": "https://api.duckmail.sbs",
        "duckmail_bearer": "",
        "proxy": "",
        "cli_proxy_management_url": "http://127.0.0.1:8317/management.html#/oauth",
        "cli_proxy_api_base": "http://127.0.0.1:8317",
        "cli_proxy_password": "",
        "accounts_file": "accounts.txt",
        "csv_file": "registered_accounts.csv",
    }

    config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
    if os.path.exists(config_path):
        try:
            with open(config_path, "r", encoding="utf-8") as f:
                file_config = json.load(f)
                config.update(file_config)
        except Exception as e:
            print(f"[!] 加载 config.json 失败: {e}")
    else:
        print(f"[!] config.json 未找到: {config_path}")

    # 环境变量优先级更高
    config["duckmail_api_base"] = os.environ.get("DUCKMAIL_API_BASE", config["duckmail_api_base"])
    config["duckmail_bearer"] = os.environ.get("DUCKMAIL_BEARER", config["duckmail_bearer"])
    config["proxy"] = os.environ.get("PROXY", config["proxy"])
    config["total_accounts"] = int(os.environ.get("TOTAL_ACCOUNTS", config["total_accounts"]))

    return config


_config = load_config()

TOTAL_ACCOUNTS = _config["total_accounts"]
DUCKMAIL_API_BASE = _config["duckmail_api_base"]
DUCKMAIL_BEARER = _config["duckmail_bearer"]
PROXY = _config["proxy"]

# CPA 配置
CLI_PROXY_MANAGEMENT_URL = _config["cli_proxy_management_url"]
CLI_PROXY_API_BASE = _config["cli_proxy_api_base"]
CLI_PROXY_PASSWORD = _config["cli_proxy_password"]

# 输出文件
ACCOUNTS_FILE = _config["accounts_file"]
CSV_FILE = _config["csv_file"]

if not DUCKMAIL_BEARER:
    print("[!] 警告: 未设置 duckmail_bearer,请在 config.json 中设置或设置环境变量 DUCKMAIL_BEARER")

# 全局线程锁 (日志/文件)
_print_lock = threading.Lock()


# ================= Chrome 指纹配置 =================

_CHROME_PROFILES = [
    {
        "major": 131, "impersonate": "chrome131",
        "build": 6778, "patch_range": (69, 205),
        "sec_ch_ua": '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
    },
    {
        "major": 133, "impersonate": "chrome133a",
        "build": 6943, "patch_range": (33, 153),
        "sec_ch_ua": '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
    },
    {
        "major": 136, "impersonate": "chrome136",
        "build": 7103, "patch_range": (48, 175),
        "sec_ch_ua": '"Chromium";v="136", "Google Chrome";v="136", "Not.A/Brand";v="99"',
    },
    {
        "major": 142, "impersonate": "chrome142",
        "build": 7540, "patch_range": (30, 150),
        "sec_ch_ua": '"Chromium";v="142", "Google Chrome";v="142", "Not_A Brand";v="99"',
    },
]


def _random_chrome_version():
    profile = random.choice(_CHROME_PROFILES)
    major = profile["major"]
    build = profile["build"]
    patch = random.randint(*profile["patch_range"])
    full_ver = f"{major}.0.{build}.{patch}"
    ua = (
        f"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
        f"(KHTML, like Gecko) Chrome/{full_ver} Safari/537.36"
    )
    return profile["impersonate"], major, full_ver, ua, profile["sec_ch_ua"]


def _random_delay(low=0.3, high=1.0):
    time.sleep(random.uniform(low, high))


def _make_trace_headers():
    trace_id = random.randint(10**17, 10**18 - 1)
    parent_id = random.randint(10**17, 10**18 - 1)
    tp = f"00-{uuid.uuid4().hex}-{format(parent_id, '016x')}-01"
    return {
        "traceparent": tp, "tracestate": "dd=s:1;o:rum",
        "x-datadog-origin": "rum", "x-datadog-sampling-priority": "1",
        "x-datadog-trace-id": str(trace_id), "x-datadog-parent-id": str(parent_id),
    }


def _generate_password(length=14):
    lower = string.ascii_lowercase
    upper = string.ascii_uppercase
    digits = string.digits
    special = "!@#$%&*"
    pwd = [random.choice(lower), random.choice(upper),
           random.choice(digits), random.choice(special)]
    all_chars = lower + upper + digits + special
    pwd += [random.choice(all_chars) for _ in range(length - 4)]
    random.shuffle(pwd)
    return "".join(pwd)


def _random_name():
    first = random.choice([
        "James", "Emma", "Liam", "Olivia", "Noah", "Ava", "Ethan", "Sophia",
        "Lucas", "Mia", "Mason", "Isabella", "Logan", "Charlotte", "Alexander",
        "Amelia", "Benjamin", "Harper", "William", "Evelyn", "Henry", "Abigail",
        "Sebastian", "Emily", "Jack", "Elizabeth", "Michael", "David", "Richard",
        "Mary", "Patricia", "Jennifer", "Linda", "Barbara", "Susan", "Jessica",
        "Sarah", "Karen", "Lisa", "Nancy", "Betty", "Margaret", "Sandra",
    ])
    last = random.choice([
        "Smith", "Johnson", "Brown", "Davis", "Wilson", "Moore", "Taylor",
        "Clark", "Hall", "Young", "Anderson", "Thomas", "Jackson", "White",
        "Harris", "Martin", "Thompson", "Garcia", "Robinson", "Lewis",
        "Walker", "Allen", "King", "Wright", "Scott", "Green", "Adams",
        "Nelson", "Baker", "Rivera", "Campbell", "Mitchell", "Hill",
    ])
    return f"{first} {last}"


def _random_birthdate():
    y = random.randint(1985, 2002)
    m = random.randint(1, 12)
    d = random.randint(1, 28)
    return f"{y}-{m:02d}-{d:02d}"


# ================= 账号保存 =================

def save_account(email: str, password: str):
    """保存账号到 txt + csv"""
    try:
        with open(ACCOUNTS_FILE, "a", encoding="utf-8") as f:
            f.write(f"{email}:{password}\n")

        file_exists = os.path.exists(CSV_FILE)
        with open(CSV_FILE, "a", newline="", encoding="utf-8") as f:
            writer = csv.writer(f)
            if not file_exists:
                writer.writerow(["email", "password", "timestamp"])
            writer.writerow([email, password, time.strftime("%Y-%m-%d %H:%M:%S")])

        print(f"[OK] 账号已保存到 {ACCOUNTS_FILE} 和 {CSV_FILE}")
    except Exception as e:
        print(f"[!] 保存账号失败: {e}")


# ================= ChatGPT 注册类 (curl_cffi 纯 HTTP) =================

class ChatGPTRegister:
    """使用 curl_cffi 纯 HTTP 方式完成 ChatGPT 注册"""

    BASE = "https://chatgpt.com"
    AUTH = "https://auth.openai.com"

    def __init__(self, proxy: str = None, tag: str = ""):
        self.tag = tag
        self.device_id = str(uuid.uuid4())
        self.auth_session_logging_id = str(uuid.uuid4())
        self.impersonate, self.chrome_major, self.chrome_full, self.ua, self.sec_ch_ua = _random_chrome_version()

        self.session = curl_requests.Session(impersonate=self.impersonate)

        # 使用轮换代理
        self.proxy = proxy or get_next_proxy()
        if self.proxy:
            self.session.proxies = {"http": self.proxy, "https": self.proxy}

        self.session.headers.update({
            "User-Agent": self.ua,
            "Accept-Language": random.choice([
                "en-US,en;q=0.9", "en-US,en;q=0.9,zh-CN;q=0.8",
                "en,en-US;q=0.9", "en-US,en;q=0.8",
            ]),
            "sec-ch-ua": self.sec_ch_ua, "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"Windows"', "sec-ch-ua-arch": '"x86"',
            "sec-ch-ua-bitness": '"64"',
            "sec-ch-ua-full-version": f'"{self.chrome_full}"',
            "sec-ch-ua-platform-version": f'"{random.randint(10, 15)}.0.0"',
        })

        self.session.cookies.set("oai-did", self.device_id, domain="chatgpt.com")
        self._callback_url = None

    def _log(self, step, method, url, status, body=None):
        prefix = f"[{self.tag}] " if self.tag else ""
        lines = [
            f"\n{'='*60}",
            f"{prefix}[Step] {step}",
            f"{prefix}[{method}] {url}",
            f"{prefix}[Status] {status}",
        ]
        if body:
            try:
                lines.append(f"{prefix}[Response] {json.dumps(body, indent=2, ensure_ascii=False)[:1000]}")
            except Exception:
                lines.append(f"{prefix}[Response] {str(body)[:1000]}")
        lines.append(f"{'='*60}")
        with _print_lock:
            print("\n".join(lines))

    def _print(self, msg):
        prefix = f"[{self.tag}] " if self.tag else ""
        with _print_lock:
            print(f"{prefix}{msg}")

    # ==================== DuckMail 临时邮箱 ====================

    def _create_duckmail_session(self):
        session = curl_requests.Session()
        session.headers.update({
            "User-Agent": self.ua,
            "Accept": "application/json",
            "Content-Type": "application/json",
        })
        if self.proxy:
            session.proxies = {"http": self.proxy, "https": self.proxy}
        return session

    def create_temp_email(self, preferred_domain="papipa.cc.cd"):
        """创建 DuckMail 临时邮箱,优先使用指定后缀,返回 (email, email_password, mail_token)"""
        if not DUCKMAIL_BEARER:
            raise Exception("DUCKMAIL_BEARER 未设置,无法创建临时邮箱")

        chars = string.ascii_lowercase + string.digits
        length = random.randint(8, 13)
        email_local = "".join(random.choice(chars) for _ in range(length))
        
        # 优先使用指定后缀,失败则回退到默认后缀
        domains_to_try = [preferred_domain, "duckmail.sbs"]
        
        api_base = DUCKMAIL_API_BASE.rstrip("/")
        headers = {"Authorization": f"Bearer {DUCKMAIL_BEARER}"}
        session = self._create_duckmail_session()
        
        last_error = None
        for domain in domains_to_try:
            email = f"{email_local}@{domain}"
            password = _generate_password()
            
            try:
                # 1. 创建账号
                res = session.post(
                    f"{api_base}/accounts",
                    json={"address": email, "password": password},
                    headers=headers,
                    timeout=15,
                    impersonate=self.impersonate,
                )
                if res.status_code in [200, 201]:
                    # 2. 获取 Token
                    time.sleep(0.5)
                    token_res = session.post(
                        f"{api_base}/token",
                        json={"address": email, "password": password},
                        timeout=15,
                        impersonate=self.impersonate,
                    )
                    if token_res.status_code == 200:
                        mail_token = token_res.json().get("token")
                        if mail_token:
                            self._print(f"[DuckMail] 邮箱创建成功 ({domain}): {email}")
                            return email, password, mail_token
                elif res.status_code == 422 or "domain" in res.text.lower():
                    # 域名不可用,尝试下一个
                    self._print(f"[!] 域名 {domain} 不可用,尝试下一个...")
                    continue
                else:
                    last_error = f"{res.status_code} - {res.text[:200]}"
                    
            except Exception as e:
                last_error = str(e)
                continue
                
        raise Exception(f"创建邮箱失败: {last_error}")

    def _fetch_emails_duckmail(self, mail_token: str):
        try:
            api_base = DUCKMAIL_API_BASE.rstrip("/")
            headers = {"Authorization": f"Bearer {mail_token}"}
            session = self._create_duckmail_session()

            res = session.get(
                f"{api_base}/messages",
                headers=headers,
                timeout=15,
                impersonate=self.impersonate,
            )
            if res.status_code == 200:
                data = res.json()
                return data.get("hydra:member") or data.get("member") or data.get("data") or []
            return []
        except Exception:
            return []

    def _fetch_email_detail_duckmail(self, mail_token: str, msg_id: str):
        try:
            api_base = DUCKMAIL_API_BASE.rstrip("/")
            headers = {"Authorization": f"Bearer {mail_token}"}
            session = self._create_duckmail_session()

            if isinstance(msg_id, str) and msg_id.startswith("/messages/"):
                msg_id = msg_id.split("/")[-1]

            res = session.get(
                f"{api_base}/messages/{msg_id}",
                headers=headers,
                timeout=15,
                impersonate=self.impersonate,
            )
            if res.status_code == 200:
                return res.json()
        except Exception:
            pass
        return None

    def _extract_verification_code(self, email_content: str):
        if not email_content:
            return None
        patterns = [
            r"Verification code:?\s*(\d{6})",
            r"code is\s*(\d{6})",
            r"代码为[::]?\s*(\d{6})",
            r"验证码[::]?\s*(\d{6})",
            r">\s*(\d{6})\s*<",
            r"(?<![#&])\b(\d{6})\b",
        ]
        for pattern in patterns:
            matches = re.findall(pattern, email_content, re.IGNORECASE)
            for code in matches:
                if code == "177010":
                    continue
                return code
        return None

    def wait_for_verification_email(self, mail_token: str, timeout: int = 120):
        self._print(f"[OTP] 等待验证码邮件 (最多 {timeout}s)...")
        start_time = time.time()

        while time.time() - start_time < timeout:
            messages = self._fetch_emails_duckmail(mail_token)
            if messages and len(messages) > 0:
                first_msg = messages[0]
                msg_id = first_msg.get("id") or first_msg.get("@id")

                if msg_id:
                    detail = self._fetch_email_detail_duckmail(mail_token, msg_id)
                    if detail:
                        content = detail.get("text") or detail.get("html") or ""
                        code = self._extract_verification_code(content)
                        if code:
                            self._print(f"[OTP] 验证码: {code}")
                            return code

            elapsed = int(time.time() - start_time)
            self._print(f"[OTP] 等待中... ({elapsed}s/{timeout}s)")
            time.sleep(3)

        self._print(f"[OTP] 超时 ({timeout}s)")
        return None

    # ==================== OpenAI 注册流程 (纯 HTTP) ====================

    def visit_homepage(self):
        url = f"{self.BASE}/"
        r = self.session.get(url, headers={
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
            "Upgrade-Insecure-Requests": "1",
        }, allow_redirects=True)
        self._log("0. Visit homepage", "GET", url, r.status_code,
                  {"cookies_count": len(self.session.cookies)})

    def get_csrf(self) -> str:
        url = f"{self.BASE}/api/auth/csrf"
        r = self.session.get(url, headers={"Accept": "application/json", "Referer": f"{self.BASE}/"})
        data = r.json()
        token = data.get("csrfToken", "")
        self._log("1. Get CSRF", "GET", url, r.status_code, data)
        if not token:
            raise Exception("Failed to get CSRF token")
        return token

    def signin(self, email: str, csrf: str) -> str:
        url = f"{self.BASE}/api/auth/signin/openai"
        params = {
            "prompt": "login", "ext-oai-did": self.device_id,
            "auth_session_logging_id": self.auth_session_logging_id,
            "screen_hint": "login_or_signup", "login_hint": email,
        }
        form_data = {"callbackUrl": f"{self.BASE}/", "csrfToken": csrf, "json": "true"}
        r = self.session.post(url, params=params, data=form_data, headers={
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "application/json", "Referer": f"{self.BASE}/", "Origin": self.BASE,
        })
        data = r.json()
        authorize_url = data.get("url", "")
        self._log("2. Signin", "POST", url, r.status_code, data)
        if not authorize_url:
            raise Exception("Failed to get authorize URL")
        return authorize_url

    def authorize(self, url: str) -> str:
        r = self.session.get(url, headers={
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Referer": f"{self.BASE}/", "Upgrade-Insecure-Requests": "1",
        }, allow_redirects=True)
        final_url = str(r.url)
        self._log("3. Authorize", "GET", url, r.status_code, {"final_url": final_url})
        return final_url

    def register(self, email: str, password: str):
        url = f"{self.AUTH}/api/accounts/user/register"
        headers = {
            "Content-Type": "application/json", "Accept": "application/json",
            "Referer": f"{self.AUTH}/create-account/password", "Origin": self.AUTH,
        }
        headers.update(_make_trace_headers())
        r = self.session.post(url, json={"username": email, "password": password}, headers=headers)
        try:
            data = r.json()
        except Exception:
            data = {"text": r.text[:500]}
        self._log("4. Register", "POST", url, r.status_code, data)
        return r.status_code, data

    def send_otp(self):
        url = f"{self.AUTH}/api/accounts/email-otp/send"
        r = self.session.get(url, headers={
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Referer": f"{self.AUTH}/create-account/password", "Upgrade-Insecure-Requests": "1",
        }, allow_redirects=True)
        try:
            data = r.json()
        except Exception:
            data = {"final_url": str(r.url), "status": r.status_code}
        self._log("5. Send OTP", "GET", url, r.status_code, data)
        return r.status_code, data

    def validate_otp(self, code: str):
        url = f"{self.AUTH}/api/accounts/email-otp/validate"
        headers = {
            "Content-Type": "application/json", "Accept": "application/json",
            "Referer": f"{self.AUTH}/email-verification", "Origin": self.AUTH,
        }
        headers.update(_make_trace_headers())
        r = self.session.post(url, json={"code": code}, headers=headers)
        try:
            data = r.json()
        except Exception:
            data = {"text": r.text[:500]}
        self._log("6. Validate OTP", "POST", url, r.status_code, data)
        return r.status_code, data

    def create_account(self, name: str, birthdate: str):
        url = f"{self.AUTH}/api/accounts/create_account"
        headers = {
            "Content-Type": "application/json", "Accept": "application/json",
            "Referer": f"{self.AUTH}/about-you", "Origin": self.AUTH,
        }
        headers.update(_make_trace_headers())
        r = self.session.post(url, json={"name": name, "birthdate": birthdate}, headers=headers)
        try:
            data = r.json()
        except Exception:
            data = {"text": r.text[:500]}
        self._log("7. Create Account", "POST", url, r.status_code, data)
        if isinstance(data, dict):
            cb = data.get("continue_url") or data.get("url") or data.get("redirect_url")
            if cb:
                self._callback_url = cb
        return r.status_code, data

    def callback(self, url: str = None):
        if not url:
            url = self._callback_url
        if not url:
            self._print("[!] No callback URL, skipping.")
            return None, None
        r = self.session.get(url, headers={
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Upgrade-Insecure-Requests": "1",
        }, allow_redirects=True)
        self._log("8. Callback", "GET", url, r.status_code, {"final_url": str(r.url)})
        return r.status_code, {"final_url": str(r.url)}

    # ==================== 注册主流程 ====================

    def run_register(self, email, password, name, birthdate, mail_token):
        """完整注册流程 (纯 HTTP)"""
        self.visit_homepage()
        _random_delay(0.3, 0.8)

        csrf = self.get_csrf()
        _random_delay(0.2, 0.5)

        auth_url = self.signin(email, csrf)
        _random_delay(0.3, 0.8)

        final_url = self.authorize(auth_url)
        final_path = urlparse(final_url).path
        _random_delay(0.3, 0.8)

        self._print(f"Authorize -> {final_path}")

        need_otp = False

        if "create-account/password" in final_path:
            self._print("全新注册流程")
            _random_delay(0.5, 1.0)
            status, data = self.register(email, password)
            if status != 200:
                raise Exception(f"Register 失败 ({status}): {data}")
            _random_delay(0.3, 0.8)
            self.send_otp()
            need_otp = True

        elif "email-verification" in final_path or "email-otp" in final_path:
            self._print("跳到 OTP 验证阶段")
            need_otp = True

        elif "about-you" in final_path:
            self._print("跳到填写信息阶段")
            _random_delay(0.5, 1.0)
            self.create_account(name, birthdate)
            _random_delay(0.3, 0.5)
            self.callback()
            return True

        elif "callback" in final_path or "chatgpt.com" in final_url:
            self._print("账号已完成注册")
            return True

        else:
            self._print(f"未知跳转: {final_url}")
            self.register(email, password)
            self.send_otp()
            need_otp = True

        if need_otp:
            otp_code = self.wait_for_verification_email(mail_token)
            if not otp_code:
                raise Exception("未能获取验证码")

            _random_delay(0.3, 0.8)
            status, data = self.validate_otp(otp_code)
            if status != 200:
                self._print("验证码失败,重试...")
                self.send_otp()
                _random_delay(1.0, 2.0)
                otp_code = self.wait_for_verification_email(mail_token, timeout=60)
                if not otp_code:
                    raise Exception("重试后仍未获取验证码")
                _random_delay(0.3, 0.8)
                status, data = self.validate_otp(otp_code)
                if status != 200:
                    raise Exception(f"验证码失败 ({status}): {data}")

        _random_delay(0.5, 1.5)
        status, data = self.create_account(name, birthdate)
        if status != 200:
            raise Exception(f"Create account 失败 ({status}): {data}")
        _random_delay(0.2, 0.5)
        self.callback()
        return True


# ================= CPA OAuth 部分 (Selenium, 保留原逻辑) =================

def _wait_oauth_page_loaded(driver, timeout=20):
    WebDriverWait(driver, timeout).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "div.card"))
    )


def _navigate_to_oauth_page(driver, max_attempts=6):
    for attempt in range(1, max_attempts + 1):
        try:
            driver.get(CLI_PROXY_MANAGEMENT_URL)
        except Exception:
            pass
        time.sleep(2)
        if driver.find_elements(By.CSS_SELECTOR, "div.card"):
            return True
        try:
            nav_candidates = driver.find_elements(
                By.XPATH,
                "//a[contains(., 'OAuth') or contains(., 'oauth') or contains(., '授权') or contains(., '认证')] "
                "| //button[contains(., 'OAuth') or contains(., 'oauth') or contains(., '授权') or contains(., '认证')]"
            )
            for nav in nav_candidates:
                if not nav.is_displayed():
                    continue
                try:
                    driver.execute_script("arguments[0].click();", nav)
                    time.sleep(2)
                    if driver.find_elements(By.CSS_SELECTOR, "div.card"):
                        return True
                except Exception:
                    continue
        except Exception:
            pass
        print(f"   OAuth page not ready, retrying ({attempt}/{max_attempts})")
    return False


def _get_codex_oauth_card(driver):
    _wait_oauth_page_loaded(driver, timeout=20)
    time.sleep(1)
    cards = driver.find_elements(By.CSS_SELECTOR, "div.card")
    for card in cards:
        try:
            if "Codex OAuth" in card.text or "Codex" in card.text:
                return card
        except Exception:
            continue
    return None


def login_cli_proxy_panel(driver):
    print("\n[CPA] 登录 CPA 管理面板...")
    driver.get(CLI_PROXY_MANAGEMENT_URL)
    time.sleep(2)
    if driver.find_elements(By.CSS_SELECTOR, "div.card"):
        return True

    if not driver.find_elements(By.CSS_SELECTOR, 'input[type="password"]'):
        if _navigate_to_oauth_page(driver):
            return True

    try:
        password_input = WebDriverWait(driver, 20).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, 'input[type="password"]'))
        )
        password_input.clear()
        password_input.send_keys(CLI_PROXY_PASSWORD)
        login_btn = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn.btn-primary"))
        )
        driver.execute_script("arguments[0].click();", login_btn)
        time.sleep(2)
        if _navigate_to_oauth_page(driver):
            return True
    except Exception as e:
        print(f"[!] 登录 CPA 失败: {e}")
    return False


def _extract_auth_url_from_card(driver, codex_card):
    try:
        card_text = codex_card.text
        urls = re.findall(r'https://auth\.openai\.com/(?:oauth/)?authorize[^\s<>\'\)]+', card_text)
        if urls:
            return urls[0].replace("&amp;", "&")

        page_source = driver.page_source
        urls = re.findall(r'https://auth\.openai\.com/(?:oauth/)?authorize[^\s"<>\'\)]+', page_source)
        if urls:
            return urls[0].replace("&amp;", "&")
    except Exception as e:
        print(f"   提取 auth 链接失败: {e}")
    return None


def get_codex_oauth_auth_link(driver):
    print("\n[CPA] 获取 Codex OAuth 授权链接...")
    if not login_cli_proxy_panel(driver):
        return None

    try:
        codex_card = _get_codex_oauth_card(driver)
        if not codex_card:
            return None

        # 检查是否已有链接 (Open 按钮)
        try:
            open_link_btn = codex_card.find_element(
                By.XPATH, ".//button[contains(text(), '打开链接') or contains(text(), 'Open')]"
            )
            if open_link_btn.is_displayed():
                auth_url = _extract_auth_url_from_card(driver, codex_card)
                if auth_url:
                    return auth_url
        except Exception:
            pass

        # 点击 Login
        login_btn = None
        try:
            login_btn = codex_card.find_element(By.CSS_SELECTOR, "button.btn-primary")
        except Exception:
            pass

        if not login_btn:
            buttons = codex_card.find_elements(By.TAG_NAME, "button")
            for btn in buttons:
                if btn.text.strip() in ["登录", "Login", "login"]:
                    login_btn = btn
                    break

        if login_btn:
            driver.execute_script("arguments[0].click();", login_btn)
            print("   已点击 Login, 等待链接...")
            for _ in range(10):
                time.sleep(1)
                codex_card = _get_codex_oauth_card(driver)
                if not codex_card:
                    continue
                auth_url = _extract_auth_url_from_card(driver, codex_card)
                if auth_url:
                    return auth_url
    except Exception as e:
        print(f"[!] 获取 auth 链接失败: {e}")
    return None


def submit_callback_via_api(callback_url: str):
    """提交 callback 到 CPA API (使用 curl_cffi)"""
    print("\n[CPA] 提交 callback...")
    try:
        parsed = urlparse(callback_url)
        params = parse_qs(parsed.query)
        state = params.get("state", [None])[0]
        if not state:
            print("[OK] callback URL 无 state 参数,可能已成功。")
            return True

        api_endpoint = f"{CLI_PROXY_API_BASE}/v0/management/oauth-callback"
        payload = {"provider": "codex", "redirect_url": callback_url, "state": state}
        headers = {"Content-Type": "application/json"}
        if CLI_PROXY_PASSWORD:
            headers["Authorization"] = f"Bearer {CLI_PROXY_PASSWORD}"
            headers["X-Management-Key"] = CLI_PROXY_PASSWORD

        res = curl_requests.post(api_endpoint, json=payload, headers=headers, timeout=30)
        if res.status_code == 200 and res.json().get("status") == "ok":
            print("[OK] Callback 提交成功!")
            return True
        elif res.status_code == 404 and "expired" in res.text.lower():
            print("[OK] CPA state 已过期 - 授权可能已自动完成!")
            return True
        else:
            print(f"[!] API 提交失败: Status {res.status_code}")
            print(f"   Response: {res.text[:200]}")
    except Exception as e:
        print(f"[!] API 提交异常: {e}")
    return False


def perform_openai_oauth_login_in_new_window(driver, auth_link, email, password, mail_token=None):
    """在浏览器新窗口执行 OpenAI OAuth 登录"""
    print(f"\n[CPA] 执行 OAuth 登录: {auth_link[:60]}...")
    initial_handle = driver.current_window_handle

    driver.switch_to.new_window('tab')
    driver.get(auth_link)
    time.sleep(3)

    email_entered = False
    password_entered = False
    verification_handled = False

    start_time = time.time()
    callback_url = None
    max_wait_time = 120

    print(f"   等待 callback (最多 {max_wait_time}s)...")

    while time.time() - start_time < max_wait_time:
        try:
            current_url = driver.current_url

            # 1. 成功检测: localhost callback
            if "localhost" in current_url or "127.0.0.1" in current_url:
                if "code=" in current_url:
                    print(f"[OK] 捕获 callback URL: {current_url[:60]}...")
                    callback_url = current_url
                    break

                try:
                    page_text = driver.find_element(By.TAG_NAME, "body").text
                    if "Authentication successful" in page_text or "Token saved" in page_text:
                        print("[OK] 检测到认证成功!")
                        callback_url = current_url
                        break
                except Exception:
                    pass

            # 2. 输入邮箱
            if not email_entered and driver.find_elements(By.CSS_SELECTOR, 'input[type="email"]'):
                print("   检测到邮箱输入框...")
                email_input = driver.find_element(By.CSS_SELECTOR, 'input[type="email"]')
                email_input.clear()
                time.sleep(0.3)
                for char in email:
                    email_input.send_keys(char)
                    time.sleep(0.03)

                try:
                    btn = driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]')
                    driver.execute_script("arguments[0].click();", btn)
                except Exception:
                    email_input.send_keys(Keys.ENTER)
                email_entered = True
                time.sleep(3)
                continue

            # 3. 输入密码
            if not password_entered and driver.find_elements(By.CSS_SELECTOR, 'input[type="password"]'):
                print("   检测到密码输入框...")
                pwd_input = driver.find_element(By.CSS_SELECTOR, 'input[type="password"]')
                pwd_input.clear()
                time.sleep(0.3)
                for char in password:
                    pwd_input.send_keys(char)
                    time.sleep(0.03)

                try:
                    btn = driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]')
                    driver.execute_script("arguments[0].click();", btn)
                except Exception:
                    pwd_input.send_keys(Keys.ENTER)
                password_entered = True
                time.sleep(3)
                continue

            # 4. 邮箱二次验证
            if not verification_handled and "email-verification" in current_url and mail_token:
                print("   检测到二次邮箱验证,正在获取验证码...")
                # 使用独立的 ChatGPTRegister 实例获取验证码(使用当前代理)
                temp_reg = ChatGPTRegister(tag="otp")
                verification_code = temp_reg.wait_for_verification_email(mail_token, timeout=60)
                if verification_code:
                    print(f"   验证码: {verification_code}")
                    try:
                        code_inputs = driver.find_elements(
                            By.CSS_SELECTOR, 'input[type="text"], input[inputmode="numeric"]'
                        )
                        if len(code_inputs) >= 6:
                            for i, digit in enumerate(verification_code[:6]):
                                code_inputs[i].send_keys(digit)
                                time.sleep(0.1)
                        elif code_inputs:
                            code_inputs[0].clear()
                            code_inputs[0].send_keys(verification_code)
                        print("   验证码已输入")
                        time.sleep(2)
                        try:
                            continue_btn = WebDriverWait(driver, 5).until(
                                EC.element_to_be_clickable((By.CSS_SELECTOR, 'button[type="submit"]'))
                            )
                            driver.execute_script("arguments[0].click();", continue_btn)
                            time.sleep(3)
                        except Exception:
                            pass
                    except Exception as e:
                        print(f"   输入验证码失败: {e}")
                else:
                    print("   未能获取验证码")
                verification_handled = True
                continue

            # 5. 处理 Continue / Authorize / Allow 按钮
            btns = driver.find_elements(By.CSS_SELECTOR, 'button')
            keywords = [
                "continue", "authorize", "allow", "yes", "accept", "confirm",
                "继续", "授权", "允许", "确定", "确认", "接受",
            ]
            for btn in btns:
                if not btn.is_displayed():
                    continue
                text = btn.text.lower()
                if any(x in text for x in ["login", "sign up", "登录", "注册"]):
                    continue
                if any(k in text for k in keywords):
                    print(f"   点击按钮: {btn.text}")
                    try:
                        driver.execute_script("arguments[0].click();", btn)
                        time.sleep(2)
                    except Exception:
                        pass

            # 6. 绿色授权按钮
            try:
                green_btns = driver.find_elements(
                    By.CSS_SELECTOR, 'button[class*="btn-primary"], button[class*="yes"]'
                )
                for btn in green_btns:
                    if btn.is_displayed() and "auth" in btn.text.lower():
                        driver.execute_script("arguments[0].click();", btn)
                        time.sleep(1)
            except Exception:
                pass

        except Exception:
            pass

        time.sleep(1)

    try:
        driver.close()
        driver.switch_to.window(initial_handle)
    except Exception:
        pass

    return callback_url


def check_and_handle_error(driver):
    try:
        body_text = driver.find_element(By.TAG_NAME, "body").text.lower()
        if "error" in body_text or "wrong" in body_text:
            btns = driver.find_elements(By.TAG_NAME, "button")
            for btn in btns:
                if "retry" in btn.text.lower() or "try again" in btn.text.lower():
                    btn.click()
                    time.sleep(3)
                    return True
    except Exception:
        pass
    return False


# Chrome 远程调试配置 (通过 HF Space)
CHROME_DEBUGGER_URL = "wss://campsong6-thisisatest.hf.space/chromium?token=nrbNXlKgQAliWZHrwScWpSAPu66xrC-mDJP38y0lLlc"

def get_driver(proxy=None):
    """获取 Chrome 驱动 - 通过 CDP 连接远程 Chrome"""
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    
    # 基本配置
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument('--window-size=1920,1080')
    options.add_argument('--disable-blink-features=AutomationControlled')
    options.add_argument('--disable-extensions')
    options.add_argument('--disable-infobars')
    
    # User-Agent
    options.add_argument(
        '--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 '
        '(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
    )
    
    # 代理
    proxy = proxy or get_next_proxy()
    if proxy:
        options.add_argument(f'--proxy-server={proxy}')
        print(f"[CPA] 使用代理: {proxy}")
    
    print("[CPA] 连接到远程 Chrome...")
    
    # 尝试连接远程 Chrome (CDP)
    try:
        from selenium.webdriver.chrome.service import Service
        from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
        
        # 使用 CDP 连接
        options.debugger_address = None
        driver = webdriver.Remote(
            command_executor='http://localhost:4444/wd/hub',
            options=options
        )
        print("[CPA] Chrome 连接成功 (Remote)")
        return driver
    except Exception as e1:
        print(f"[CPA] Remote 连接失败: {e1}")
    
    # 回退到本地
    try:
        driver = webdriver.Chrome(options=options)
        print("[CPA] Chrome 启动成功 (Local)")
        return driver
    except Exception as e2:
        print(f"[CPA] Local 也失败: {e2}")
        raise


# ================= 主流程 =================

def register_and_feed_cpa(max_proxy_retries=3):
    """注册一个账号并喂给 CPA"""
    email = None
    password = None
    success = False
    driver = None

    for retry in range(max_proxy_retries):
        try:
            # ---- 阶段一: curl_cffi 纯 HTTP 注册 ----
            reg = ChatGPTRegister(tag="reg")

            # 1. 创建临时邮箱
            reg._print("[Step 1] 创建 DuckMail 临时邮箱...")
            email, email_pwd, mail_token = reg.create_temp_email()
            reg.tag = email.split("@")[0]

            # 2. 生成注册信息
            password = _generate_password()
            name = _random_name()
            birthdate = _random_birthdate()

            print(f"\n{'='*60}")
            print(f"  邮箱: {email}")
            print(f"  ChatGPT 密码: {password}")
            print(f"  邮箱密码: {email_pwd}")
            print(f"  姓名: {name} | 生日: {birthdate}")
            print(f"  代理: {reg.proxy}")
            print(f"{'='*60}")

            # 3. 执行注册 (纯 HTTP)
            reg._print("[Step 2] 执行 OpenAI 注册 (HTTP)...")
            reg.run_register(email, password, name, birthdate, mail_token)

            # 4. 保存账号
            save_account(email, password)
            print(f"\n[OK] 注册成功: {email}")

            # ---- 阶段二: Selenium CPA OAuth 喂养 ----
            print("\n[CPA] 开始 CPA OAuth 喂养...")
            driver = get_driver()

            auth_link = get_codex_oauth_auth_link(driver)
            if auth_link:
                callback = perform_openai_oauth_login_in_new_window(
                    driver, auth_link, email, password, mail_token
                )
                if callback:
                    if submit_callback_via_api(callback):
                        success = True
                        print("[OK] 注册 + CPA 喂养全部完成!")
                    else:
                        print("[!] 注册成功,但 CPA API 提交失败")
                else:
                    print("[!] 注册成功,但未获取到 callback URL")
            else:
                print("[!] 注册成功,但未获取到 CPA Auth 链接")
            
            # 成功就跳出重试循环
            break

        except Exception as e:
            print(f"[!] 流程异常 (代理: {reg.proxy if 'reg' in locals() else 'N/A'}): {e}")
            if email and password:
                save_account(email, password)
            
            if retry < max_proxy_retries - 1:
                print(f"[*] 切换代理重试 ({retry + 1}/{max_proxy_retries})...")
                time.sleep(2)
            else:
                print(f"[!] 已用完所有代理重试次数")

        finally:
            if driver:
                try:
                    driver.quit()
                except OSError:
                    pass
                except Exception as e:
                    print(f"[!] 浏览器关闭异常: {e}")
            driver = None

    return email, success


def run():
    print(f"\n{'#'*60}")
    print(f"  ChatGPT 注册 + CPA 喂养工具")
    print(f"  注册方式: curl_cffi 纯 HTTP")
    print(f"  模式: 无限循环运行 (按 Ctrl+C 停止)")
    print(f"  可用代理: {len(_PROXY_LIST)} 个")
    print(f"  CPA: {CLI_PROXY_API_BASE}")
    print(f"  DuckMail: {DUCKMAIL_API_BASE}")
    print(f"{'#'*60}\n")

    success_count = 0
    fail_count = 0
    i = 0

    try:
        while True:
            i += 1
            print(f"\n--- 账号 #{i} ---")
            try:
                email, ok = register_and_feed_cpa()
                if ok:
                    success_count += 1
                else:
                    fail_count += 1
            except Exception as e:
                print(f"[!] 账号 #{i} 意外异常: {e}")
                fail_count += 1
            print(f"   进度: OK {success_count} / FAIL {fail_count} / 总计 #{i}")
            
            # 每5个账号后随机休眠 30秒~3分钟
            if i % 5 == 0:
                random_delay_between_accounts()
            else:
                time.sleep(5)

    except KeyboardInterrupt:
        print(f"\n\n[!] 用户手动停止")
        
    print(f"\n{'#'*60}")
    print(f"  完成! OK {success_count} / FAIL {fail_count} / 总计 #{i}")
    print(f"{'#'*60}")


if __name__ == "__main__":
    run()