File size: 65,548 Bytes
9adc988
 
 
 
 
 
 
 
fcc568b
9adc988
 
 
 
 
 
 
 
09accbc
9adc988
 
 
 
 
21f1556
9adc988
72d8b3f
9adc988
 
77988be
9adc988
 
fcc568b
21f1556
9adc988
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b8310b
 
 
9adc988
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5dd041
9adc988
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2625652
 
 
 
411d6c7
 
 
 
 
 
 
2625652
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09accbc
 
 
 
 
 
 
3f5f34a
9adc988
3f5f34a
9adc988
77988be
9adc988
 
 
 
 
 
77988be
 
9adc988
 
77988be
 
9adc988
 
 
77988be
 
 
 
 
 
 
 
 
 
 
 
b66ac73
 
 
2625652
77988be
 
 
b66ac73
77988be
2625652
77988be
09accbc
77988be
 
 
09accbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77988be
9adc988
 
 
 
 
 
 
 
 
 
 
 
 
09accbc
9adc988
 
 
 
 
 
 
77988be
 
 
850c00e
77988be
850c00e
77988be
 
9adc988
 
 
 
 
 
 
c2c477d
 
 
 
 
 
 
 
3f5f34a
c47511d
 
 
 
 
 
 
 
9adc988
 
 
 
 
 
 
 
 
 
 
efea4b7
9adc988
 
 
 
 
 
efea4b7
9adc988
 
 
 
 
efea4b7
 
 
 
 
9adc988
 
72d8b3f
 
 
 
 
9adc988
 
 
 
 
 
 
 
 
 
 
 
 
72d8b3f
3f5f34a
 
850c00e
 
 
 
72d8b3f
 
 
 
 
 
 
 
 
 
9adc988
 
 
 
 
 
72d8b3f
9adc988
efea4b7
9adc988
 
efea4b7
 
 
 
 
958130d
 
 
 
 
72d8b3f
 
 
 
 
 
 
 
 
 
9adc988
 
 
efea4b7
9adc988
 
 
 
 
efea4b7
 
 
 
 
 
 
9adc988
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcc568b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9adc988
 
 
 
 
fcc568b
9adc988
 
 
 
fcc568b
 
 
9adc988
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcc568b
 
 
 
 
9adc988
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efea4b7
9adc988
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
958130d
 
 
 
 
9adc988
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcc568b
 
 
 
 
 
 
9adc988
fcc568b
 
 
 
9adc988
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcc568b
9adc988
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcc568b
9adc988
 
 
 
 
b66ac73
77988be
 
 
 
 
9adc988
 
 
 
 
 
 
 
 
 
fcc568b
 
 
9adc988
 
c2c477d
 
 
9adc988
 
 
 
 
 
 
 
 
77988be
 
 
 
9adc988
 
 
 
 
 
 
c2c477d
 
 
 
 
 
 
9adc988
 
fcc568b
 
 
 
9adc988
3b8310b
 
 
 
9adc988
 
 
 
 
 
 
 
fcc568b
9adc988
 
 
 
 
 
 
 
 
efea4b7
9adc988
 
fcc568b
 
9adc988
 
 
 
 
 
 
 
 
 
 
72d8b3f
9adc988
 
 
 
 
 
 
 
 
 
 
 
 
72d8b3f
 
 
9adc988
 
 
 
 
 
 
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
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
import os
import sys
import re
import json
import base64
import argparse
import time
import random
import math
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from urllib import request, parse, error
from datetime import datetime, timezone, timedelta

P401 = re.compile(r'(^|\D)401(\D|$)|unauthorized|unauthenticated|token\s+expired|login\s+required|authentication\s+failed|invalid_grant|refresh_token_reused|invalid\s+refresh', re.I)
PQUOTA = re.compile(r'(^|\D)(402|403|429)(\D|$)|quota|insufficient\s*quota|resource\s*exhausted|rate\s*limit|too\s+many\s+requests|payment\s+required|billing|credit|额度|用完|超限|上限|usage_limit_reached', re.I)
PREMOVE = re.compile(r'invalid_grant|refresh_token_reused|account.*deactivated|account.*disabled|missing\s+refresh\s+token|invalid\s+token', re.I)
PPLACEHOLDER = re.compile(r'^\$[A-Z0-9_]+\$$')

DEFAULT_BASE_URL = 'https://example.com/management.html'
DEFAULT_MANAGEMENT_KEY = 'replace-me'
DEFAULT_API_CALL_PROVIDERS = 'codex,openai,chatgpt'
DEFAULT_API_CALL_URL = 'https://chatgpt.com/backend-api/wham/usage'
DEFAULT_API_CALL_USER_AGENT = 'Mozilla/5.0 CLIProxyAPI-cleaner/1.0'
DEFAULT_API_CALL_ACCOUNT_ID = ''
DEFAULT_API_CALL_MAX_PER_RUN = 30
DEFAULT_API_CALL_SLEEP_MIN = 5.0
DEFAULT_API_CALL_SLEEP_MAX = 10.0
DEFAULT_PRE_USAGE_PROBE_SLEEP_SECONDS = 1.0
DEFAULT_REVIVAL_WAIT_DAYS = 7
DEFAULT_REVIVAL_INTERVAL_HOURS = 12
DEFAULT_USAGE_LIMIT_RESET_BUFFER_SECONDS = 60
DEFAULT_STATE_FILE = 'CLIProxyAPI-cleaner-state.json'
OPENAI_TOKEN_URL = 'https://auth.openai.com/oauth/token'
OPENAI_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann'
OPENAI_SCOPE = 'openid profile email'
AUTH_FILE_STATUS_METHODS = ('PATCH', 'PUT', 'POST')


def get_current_time():
    return datetime.now().astimezone().strftime('%Y-%m-%d %H:%M:%S %z')


def iso_now():
    return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace('+00:00', 'Z')


def run_id():
    return datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')


def script_dir():
    override = os.environ.get('CLIPROXY_SCRIPT_DIR')
    if override:
        return Path(override).expanduser().resolve()
    return Path(__file__).resolve().parent


def normalize_base_url(base):
    text = str(base or '').strip()
    if not text:
        return text
    text = text.rstrip('/')
    if text.endswith('/management.html'):
        text = text[:-len('/management.html')]
    return text.rstrip('/')


def parse_csv_set(value):
    if not value:
        return set()
    return {x.strip().lower() for x in str(value).split(',') if x.strip()}


def env_bool(name, default=False):
    raw = os.environ.get(name)
    if raw is None:
        return default
    return str(raw).strip().lower() not in ('0', 'false', 'no', 'off', '')


def parse_time(value):
    text = str(value or '').strip()
    if not text:
        return None
    try:
        return datetime.fromisoformat(text.replace('Z', '+00:00'))
    except Exception:
        return None


def to_iso(dt):
    if not dt:
        return ''
    return dt.astimezone(timezone.utc).replace(microsecond=0).isoformat().replace('+00:00', 'Z')


def api(base, key, method, path, timeout=20, query=None, expect_json=True, body=None, extra_headers=None):
    base = normalize_base_url(base)
    url = base.rstrip('/') + '/v0/management' + path
    if query:
        url += '?' + parse.urlencode(query, doseq=True)

    headers = {
        'Authorization': 'Bearer ' + key,
        'Accept': 'application/json',
        'User-Agent': 'cliproxyapi-cleaner/2.0',
    }
    if extra_headers:
        headers.update(extra_headers)

    data = None
    if body is not None:
        if isinstance(body, (dict, list)):
            data = json.dumps(body, ensure_ascii=False).encode('utf-8')
            headers.setdefault('Content-Type', 'application/json')
        elif isinstance(body, bytes):
            data = body
        else:
            data = str(body).encode('utf-8')
            headers.setdefault('Content-Type', 'application/json')

    req = request.Request(url, data=data, headers=headers, method=method.upper())
    try:
        with request.urlopen(req, timeout=timeout) as resp:
            raw = resp.read()
            code = resp.getcode()
            resp_headers = dict(resp.headers.items())
    except error.HTTPError as e:
        raw = e.read()
        code = e.code
        resp_headers = dict(e.headers.items()) if e.headers else {}
    except error.URLError as e:
        raise RuntimeError('请求管理 API 失败: %s' % e)

    if expect_json:
        try:
            payload = json.loads(raw.decode('utf-8')) if raw else {}
        except Exception:
            payload = {'raw': raw.decode('utf-8', errors='replace')}
        return code, payload, resp_headers
    return code, raw, resp_headers


def request_json_or_text(url, method='GET', timeout=20, body=None, headers=None):
    method = (method or 'GET').upper()
    req_headers = {
        'Accept': 'application/json',
        'User-Agent': 'cliproxyapi-cleaner/2.0',
    }
    if headers:
        req_headers.update(headers)

    data = None
    if body is not None:
        if isinstance(body, (dict, list)):
            data = json.dumps(body, ensure_ascii=False).encode('utf-8')
            req_headers.setdefault('Content-Type', 'application/json')
        elif isinstance(body, bytes):
            data = body
        else:
            data = str(body).encode('utf-8')
            req_headers.setdefault('Content-Type', 'application/json')

    req = request.Request(url, data=data, headers=req_headers, method=method)
    try:
        with request.urlopen(req, timeout=timeout) as resp:
            raw = resp.read()
            code = resp.getcode()
            resp_headers = dict(resp.headers.items())
    except error.HTTPError as e:
        raw = e.read()
        code = e.code
        resp_headers = dict(e.headers.items()) if e.headers else {}
    except error.URLError as e:
        raise RuntimeError('请求上游失败: %s' % e)

    text = raw.decode('utf-8', errors='replace') if raw else ''
    try:
        parsed = json.loads(text) if text else {}
    except Exception:
        parsed = text
    return {
        'status_code': code,
        'header': resp_headers,
        'body': parsed,
    }


def extract_error_message(msg):
    try:
        if isinstance(msg, str) and msg.strip().startswith('{'):
            error_data = json.loads(msg)
            if 'error' in error_data:
                error_obj = error_data['error']
                if isinstance(error_obj, dict):
                    error_type = error_obj.get('type', '')
                    error_message = error_obj.get('message', '')
                    return error_type, error_message
                if isinstance(error_obj, str):
                    return 'error', error_obj
            return None, msg
    except Exception:
        pass
    return None, msg


def simplify_reason(reason):
    text = str(reason or '').strip()
    if not text:
        return ''
    if not text.startswith('{'):
        return text[:160]
    try:
        error_data = json.loads(text)
    except Exception:
        return text[:160]
    if 'error' not in error_data:
        return text[:160]
    error_obj = error_data['error']
    if isinstance(error_obj, dict):
        error_type = str(error_obj.get('type') or '').strip()
        error_message = str(error_obj.get('message') or '').strip()
        if error_type == 'usage_limit_reached':
            return ('usage_limit_reached: ' + error_message)[:160]
        return (error_type or error_message or text)[:160]
    return str(error_obj)[:160]


def normalize_api_call_body(body):
    if body is None:
        return '', None
    if isinstance(body, str):
        text = body
        trimmed = text.strip()
        if not trimmed:
            return text, None
        try:
            return text, json.loads(trimmed)
        except Exception:
            return text, text
    try:
        return json.dumps(body, ensure_ascii=False), body
    except Exception:
        return str(body), body


def is_limit_reached_window(value):
    if not isinstance(value, dict):
        return False
    if value.get('allowed') is False:
        return True
    if value.get('limit_reached') is True:
        return True
    return False


def classify_api_call_response(payload):
    nested_status = payload.get('status_code', payload.get('statusCode', 0))
    try:
        nested_status = int(nested_status)
    except Exception:
        nested_status = 0

    header = payload.get('header') or payload.get('headers') or {}
    body_text, body = normalize_api_call_body(payload.get('body'))

    try:
        header_text = json.dumps(header, ensure_ascii=False)
    except Exception:
        header_text = str(header)

    if isinstance(body, (dict, list)):
        try:
            body_signal = json.dumps(body, ensure_ascii=False)
        except Exception:
            body_signal = body_text
    else:
        body_signal = body_text

    if nested_status == 401:
        return 'delete_401', body_signal or ('api-call status_code=%s' % nested_status)
    if nested_status in (402, 403, 429):
        return 'quota_exhausted', body_signal or ('api-call status_code=%s' % nested_status)

    if isinstance(body, dict):
        error_obj = body.get('error')
        if isinstance(error_obj, dict):
            error_type = str(error_obj.get('type') or '').strip().lower()
            error_message = str(error_obj.get('message') or '').strip()
            error_text = (error_type + '\n' + error_message).lower()
            if error_type == 'usage_limit_reached' or PQUOTA.search(error_text):
                return 'quota_exhausted', body_signal or error_message or error_type
            if P401.search(error_text):
                return 'delete_401', body_signal or error_message or error_type
        rate_limit = body.get('rate_limit')
        code_review_rate_limit = body.get('code_review_rate_limit')
        if is_limit_reached_window(rate_limit) or is_limit_reached_window(code_review_rate_limit):
            return 'quota_exhausted', body_signal or 'rate_limit_reached'
        if nested_status == 200:
            return None, body_signal or 'ok'

    fallback_text = ('%s\n%s\n%s' % (nested_status, header_text, body_signal)).lower()
    if P401.search(fallback_text):
        return 'delete_401', body_signal or ('api-call status_code=%s' % nested_status)
    if nested_status != 200 and PQUOTA.search(fallback_text):
        return 'quota_exhausted', body_signal or ('api-call status_code=%s' % nested_status)
    return None, body_signal or ('api-call status_code=%s' % nested_status if nested_status else 'ok')


def classify(item):
    status = str(item.get('status', '')).strip().lower()
    msg = str(item.get('status_message', '') or '').strip()
    error_type, _ = extract_error_message(msg)
    text = (status + '\n' + msg).lower()

    if P401.search(text):
        return 'delete_401', msg or status or '401/unauthorized'
    if error_type == 'usage_limit_reached' or 'usage_limit_reached' in text:
        return 'quota_exhausted', msg or status or 'usage_limit_reached'
    if PQUOTA.search(text):
        return 'quota_exhausted', msg or status or 'quota'
    if bool(item.get('disabled', False)) or status == 'disabled':
        return 'disabled', msg or status or 'disabled'
    if bool(item.get('unavailable', False)) or status == 'error':
        return 'unavailable', msg or status or 'error'
    return 'available', msg or status or 'active'


def should_probe_api_call(item, args):
    if not args.enable_api_call_check:
        return False
    auth_index = str(item.get('auth_index') or '').strip()
    if not auth_index:
        return False
    provider = str(item.get('provider') or item.get('type') or '').strip().lower()
    if args.api_call_provider_set and provider not in args.api_call_provider_set:
        return False
    initial_kind, _ = classify(item)
    return initial_kind in ('available', 'unavailable')


def api_call_item_key(item):
    auth_index = str(item.get('auth_index') or '').strip()
    if auth_index:
        return 'auth_index:' + auth_index
    return 'name:' + str(item.get('name') or item.get('id') or '').strip()


def choose_account_id(item, args, auth_payload=None):
    candidates = []
    if auth_payload and isinstance(auth_payload, dict):
        candidates.extend([
            auth_payload.get('account_id'),
            auth_payload.get('accountId'),
        ])
        metadata = auth_payload.get('metadata') if isinstance(auth_payload.get('metadata'), dict) else {}
        candidates.extend([metadata.get('account_id'), metadata.get('accountId')])
    candidates.extend([
        item.get('account_id'),
        item.get('accountId'),
        item.get('account'),
    ])
    for candidate in candidates:
        value = str(candidate or '').strip()
        if value:
            return value
    return args.api_call_account_id.strip()


def derive_heartbeat_account_prefix(item):
    if not isinstance(item, dict):
        return ''

    # 优先顺序:account → email → label → name
    for key in ('account', 'email', 'label', 'name'):
        value = str(item.get(key) or '').strip()
        if value:
            # 只取全局(不做 @ 前缀分割)
            return value

    return ''


def build_prefixed_pre_usage_probe_body(item, body):
    body_text, parsed_body = normalize_api_call_body(body)
    if not isinstance(parsed_body, dict):
        return body_text

    model = parsed_body.get('model')
    if not isinstance(model, str):
        return body_text

    model = model.strip()
    if not model or '/' in model:
        return body_text

    prefix = derive_heartbeat_account_prefix(item)
    if not prefix:
        return body_text

    payload = dict(parsed_body)
    payload['model'] = prefix + '/' + model
    return json.dumps(payload, ensure_ascii=False, separators=(',', ':'))


def resolve_pre_usage_api_key_authorization():
    api_key = str(os.environ.get('CLIPROXY_API_KEY') or '').strip()
    if api_key:
        return 'Bearer ' + api_key
    return 'Bearer $CLIPROXY_API_KEY$'


def build_management_probe_payload(item, method, url, user_agent, body_text, args, authorization_value='Bearer $TOKEN$'):
    headers = {
        'Authorization': str(authorization_value or '').strip(),
        'Content-Type': 'application/json',
        'User-Agent': user_agent,
    }
    account_id = choose_account_id(item, args)
    if account_id:
        headers['Chatgpt-Account-Id'] = account_id
    payload = {
        'authIndex': str(item.get('auth_index') or '').strip(),
        'method': str(method or 'GET').upper(),
        'url': str(url or '').strip(),
        'header': headers,
    }
    if body_text:
        payload['data'] = body_text
    return payload


def build_api_call_payload(item, args):
    return build_management_probe_payload(
        item,
        args.api_call_method,
        args.api_call_url,
        args.api_call_user_agent,
        args.api_call_body,
        args,
    )


def build_pre_usage_probe_payload(item, args):
    pre_usage_probe_url = str(getattr(args, 'pre_usage_probe_url', '') or '').strip()
    if not pre_usage_probe_url:
        pre_usage_probe_url = normalize_base_url(getattr(args, 'base_url', '')) + '/v1/responses'
    pre_usage_probe_body = build_prefixed_pre_usage_probe_body(item, args.pre_usage_probe_body)
    return build_management_probe_payload(
        item,
        args.pre_usage_probe_method,
        pre_usage_probe_url,
        args.api_call_user_agent,
        pre_usage_probe_body,
        args,
        authorization_value=resolve_pre_usage_api_key_authorization(),
    )


def sanitize_authorization_for_storage(value):
    text = str(value or '').strip()
    if not text:
        return ''
    if ' ' in text:
        scheme, token = text.split(' ', 1)
        token = token.strip()
        if PPLACEHOLDER.fullmatch(token):
            return scheme + ' ' + token
        return scheme + ' ' + mask_value_for_log(token)
    if PPLACEHOLDER.fullmatch(text):
        return text
    return mask_value_for_log(text)


def redact_request_for_storage(payload, missing='disabled'):
    if not isinstance(payload, dict):
        return missing
    safe_payload = {}
    for key in ('authIndex', 'method', 'url', 'data'):
        if key in payload:
            safe_payload[key] = payload.get(key)
    header = payload.get('header')
    if isinstance(header, dict):
        safe_header = {}
        for key, value in header.items():
            if str(key).lower() == 'authorization':
                safe_header[key] = sanitize_authorization_for_storage(value)
            else:
                safe_header[key] = value
        safe_payload['header'] = safe_header
    return safe_payload


def execute_management_probe(args, request_payload):
    code, payload, _ = api(
        args.base_url,
        args.management_key,
        'POST',
        '/api-call',
        args.timeout,
        expect_json=True,
        body=request_payload,
    )
    if code != 200:
        raise RuntimeError('调用 /api-call 失败: HTTP %s %s' % (code, payload))
    kind, reason = classify_api_call_response(payload)
    return {
        'request': redact_request_for_storage(request_payload),
        'response': payload,
        'classification': kind,
        'reason': reason,
        'status_code': payload.get('status_code', payload.get('statusCode')),
    }


def run_api_call_probe(args, item):
    if getattr(args, 'pre_usage_probe_enabled', False):
        pre_request_payload = build_pre_usage_probe_payload(item, args)
        return execute_management_probe(args, pre_request_payload)

    return execute_management_probe(args, build_api_call_payload(item, args))


def pick_api_call_sleep_seconds(args):
    fixed_sleep = getattr(args, 'api_call_sleep', None)
    if fixed_sleep is not None:
        return max(0.0, float(fixed_sleep))
    return random.uniform(args.api_call_sleep_min, args.api_call_sleep_max)



def pick_loop_interval_seconds(args):
    start = int(getattr(args, "interval_min", 1800))
    end = int(getattr(args, "interval_max", 3600))
    if end < start:
        start, end = end, start
    return random.randint(start, end)


def mask_value_for_log(value):
    text = str(value or '').strip()
    if not text:
        return ''
    if len(text) <= 10:
        return text[:2] + '...' if len(text) > 2 else text
    return text[:6] + '...' + text[-4:]

def run_api_call_full_scan(args, files, counts):
    if not args.enable_api_call_check:
        counts['api-call候选数'] = 0
        counts['api-call批次数'] = 0
        return {}

    eligible = [item for item in files if should_probe_api_call(item, args)]
    counts['api-call候选数'] = len(eligible)
    if not eligible:
        counts['api-call批次数'] = 0
        args.api_call_scan_completed = True
        print('[heartbeat] 本轮没有需要探测的候选账号', flush=True)
        return {}

    batch_size = max(1, min(int(args.api_call_max_per_run), DEFAULT_API_CALL_MAX_PER_RUN))
    batch_count = (len(eligible) + batch_size - 1) // batch_size
    counts['api-call批次数'] = batch_count
    sleep_desc = '固定 %.1f 秒' % args.api_call_sleep if args.api_call_sleep is not None else '随机 %.1f-%.1f 秒' % (args.api_call_sleep_min, args.api_call_sleep_max)
    print('[heartbeat] 本轮将探测 %s 个候选账号,共 %s 批,每批最多 %s 个,批次间隔 %s' % (
        len(eligible), batch_count, batch_size, sleep_desc,
    ), flush=True)

    probe_results = {}
    probed_total = 0
    total_heartbeat_success = 0
    total_heartbeat_delete_401 = 0
    total_heartbeat_quota_exhausted = 0
    total_heartbeat_failed = 0
    total_usage_started = 0
    for batch_index in range(batch_count):
        batch = eligible[batch_index * batch_size:(batch_index + 1) * batch_size]
        heartbeat_success = 0
        heartbeat_delete_401 = 0
        heartbeat_quota_exhausted = 0
        heartbeat_failed = 0
        usage_started = 0
        with ThreadPoolExecutor(max_workers=len(batch)) as executor:
            future_to_item = {executor.submit(run_api_call_probe, args, item): item for item in batch}
            for future in as_completed(future_to_item):
                item = future_to_item[future]
                counts['api-call已探测'] += 1
                probed_total += 1
                name = str(item.get('name') or item.get('id') or '').strip()
                provider = str(item.get('provider') or item.get('type') or '').strip()
                auth_index = item.get('auth_index')
                try:
                    probe = future.result()
                    probe_results[api_call_item_key(item)] = probe
                    classification = probe.get('classification') or 'ok'
                    heartbeat_probe = probe.get('pre_probe') if isinstance(probe.get('pre_probe'), dict) else None
                    usage_probe = probe.get('usage_probe') if isinstance(probe.get('usage_probe'), dict) else None
                    if usage_probe is None and heartbeat_probe is None and isinstance(probe, dict):
                        if getattr(args, 'pre_usage_probe_enabled', False):
                            heartbeat_probe = probe
                        else:
                            usage_probe = probe
                    if heartbeat_probe is not None:
                        heartbeat_classification = heartbeat_probe.get('classification')
                        if heartbeat_classification == 'delete_401':
                            heartbeat_delete_401 += 1
                        elif heartbeat_classification == 'quota_exhausted':
                            heartbeat_quota_exhausted += 1
                        else:
                            heartbeat_success += 1
                        if 'usage_probe' in probe:
                            usage_started += 1
                    if classification == 'delete_401':
                        counts['api-call发现401'] += 1
                    elif classification == 'quota_exhausted':
                        counts['api-call发现配额耗尽'] += 1
                except Exception as e:
                    counts['api-call探测失败'] += 1
                    heartbeat_failed += 1
                    probe_results[api_call_item_key(item)] = {'error': str(e)}
                    print('[heartbeat error %s/%s] %s provider=%s auth_index=%s error=%s' % (
                        probed_total, len(eligible), name, provider, auth_index, e,
                    ), flush=True)
        total_heartbeat_success += heartbeat_success
        total_heartbeat_delete_401 += heartbeat_delete_401
        total_heartbeat_quota_exhausted += heartbeat_quota_exhausted
        total_heartbeat_failed += heartbeat_failed
        total_usage_started += usage_started
        counts['心跳成功'] += heartbeat_success
        counts['心跳401'] += heartbeat_delete_401
        counts['心跳配额耗尽'] += heartbeat_quota_exhausted
        counts['心跳失败'] += heartbeat_failed
        counts['进入usage探测'] += usage_started
        if getattr(args, 'pre_usage_probe_enabled', False):
            print('[heartbeat batch %s/%s] success=%s delete_401=%s quota_exhausted=%s failed=%s usage_started=%s' % (
                batch_index + 1,
                batch_count,
                heartbeat_success,
                heartbeat_delete_401,
                heartbeat_quota_exhausted,
                heartbeat_failed,
                usage_started,
            ), flush=True)
        if batch_index + 1 < batch_count:
            sleep_seconds = pick_api_call_sleep_seconds(args)
            if sleep_seconds > 0:
                print('[heartbeat] 第 %s/%s 批完成,等待 %.1f 秒后继续下一批' % (
                    batch_index + 1, batch_count, sleep_seconds,
                ), flush=True)
                time.sleep(sleep_seconds)

    args.api_call_scan_completed = True
    print('[heartbeat] 本轮完成 success=%s delete_401=%s quota_exhausted=%s failed=%s usage_started=%s' % (
        total_heartbeat_success,
        total_heartbeat_delete_401,
        total_heartbeat_quota_exhausted,
        total_heartbeat_failed,
        total_usage_started,
    ), flush=True)
    return probe_results


def patch_auth_file_disabled(args, name, disabled):
    payload = {'name': name, 'disabled': bool(disabled)}
    attempts = []
    for method in AUTH_FILE_STATUS_METHODS:
        code, resp, _ = api(
            args.base_url,
            args.management_key,
            method,
            '/auth-files/status',
            args.timeout,
            expect_json=True,
            body=payload,
        )
        attempts.append({'method': method, 'code': code, 'response': resp})
        if 200 <= code < 300:
            return attempts[-1]
        if code not in (404, 405, 501):
            break
    raise RuntimeError('更新 auth-files/status 失败: %s' % attempts)


def load_state(path):
    if not path.exists():
        return {'version': 1, 'quota_accounts': {}}
    try:
        data = json.loads(path.read_text(encoding='utf-8'))
    except Exception:
        return {'version': 1, 'quota_accounts': {}}
    if not isinstance(data, dict):
        data = {}
    data.setdefault('version', 1)
    quota_accounts = data.get('quota_accounts')
    if not isinstance(quota_accounts, dict):
        quota_accounts = {}
    data['quota_accounts'] = quota_accounts
    return data


def save_state(path, data):
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(path.suffix + '.tmp')
    tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
    os.replace(tmp, path)


def parse_positive_number(value):
    if isinstance(value, bool):
        return None
    try:
        number = float(value)
    except Exception:
        return None
    if not math.isfinite(number) or number <= 0:
        return None
    return number


def compact_number(value):
    if value is None:
        return None
    try:
        number = float(value)
    except Exception:
        return value
    if math.isfinite(number) and number.is_integer():
        return int(number)
    return number


def utc_from_epoch_seconds(value):
    try:
        return datetime.fromtimestamp(value, timezone.utc)
    except Exception:
        return None


def quota_reason_payload(reason):
    if isinstance(reason, dict):
        return reason
    text = str(reason or '').strip()
    if not text or not text.startswith('{'):
        return None
    try:
        payload = json.loads(text)
    except Exception:
        return None
    return payload if isinstance(payload, dict) else None


def usage_limit_error_from_reason(reason):
    payload = quota_reason_payload(reason)
    if not isinstance(payload, dict):
        return None
    error_obj = payload.get('error')
    if isinstance(error_obj, dict):
        data = error_obj
    elif any(key in payload for key in ('type', 'resets_in_seconds', 'resets_at', 'plan_type')):
        data = payload
    else:
        return None
    error_type = str(data.get('type') or '').strip().lower()
    has_reset_hint = any(key in data for key in ('resets_in_seconds', 'resets_at'))
    if error_type and error_type != 'usage_limit_reached':
        return None
    if not error_type and not has_reset_hint:
        return None
    return data


def usage_limit_reset_buffer_seconds(args):
    value = getattr(args, 'usage_limit_reset_buffer_seconds', DEFAULT_USAGE_LIMIT_RESET_BUFFER_SECONDS)
    try:
        return max(0, int(value))
    except Exception:
        return DEFAULT_USAGE_LIMIT_RESET_BUFFER_SECONDS


def quota_reset_schedule_from_reason(reason, now, args, fallback_due):
    buffer_seconds = usage_limit_reset_buffer_seconds(args)
    decision = {
        'source': 'fallback',
        'next_revival_check_at': to_iso(fallback_due),
        'plan_type': '',
        'resets_in_seconds': None,
        'resets_at': None,
        'buffer_seconds': buffer_seconds,
    }
    error_obj = usage_limit_error_from_reason(reason)
    if not error_obj:
        return decision

    plan_type = str(error_obj.get('plan_type') or '').strip()
    if plan_type:
        decision['plan_type'] = plan_type

    resets_in_seconds = parse_positive_number(error_obj.get('resets_in_seconds'))
    resets_at = parse_positive_number(error_obj.get('resets_at'))
    if resets_in_seconds is not None:
        decision['resets_in_seconds'] = compact_number(resets_in_seconds)
    if resets_at is not None:
        reset_at_dt = utc_from_epoch_seconds(resets_at)
        if reset_at_dt and reset_at_dt > now:
            decision['resets_at'] = compact_number(resets_at)

    if resets_in_seconds is not None:
        due = now + timedelta(seconds=resets_in_seconds + buffer_seconds)
        decision['source'] = 'resets_in_seconds'
        decision['next_revival_check_at'] = to_iso(due)
    elif decision['resets_at'] is not None:
        reset_at_dt = utc_from_epoch_seconds(resets_at)
        if reset_at_dt:
            due = reset_at_dt + timedelta(seconds=buffer_seconds)
            decision['source'] = 'resets_at'
            decision['next_revival_check_at'] = to_iso(due)
    return decision


def apply_quota_reset_metadata(entry, decision):
    entry['quota_reset_source'] = decision.get('source') or 'fallback'
    entry['quota_reset_buffer_seconds'] = int(decision.get('buffer_seconds') or 0)
    optional_fields = {
        'quota_reset_plan_type': decision.get('plan_type'),
        'quota_reset_resets_in_seconds': decision.get('resets_in_seconds'),
        'quota_reset_resets_at': decision.get('resets_at'),
    }
    for key, value in optional_fields.items():
        if value is None or value == '':
            entry.pop(key, None)
        else:
            entry[key] = value


def ensure_quota_state(state, item, reason, args, force_reschedule=False):
    name = str(item.get('name') or item.get('id') or '').strip()
    if not name:
        return None
    now = datetime.now(timezone.utc)
    due = now + timedelta(days=args.revival_wait_days)
    reset_schedule = quota_reset_schedule_from_reason(reason, now, args, due)
    quota_accounts = state.setdefault('quota_accounts', {})
    entry = quota_accounts.get(name) or {}
    if not entry.get('quota_disabled_at'):
        entry['quota_disabled_at'] = to_iso(now)
    if force_reschedule or not entry.get('next_revival_check_at'):
        entry['next_revival_check_at'] = reset_schedule['next_revival_check_at']
        apply_quota_reset_metadata(entry, reset_schedule)
    entry['provider'] = str(item.get('provider') or item.get('type') or '').strip()
    entry['reason'] = str(reason or '')
    entry['path'] = str(item.get('path') or entry.get('path') or '').strip()
    entry['auth_index'] = item.get('auth_index')
    entry['email'] = str(item.get('email') or entry.get('email') or '').strip()
    account = str(item.get('account') or item.get('account_id') or entry.get('account_id') or '').strip()
    if account:
        entry['account_id'] = account
    entry['last_seen_at'] = iso_now()
    quota_accounts[name] = entry
    return entry


def clear_quota_state(state, name):
    quota_accounts = state.get('quota_accounts') or {}
    if name in quota_accounts:
        del quota_accounts[name]
        return True
    return False


def backup_bytes(base_dir, name, suffix, raw):
    base_dir.mkdir(parents=True, exist_ok=True)
    file_name = Path(str(name or 'unknown.json')).name
    target = base_dir / (file_name + suffix)
    target.write_bytes(raw)
    return target


def backup_json_file(base_dir, path):
    base_dir.mkdir(parents=True, exist_ok=True)
    src = Path(path)
    target = base_dir / src.name
    target.write_bytes(src.read_bytes())
    return target


def delete_auth_file(args, name, backup_root):
    code, raw, _ = api(args.base_url, args.management_key, 'GET', '/auth-files/download', args.timeout, {'name': name}, False)
    if code != 200:
        raise RuntimeError('下载 auth 文件失败: %s HTTP %s' % (name, code))
    backup_path = backup_bytes(backup_root, name, '', raw)
    code, payload, _ = api(args.base_url, args.management_key, 'DELETE', '/auth-files', args.timeout, {'name': name}, True)
    if code != 200:
        raise RuntimeError('删除 auth 文件失败: %s HTTP %s %s' % (name, code, payload))
    return backup_path, payload


def parse_jwt_payload(token):
    text = str(token or '').strip()
    if not text or text.count('.') < 2:
        return {}
    try:
        payload_part = text.split('.')[1]
        padding = '=' * (-len(payload_part) % 4)
        raw = base64.urlsafe_b64decode(payload_part + padding)
        data = json.loads(raw.decode('utf-8'))
        if isinstance(data, dict):
            return data
    except Exception:
        pass
    return {}


def load_auth_payload_from_path(path):
    data = json.loads(Path(path).read_text(encoding='utf-8'))
    if not isinstance(data, dict):
        raise RuntimeError('auth 文件不是对象 JSON')
    return data


def write_auth_payload(path, payload):
    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    tmp = target.with_suffix(target.suffix + '.tmp')
    tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
    os.replace(tmp, target)


def refresh_openai_family_tokens(auth_payload, timeout=20):
    refresh_token = str(auth_payload.get('refresh_token') or '').strip()
    if not refresh_token:
        raise RuntimeError('missing refresh token')
    form = parse.urlencode({
        'client_id': OPENAI_CLIENT_ID,
        'grant_type': 'refresh_token',
        'refresh_token': refresh_token,
        'scope': OPENAI_SCOPE,
    }).encode('utf-8')
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json',
        'User-Agent': 'cliproxyapi-cleaner/2.0',
    }
    req = request.Request(OPENAI_TOKEN_URL, data=form, headers=headers, method='POST')
    try:
        with request.urlopen(req, timeout=timeout) as resp:
            raw = resp.read()
            code = resp.getcode()
    except error.HTTPError as e:
        raw = e.read()
        code = e.code
    except error.URLError as e:
        raise RuntimeError('refresh request failed: %s' % e)

    text = raw.decode('utf-8', errors='replace') if raw else ''
    if code != 200:
        raise RuntimeError('token refresh failed with status %s: %s' % (code, text))
    try:
        token_resp = json.loads(text) if text else {}
    except Exception as e:
        raise RuntimeError('failed to parse refresh response: %s' % e)

    access_token = str(token_resp.get('access_token') or '').strip()
    if not access_token:
        raise RuntimeError('refresh response missing access_token: %s' % token_resp)

    new_payload = dict(auth_payload)
    new_payload['access_token'] = access_token
    if token_resp.get('refresh_token'):
        new_payload['refresh_token'] = token_resp.get('refresh_token')
    if token_resp.get('id_token'):
        new_payload['id_token'] = token_resp.get('id_token')
    new_payload['last_refresh'] = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
    new_payload['expired'] = False

    claims = parse_jwt_payload(new_payload.get('id_token'))
    if claims.get('email'):
        new_payload['email'] = claims.get('email')
    account_candidates = [
        claims.get('https://api.openai.com/profile/account_id'),
        claims.get('account_id'),
        claims.get('org_id'),
    ]
    for candidate in account_candidates:
        value = str(candidate or '').strip()
        if value:
            new_payload['account_id'] = value
            break
    return new_payload, token_resp


def direct_probe_auth(args, item, auth_payload):
    access_token = str(auth_payload.get('access_token') or '').strip()
    if not access_token:
        raise RuntimeError('缺少 access_token,无法测活')

    headers = {
        'Authorization': 'Bearer ' + access_token,
        'User-Agent': args.api_call_user_agent,
        'Accept': 'application/json',
    }
    account_id = choose_account_id(item, args, auth_payload)
    if account_id:
        headers['Chatgpt-Account-Id'] = account_id

    body = None
    if args.api_call_body:
        text = args.api_call_body
        try:
            body = json.loads(text)
        except Exception:
            body = text

    response_payload = request_json_or_text(
        args.api_call_url.strip(),
        method=args.api_call_method.upper(),
        timeout=args.timeout,
        body=body,
        headers=headers,
    )
    classification, reason = classify_api_call_response(response_payload)
    return {
        'classification': classification,
        'reason': reason,
        'response': response_payload,
    }


def is_delete_worthy(text):
    signal = str(text or '').strip()
    if not signal:
        return False
    lowered = signal.lower()
    return bool(P401.search(lowered) or PREMOVE.search(lowered))


def next_revival_due(now, args):
    return to_iso(now + timedelta(hours=args.revival_probe_interval_hours))


def run_revival_cycle(args, item, state_entry, counts, backup_root):
    name = str(item.get('name') or item.get('id') or '').strip()
    provider = str(item.get('provider') or item.get('type') or '').strip().lower()
    row = {
        'name': name,
        'provider': provider,
        'auth_index': item.get('auth_index'),
        'path': item.get('path') or state_entry.get('path'),
        'revival_cycle': True,
    }
    counts['复活待检查'] += 1
    now = datetime.now(timezone.utc)
    state_entry['last_revival_check_at'] = to_iso(now)

    if provider not in ('codex', 'openai', 'chatgpt'):
        row['revival_result'] = 'skip_unsupported_provider'
        row['reason'] = 'provider 不在 codex/openai/chatgpt 范围内'
        state_entry['next_revival_check_at'] = next_revival_due(now, args)
        return row

    path = str(item.get('path') or state_entry.get('path') or '').strip()
    if not path:
        row['revival_result'] = 'skip_missing_path'
        row['reason'] = '缺少本地文件路径,无法刷新并写回 token'
        state_entry['next_revival_check_at'] = next_revival_due(now, args)
        return row

    try:
        auth_payload = load_auth_payload_from_path(path)
        row['auth_payload_loaded'] = True
    except Exception as e:
        row['revival_result'] = 'load_failed'
        row['reason'] = str(e)
        if is_delete_worthy(e):
            try:
                backup_path, delete_resp = delete_auth_file(args, name, backup_root / 'delete-on-load-failed')
                counts['复活删除'] += 1
                row['revival_result'] = 'deleted_on_load_failure'
                row['backup_path'] = str(backup_path)
                row['delete_response'] = delete_resp
            except Exception as delete_err:
                row['delete_error'] = str(delete_err)
                state_entry['next_revival_check_at'] = next_revival_due(now, args)
        else:
            state_entry['next_revival_check_at'] = next_revival_due(now, args)
        return row

    counts['refresh尝试'] += 1
    try:
        before_backup = backup_json_file(backup_root / 'before-refresh', path)
        refreshed_payload, refresh_resp = refresh_openai_family_tokens(auth_payload, timeout=args.timeout)
        write_auth_payload(path, refreshed_payload)
        counts['refresh成功'] += 1
        row['refresh_result'] = 'ok'
        row['refresh_backup'] = str(before_backup)
        row['refresh_response_keys'] = sorted(refresh_resp.keys()) if isinstance(refresh_resp, dict) else []
    except Exception as e:
        counts['refresh失败'] += 1
        row['refresh_result'] = 'failed'
        row['reason'] = str(e)
        state_entry['last_error'] = str(e)
        if is_delete_worthy(e):
            try:
                backup_path, delete_resp = delete_auth_file(args, name, backup_root / 'delete-on-refresh-failed')
                counts['复活删除'] += 1
                row['revival_result'] = 'deleted_on_refresh_failure'
                row['backup_path'] = str(backup_path)
                row['delete_response'] = delete_resp
            except Exception as delete_err:
                row['delete_error'] = str(delete_err)
                state_entry['next_revival_check_at'] = next_revival_due(now, args)
        else:
            state_entry['next_revival_check_at'] = next_revival_due(now, args)
        return row

    try:
        current_payload = load_auth_payload_from_path(path)
        probe = direct_probe_auth(args, item, current_payload)
        row['probe'] = probe
        classification = probe.get('classification') or 'ok'
        row['revival_classification'] = classification
        row['reason'] = probe.get('reason') or ''
    except Exception as e:
        row['revival_result'] = 'probe_failed'
        row['reason'] = str(e)
        state_entry['last_error'] = str(e)
        state_entry['next_revival_check_at'] = next_revival_due(now, args)
        return row

    classification = row.get('revival_classification')
    if classification in (None, 'ok'):
        try:
            disable_resp = patch_auth_file_disabled(args, name, False)
            counts['复活成功启用'] += 1
            row['revival_result'] = 'enabled'
            row['enable_response'] = disable_resp
            return row
        except Exception as e:
            row['revival_result'] = 'enable_failed'
            row['reason'] = str(e)
            state_entry['last_error'] = str(e)
            state_entry['next_revival_check_at'] = next_revival_due(now, args)
            return row

    if classification == 'quota_exhausted':
        counts['复活仍限额'] += 1
        row['revival_result'] = 'still_quota_exhausted'
        try:
            row['disable_response'] = patch_auth_file_disabled(args, name, True)
        except Exception as e:
            row['disable_error'] = str(e)
        state_entry['last_error'] = simplify_reason(row.get('reason'))
        retry_due = now + timedelta(hours=args.revival_probe_interval_hours)
        reset_schedule = quota_reset_schedule_from_reason(row.get('reason'), now, args, retry_due)
        state_entry['next_revival_check_at'] = reset_schedule['next_revival_check_at']
        apply_quota_reset_metadata(state_entry, reset_schedule)
        row['revival_reschedule'] = reset_schedule
        return row

    if classification == 'delete_401' or is_delete_worthy(row.get('reason')):
        try:
            backup_path, delete_resp = delete_auth_file(args, name, backup_root / 'delete-on-bad-probe')
            counts['复活删除'] += 1
            row['revival_result'] = 'deleted_on_bad_probe'
            row['backup_path'] = str(backup_path)
            row['delete_response'] = delete_resp
            return row
        except Exception as e:
            row['revival_result'] = 'delete_failed'
            row['delete_error'] = str(e)
            state_entry['last_error'] = str(e)
            state_entry['next_revival_check_at'] = next_revival_due(now, args)
            return row

    row['revival_result'] = 'retry_later'
    state_entry['last_error'] = simplify_reason(row.get('reason'))
    state_entry['next_revival_check_at'] = next_revival_due(now, args)
    return row


def run_check(args):
    args.api_call_scan_completed = False
    code, payload, _ = api(args.base_url, args.management_key, 'GET', '/auth-files', args.timeout)
    if code != 200:
        print('[错误] 获取 auth-files 失败: HTTP %s %s' % (code, payload), file=sys.stderr)
        return None

    files = payload.get('files') or []
    if not isinstance(files, list):
        print('[错误] auth-files 返回异常: %s' % payload, file=sys.stderr)
        return None

    rid = run_id()
    backup_root = args.backup_root / rid
    report_root = args.report_root
    report_root.mkdir(parents=True, exist_ok=True)
    state = load_state(args.state_path)

    counts = {
        '检查总数': 0,
        '可用账号': 0,
        '配额耗尽': 0,
        '已禁用': 0,
        '不可用': 0,
        'api-call候选数': 0,
        'api-call批次数': 0,
        'api-call已探测': 0,
        'api-call发现401': 0,
        'api-call发现配额耗尽': 0,
        'api-call探测失败': 0,
        '心跳成功': 0,
        '心跳401': 0,
        '心跳配额耗尽': 0,
        '心跳失败': 0,
        '进入usage探测': 0,
        '待删除401': 0,
        '已删除': 0,
        '备份失败': 0,
        '删除失败': 0,
        '额度账号已禁用': 0,
        '禁用失败': 0,
        '复活待检查': 0,
        'refresh尝试': 0,
        'refresh成功': 0,
        'refresh失败': 0,
        '复活成功启用': 0,
        '复活仍限额': 0,
        '复活删除': 0,
        '状态清理': 0,
    }
    results = []
    name_to_item = {}

    print('[%s] 开始检查 %s 个账号' % (get_current_time(), len(files)), flush=True)
    probe_results = run_api_call_full_scan(args, files, counts)

    for item in files:
        counts['检查总数'] += 1
        name = str(item.get('name') or item.get('id') or '').strip()
        provider = str(item.get('provider') or item.get('type') or '').strip()
        kind, reason = classify(item)
        row = {
            'name': name,
            'provider': provider,
            'auth_index': item.get('auth_index'),
            'status': item.get('status'),
            'status_message': item.get('status_message'),
            'disabled': item.get('disabled'),
            'unavailable': item.get('unavailable'),
            'runtime_only': item.get('runtime_only'),
            'source': item.get('source'),
            'path': item.get('path'),
        }
        if name:
            name_to_item[name] = item

        probe = probe_results.get(api_call_item_key(item))
        if probe is not None:
            row['api_call_probe'] = probe
            if probe.get('classification') == 'delete_401':
                kind = 'delete_401'
                reason = probe.get('reason') or reason
            elif probe.get('classification') == 'quota_exhausted':
                kind = 'quota_exhausted'
                reason = probe.get('reason') or reason

        row['final_classification'] = kind
        row['reason'] = reason
        display_reason = simplify_reason(reason)

        if kind == 'available':
            counts['可用账号'] += 1
            if name and not bool(item.get('disabled')) and clear_quota_state(state, name):
                counts['状态清理'] += 1
                row['state_cleared'] = 'became_available'

        elif kind == 'quota_exhausted':
            counts['配额耗尽'] += 1
            print('[配额耗尽] %s provider=%s reason=%s' % (name, provider, display_reason), flush=True)
            if args.dry_run:
                row['disable_result'] = 'dry_run_skip'
                print(' [模拟运行] 将调用 /auth-files/status 设置 disabled=true', flush=True)
            elif not name:
                counts['禁用失败'] += 1
                row['disable_result'] = 'skip_no_name'
                row['disable_error'] = '缺少 name,无法调用 /auth-files/status'
                print(' [禁用失败] 缺少 name,无法更新状态', flush=True)
            else:
                try:
                    disable_resp = patch_auth_file_disabled(args, name, True)
                    counts['额度账号已禁用'] += 1
                    row['disable_result'] = 'disabled_true'
                    row['disable_response'] = disable_resp
                    state_entry = ensure_quota_state(
                        state,
                        item,
                        reason,
                        args,
                        force_reschedule=bool(probe and probe.get('classification') == 'quota_exhausted'),
                    )
                    row['revival_tracking'] = state_entry
                    print(' [已禁用] method=%s HTTP %s,下次 refresh + 测活: %s (source=%s)' % (
                        disable_resp['method'], disable_resp['code'],
                        state_entry.get('next_revival_check_at') if state_entry else '',
                        state_entry.get('quota_reset_source') if state_entry else 'fallback',
                    ), flush=True)
                except Exception as e:
                    counts['禁用失败'] += 1
                    row['disable_result'] = 'disable_failed'
                    row['disable_error'] = str(e)
                    print(' [禁用失败] %s' % e, flush=True)

        elif kind == 'disabled':
            counts['已禁用'] += 1
            print('[已禁用-不直接删除] %s provider=%s' % (name, provider), flush=True)

        elif kind == 'unavailable':
            counts['不可用'] += 1
            print('[不可用-不删除] %s provider=%s reason=%s' % (name, provider, display_reason), flush=True)

        elif kind == 'delete_401':
            counts['待删除401'] += 1
            print('[待删除-401认证失败] %s provider=%s reason=%s' % (name, provider, display_reason), flush=True)
            if args.dry_run:
                row['delete_result'] = 'dry_run_skip'
                print(' [模拟运行] 将删除此文件', flush=True)
            else:
                runtime_only = bool(item.get('runtime_only', False))
                source = str(item.get('source') or '').strip().lower()
                if runtime_only or (source and source != 'file'):
                    counts['备份失败'] += 1
                    row['delete_result'] = 'skip_runtime_only'
                    row['delete_error'] = 'runtime_only/source!=file,管理 API 无法删除'
                    print(' [跳过] runtime_only 或非磁盘文件,无法通过 /auth-files 删除', flush=True)
                elif not name.lower().endswith('.json'):
                    counts['备份失败'] += 1
                    row['delete_result'] = 'skip_no_json_name'
                    row['delete_error'] = '不是标准 .json 文件名,默认不删'
                    print(' [跳过] 不是 .json 文件', flush=True)
                else:
                    try:
                        backup_path, delete_resp = delete_auth_file(args, name, backup_root / 'delete-401')
                        counts['已删除'] += 1
                        row['delete_result'] = 'deleted'
                        row['backup_path'] = str(backup_path)
                        row['delete_response'] = delete_resp
                        clear_quota_state(state, name)
                        print(' [已删除] 备份路径: %s' % row['backup_path'], flush=True)
                    except Exception as e:
                        counts['删除失败'] += 1
                        row['delete_result'] = 'delete_failed'
                        row['delete_error'] = str(e)
                        print(' [删除失败] %s' % e, flush=True)

        results.append(row)

    for name in list((state.get('quota_accounts') or {}).keys()):
        if name not in name_to_item:
            clear_quota_state(state, name)
            counts['状态清理'] += 1

    if not args.dry_run:
        now = datetime.now(timezone.utc)
        for name, entry in sorted((state.get('quota_accounts') or {}).items()):
            item = name_to_item.get(name)
            if not item:
                continue
            due_at = parse_time(entry.get('next_revival_check_at'))
            if due_at and due_at > now:
                continue
            revival_row = run_revival_cycle(args, item, entry, counts, backup_root)
            results.append(revival_row)
            result_tag = revival_row.get('revival_result')
            if result_tag in ('enabled', 'deleted_on_refresh_failure', 'deleted_on_bad_probe', 'deleted_on_load_failure'):
                clear_quota_state(state, name)

    save_state(args.state_path, state)

    report = {
        'run_id': rid,
        'base_url': normalize_base_url(args.base_url),
        'dry_run': args.dry_run,
        'api_call': {
            'enabled': args.enable_api_call_check,
            'completed_in_this_process': bool(getattr(args, 'api_call_scan_completed', False)),
            'providers': args.api_call_providers,
            'url': args.api_call_url,
            'batch_size': args.api_call_max_per_run,
            'sleep_fixed': args.api_call_sleep,
            'sleep_min': args.api_call_sleep_min,
            'sleep_max': args.api_call_sleep_max,
        },
        'revival': {
            'wait_days': args.revival_wait_days,
            'probe_interval_hours': args.revival_probe_interval_hours,
            'usage_limit_reset_buffer_seconds': usage_limit_reset_buffer_seconds(args),
            'state_path': str(args.state_path),
        },
        'results': results,
        'summary': counts,
        'state': state,
    }
    report_path = report_root / ('report-' + rid + '.json')
    report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')

    print('\n' + '=' * 60)
    print('【统计结果】')
    print('=' * 60)
    for key, value in counts.items():
        print(' %s: %d' % (key, value))

    print('\n【操作说明】')
    if args.dry_run:
        print(' ✅ 模拟运行模式 - 没有实际删除、禁用或刷新任何账号')
        if counts['待删除401'] > 0:
            print(' 📝 发现 %d 个 401 认证失败账号(去掉 --dry-run 后会备份并删除)' % counts['待删除401'])
        if counts['配额耗尽'] > 0:
            print(' 📝 发现 %d 个额度耗尽账号(去掉 --dry-run 后会调用 /auth-files/status 禁用)' % counts['配额耗尽'])
    else:
        print(' ✅ 已删除 %d 个 401 认证失败账号' % counts['已删除'])
        print(' ✅ 已禁用 %d 个额度耗尽账号' % counts['额度账号已禁用'])
        print(' ✅ 复活成功启用 %d 个账号' % counts['复活成功启用'])
        if counts['复活仍限额'] > 0:
            print(' 🕒 仍有 %d 个账号处于限额,已安排 12h 后再次 refresh + 测活' % counts['复活仍限额'])
        if counts['复活删除'] > 0:
            print(' 🗑️ 复活检查中删除 %d 个异常账号' % counts['复活删除'])
        if counts['删除失败'] > 0:
            print(' ⚠️ 有 %d 个账号删除失败,请查看报告' % counts['删除失败'])
        if counts['禁用失败'] > 0:
            print(' ⚠️ 有 %d 个额度账号禁用失败,请查看报告' % counts['禁用失败'])
        if counts['refresh失败'] > 0:
            print(' ⚠️ 有 %d 次 refresh 失败,请查看报告' % counts['refresh失败'])

    print('\n【报告文件】')
    print(' 📄 %s' % report_path)
    print('=' * 60, flush=True)
    return counts


def build_parser():
    ap = argparse.ArgumentParser(description='CLIProxyAPI 清理工具 - 删除 401 账号、禁用额度耗尽账号,并按上游 reset/等待期策略尝试复活')
    ap.add_argument('--base-url', default=os.environ.get('CLIPROXY_BASE_URL', DEFAULT_BASE_URL))
    ap.add_argument('--management-key', default=os.environ.get('CLIPROXY_MANAGEMENT_KEY', DEFAULT_MANAGEMENT_KEY))
    ap.add_argument('--timeout', type=int, default=int(os.environ.get('CLIPROXY_TIMEOUT', '20')))
    ap.add_argument('--enable-api-call-check', dest='enable_api_call_check', action='store_true', default=env_bool('CLIPROXY_ENABLE_API_CALL_CHECK', True), help='开启 /api-call 全量探测;本次脚本运行只会完整探测一遍')
    ap.add_argument('--disable-api-call-check', dest='enable_api_call_check', action='store_false', help='关闭 /api-call 全量探测')
    ap.add_argument('--enable-pre-usage-probe', dest='pre_usage_probe_enabled', action='store_true', default=env_bool('CLIPROXY_PRE_USAGE_PROBE_ENABLED', True), help='开启 usage 探测前的预探测请求')
    ap.add_argument('--disable-pre-usage-probe', dest='pre_usage_probe_enabled', action='store_false', help='关闭 usage 探测前的预探测请求')
    ap.add_argument('--pre-usage-probe-url', default=os.environ.get('CLIPROXY_PRE_USAGE_PROBE_URL', ''), help='预探测请求的上游 URL')
    ap.add_argument('--pre-usage-probe-method', default=os.environ.get('CLIPROXY_PRE_USAGE_PROBE_METHOD', 'POST'), help='预探测请求的 HTTP 方法')
    ap.add_argument('--pre-usage-probe-body', default=os.environ.get('CLIPROXY_PRE_USAGE_PROBE_BODY', ''), help='预探测请求的 body')
    ap.add_argument('--pre-usage-probe-sleep-seconds', type=float, default=float(os.environ.get('CLIPROXY_PRE_USAGE_PROBE_SLEEP_SECONDS', str(DEFAULT_PRE_USAGE_PROBE_SLEEP_SECONDS))), help='预探测成功后到 usage 探测前的等待秒数')
    ap.add_argument('--api-call-url', default=os.environ.get('CLIPROXY_API_CALL_URL', DEFAULT_API_CALL_URL), help='主动探测时调用的上游 URL')
    ap.add_argument('--api-call-method', default=os.environ.get('CLIPROXY_API_CALL_METHOD', 'GET'), help='主动探测时使用的 HTTP 方法')
    ap.add_argument('--api-call-account-id', default=os.environ.get('CLIPROXY_API_CALL_ACCOUNT_ID', DEFAULT_API_CALL_ACCOUNT_ID), help='主动探测时附带的 Chatgpt-Account-Id(若 auth 文件内有 account_id 会优先使用文件值)')
    ap.add_argument('--api-call-user-agent', default=os.environ.get('CLIPROXY_API_CALL_USER_AGENT', DEFAULT_API_CALL_USER_AGENT), help='主动探测时附带的 User-Agent')
    ap.add_argument('--api-call-body', default=os.environ.get('CLIPROXY_API_CALL_BODY', ''), help='主动探测时透传到 api-call/直连测活的 data 字段')
    ap.add_argument('--api-call-providers', default=os.environ.get('CLIPROXY_API_CALL_PROVIDERS', DEFAULT_API_CALL_PROVIDERS), help='哪些 provider 需要做 /api-call 主动探测,逗号分隔;留空表示全部')
    ap.add_argument('--api-call-max-per-run', type=int, default=int(os.environ.get('CLIPROXY_API_CALL_MAX_PER_RUN', str(DEFAULT_API_CALL_MAX_PER_RUN))), help='每批最多探测多少个账号,最大 9')
    ap.add_argument('--api-call-sleep', type=float, default=None, help='固定批次等待秒数;如不设置则使用随机等待')
    ap.add_argument('--api-call-sleep-min', type=float, default=float(os.environ.get('CLIPROXY_API_CALL_SLEEP_MIN', str(DEFAULT_API_CALL_SLEEP_MIN))), help='批次随机等待最小秒数')
    ap.add_argument('--api-call-sleep-max', type=float, default=float(os.environ.get('CLIPROXY_API_CALL_SLEEP_MAX', str(DEFAULT_API_CALL_SLEEP_MAX))), help='批次随机等待最大秒数')
    ap.add_argument('--revival-wait-days', type=int, default=int(os.environ.get('CLIPROXY_REVIVAL_WAIT_DAYS', str(DEFAULT_REVIVAL_WAIT_DAYS))), help='额度耗尽账号禁用后,若上游未返回 reset 时间,等待多少天再用 refresh token 尝试复活')
    ap.add_argument('--revival-probe-interval-hours', type=int, default=int(os.environ.get('CLIPROXY_REVIVAL_PROBE_INTERVAL_HOURS', str(DEFAULT_REVIVAL_INTERVAL_HOURS))), help='复活探测后仍未恢复且无新的 reset 时间时,后续每隔多少小时再次 refresh + 测活')
    ap.add_argument('--usage-limit-reset-buffer-seconds', type=int, default=int(os.environ.get('CLIPROXY_USAGE_LIMIT_RESET_BUFFER_SECONDS', str(DEFAULT_USAGE_LIMIT_RESET_BUFFER_SECONDS))), help='usage_limit_reached 上游 reset 时间后额外等待多少秒再尝试复活')
    ap.add_argument('--state-file', default=os.environ.get('CLIPROXY_STATE_FILE', str(script_dir() / DEFAULT_STATE_FILE)), help='持久化状态文件路径')
    ap.add_argument('--dry-run', action='store_true', help='模拟运行,不实际删除、禁用或刷新')
    ap.add_argument('--interval', type=int, default=None, help='兼容旧配置:固定轮询秒数;如设置则等同于 interval_min = interval_max = 该值')
    ap.add_argument('--interval-min', type=int, default=int(os.environ.get('CLIPROXY_INTERVAL_MIN', '1800')), help='随机轮询的最小秒数,默认 1800')
    ap.add_argument('--interval-max', type=int, default=int(os.environ.get('CLIPROXY_INTERVAL_MAX', '3600')), help='随机轮询的最大秒数,默认 3600')
    ap.add_argument('--once', action='store_true', help='只执行一次,不循环')
    return ap


def main():
    ap = build_parser()
    args = ap.parse_args()

    args.base_url = normalize_base_url(args.base_url)
    if getattr(args, 'pre_usage_probe_url', '').strip():
        args.pre_usage_probe_url = args.pre_usage_probe_url.strip()
    args.pre_usage_probe_method = str(getattr(args, 'pre_usage_probe_method', 'POST') or 'POST').upper()
    args.pre_usage_probe_sleep_seconds = max(0.0, float(getattr(args, 'pre_usage_probe_sleep_seconds', DEFAULT_PRE_USAGE_PROBE_SLEEP_SECONDS)))
    args.api_call_provider_set = parse_csv_set(args.api_call_providers)
    args.api_call_max_per_run = max(0, min(int(args.api_call_max_per_run), DEFAULT_API_CALL_MAX_PER_RUN))
    if args.api_call_sleep is not None:
        args.api_call_sleep = max(0.0, float(args.api_call_sleep))
    args.api_call_sleep_min = max(0.0, float(args.api_call_sleep_min))
    args.api_call_sleep_max = max(args.api_call_sleep_min, float(args.api_call_sleep_max))
    args.api_call_scan_completed = False
    if args.interval is not None:
        fixed_interval = max(10, int(args.interval))
        args.interval_min = fixed_interval
        args.interval_max = fixed_interval
    else:
        args.interval_min = max(10, int(getattr(args, 'interval_min', 1800)))
        args.interval_max = max(args.interval_min, int(getattr(args, 'interval_max', 3600)))
    args.revival_wait_days = max(0, int(args.revival_wait_days))
    args.revival_probe_interval_hours = max(1, int(args.revival_probe_interval_hours))
    args.usage_limit_reset_buffer_seconds = max(
        0,
        int(getattr(args, 'usage_limit_reset_buffer_seconds', DEFAULT_USAGE_LIMIT_RESET_BUFFER_SECONDS)),
    )
    args.state_path = Path(args.state_file).expanduser().resolve()
    backup_root_env = os.environ.get('CLIPROXY_BACKUP_ROOT')
    report_root_env = os.environ.get('CLIPROXY_REPORT_ROOT')
    args.backup_root = Path(backup_root_env).expanduser().resolve() if backup_root_env else (script_dir() / 'backups' / 'cliproxyapi-auth-cleaner')
    args.report_root = Path(report_root_env).expanduser().resolve() if report_root_env else (script_dir() / 'reports' / 'cliproxyapi-auth-cleaner')

    if not args.management_key.strip():
        print('❌ 缺少 management key:请先设置 CLIPROXY_MANAGEMENT_KEY', file=sys.stderr)
        return 2

    print('\n' + '=' * 60)
    print('【CLIProxyAPI 清理工具】')
    print('=' * 60)
    print(' 🎯 清理目标: 删除 401 认证失败账号 + 禁用额度耗尽账号 + 按上游 reset/等待期 refresh 复活 + 周期测活')
    print(' 🌐 管理地址: %s' % args.base_url)
    if args.enable_api_call_check:
        providers_desc = args.api_call_providers if args.api_call_providers.strip() else '全部 provider'
        sleep_desc = '固定 %.1f 秒' % args.api_call_sleep if args.api_call_sleep is not None else '随机 %.1f-%.1f 秒' % (args.api_call_sleep_min, args.api_call_sleep_max)
        print(' 🔎 主动探测: 已开启 /v0/management/api-call')
        print(' - 上游 URL: %s' % args.api_call_url)
        print(' - 适用 provider: %s' % providers_desc)
        print(' - 单批最多: %s 个' % args.api_call_max_per_run)
        print(' - 批次间隔: %s' % sleep_desc)
        print(' - 探测策略: 每轮检测都会重新执行 heartbeat / api-call 探测')
    else:
        print(' 🔎 主动探测: 已关闭 /v0/management/api-call')
    print(' ♻️ 复活策略: 优先按上游 reset + %d 秒缓冲;无 reset 时等待 %d 天,仍未恢复则每 %d 小时重试' % (
        args.usage_limit_reset_buffer_seconds, args.revival_wait_days, args.revival_probe_interval_hours,
    ))
    if args.dry_run:
        print(' 🔍 运行模式: 模拟运行(不会实际删除、禁用或刷新)')
    else:
        print(' ⚡ 运行模式: 实际运行(将删除/禁用/刷新符合条件的账号)')
    print('=' * 60 + '\n')

    if args.once:
        run_check(args)
        return 0

    print('🔁 自动循环检测模式,等待区间 %d-%d 秒' % (args.interval_min, args.interval_max))
    print('💡 提示: 按 Ctrl+C 停止程序\n')

    loop_count = 0
    try:
        while True:
            loop_count += 1
            print('\n' + '🔵' * 30)
            print('【第 %d 次检测】%s' % (loop_count, get_current_time()))
            print('🔵' * 30)
            try:
                run_check(args)
            except Exception as e:
                print('❌ 检测过程中发生异常: %s' % e, flush=True)
            next_interval = pick_loop_interval_seconds(args)
            print('\n⏰ 等待 %d 秒后进行下一次检测...' % next_interval)
            time.sleep(next_interval)
    except KeyboardInterrupt:
        print('\n\n🛑 用户中断程序,共执行 %d 次检测' % loop_count)
        return 0


if __name__ == '__main__':
    raise SystemExit(main())