File size: 90,091 Bytes
8deacaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
import ast
import io
import json
import os
import subprocess
import sys
import tempfile
import unittest
from contextlib import redirect_stderr, redirect_stdout
from pathlib import Path
from unittest.mock import patch
from uuid import uuid4

sys.path.insert(0, str(Path(__file__).parent.parent.parent))

import cli
from app.config import config as app_config
from app.models import schema as app_schema
from app.models.schema import VideoTransitionMode


class TestCli(unittest.TestCase):
    def setUp(self):
        # ``build_video_params`` 会读取本地 config.toml 的 [ui] 段作为默认值。
        # 不做隔离时,这些测试就依赖开发机的状态:配置里保存的字体一旦已被
        # 删除,``prepare_cli_files`` 的字体校验就会触发,让与此无关的测试以
        # 误导性的报错失败。
        ui_patch = patch.dict(app_config.ui, {}, clear=True)
        ui_patch.start()
        self.addCleanup(ui_patch.stop)

    def test_default_voice_is_valid_edge_tts_voice(self):
        args = cli.parse_args(["--video-subject", "测试主题"])
        params = cli.build_video_params(args)

        self.assertEqual(params.voice_name, "zh-CN-XiaoxiaoNeural-Female")

    def test_video_fit_mode_defaults_to_cover_and_accepts_contain(self):
        default_params = cli.build_video_params(
            cli.parse_args(["--video-subject", "test"])
        )
        contain_params = cli.build_video_params(
            cli.parse_args(
                [
                    "--video-subject",
                    "test",
                    "--video-fit-mode",
                    "contain",
                ]
            )
        )

        self.assertEqual(default_params.video_fit_mode.value, "cover")
        self.assertEqual(contain_params.video_fit_mode.value, "contain")

    def test_zoom_transition_modes_are_reachable_from_the_cli(self):
        # Every transition the render pipeline understands must also be
        # selectable from the CLI. Deriving the expectation from the enum stops
        # the two lists from drifting apart again.
        cli_modes = set(cli._TRANSITION_MODE_VALUES.values()) - {None}
        pipeline_modes = {
            mode.value
            for mode in VideoTransitionMode
            if mode is not VideoTransitionMode.none
        }
        self.assertEqual(cli_modes, pipeline_modes)

        zoom_params = cli.build_video_params(
            cli.parse_args(
                ["--video-subject", "test", "--video-transition-mode", "zoom-in"]
            )
        )

        self.assertEqual(zoom_params.video_transition_mode.value, "ZoomIn")

    def test_complete_script_can_replace_video_subject(self):
        args = cli.parse_args(["--video-script", "完整的视频文案"])
        params = cli.build_video_params(args)

        self.assertEqual(params.video_subject, "")
        self.assertEqual(params.video_script, "完整的视频文案")

    def test_subject_or_script_is_required(self):
        with self.assertRaises(SystemExit) as cm:
            cli.parse_args([])

        self.assertEqual(cm.exception.code, 2)

    def test_build_video_params_with_local_materials(self):
        args = cli.parse_args(
            [
                "--video-subject",
                "测试主题",
                "--video-source",
                "local",
                "--video-materials",
                "a.mp4, ,b.jpg,",
                "--video-terms",
                "foo, bar",
            ]
        )

        params = cli.build_video_params(args)
        materials = params.video_materials

        self.assertEqual(params.video_subject, "测试主题")
        self.assertEqual(params.video_source, "local")
        self.assertEqual([m.url for m in materials], ["a.mp4", "b.jpg"])
        self.assertTrue(all(m.provider == "local" for m in materials))
        self.assertEqual(params.video_terms, ["foo", "bar"])

    def test_run_cli_dispatches_task_start(self):
        with patch("app.services.task.start", return_value={"script": "ok"}) as start, patch(
            "app.utils.utils.get_uuid", return_value="task-123"
        ), patch("builtins.print") as print_mock:
            code = cli.run_cli(["--video-subject", "命令行测试", "--stop-at", "script"])

        self.assertEqual(code, 0)
        self.assertTrue(start.called)
        kwargs = start.call_args.kwargs
        self.assertEqual(kwargs["task_id"], "task-123")
        self.assertEqual(kwargs["stop_at"], "script")
        self.assertEqual(kwargs["params"].video_subject, "命令行测试")
        self.assertIs(kwargs["allow_server_file_input"], True)
        print_mock.assert_called_once()

    def test_force_utf8_console_keeps_unicode_result_printable(self):
        """旧版 Windows 代码页下,成功结果中的 Unicode 字符不应让 CLI 失败。"""
        stdout_buffer = io.BytesIO()
        stderr_buffer = io.BytesIO()
        # 使用 errors="strict" 还原问题现场:如果入口没有先切换到 UTF-8,
        # U+202F 窄不换行空格和带圈数字都会在 cp1252 编码阶段直接抛异常。
        legacy_stdout = io.TextIOWrapper(
            stdout_buffer,
            encoding="cp1252",
            errors="strict",
        )
        legacy_stderr = io.TextIOWrapper(
            stderr_buffer,
            encoding="cp1252",
            errors="strict",
        )
        result = {"script": "Température 18\u202f°C ⑤"}

        with (
            patch.object(cli.sys, "stdout", legacy_stdout),
            patch.object(cli.sys, "stderr", legacy_stderr),
            patch("app.services.task.start", return_value=result),
            patch("app.utils.utils.get_uuid", return_value="task-unicode"),
        ):
            cli._force_utf8_console()
            code = cli.run_cli(
                ["--video-subject", "Unicode test", "--stop-at", "script"]
            )
            legacy_stdout.flush()

        payload = json.loads(stdout_buffer.getvalue().decode("utf-8"))
        self.assertEqual(code, 0)
        self.assertEqual(legacy_stdout.encoding, "utf-8")
        self.assertEqual(legacy_stderr.encoding, "utf-8")
        self.assertEqual(payload["task_id"], "task-unicode")
        self.assertEqual(payload["result"], result)

    def test_run_cli_returns_error_when_task_fails(self):
        with patch("app.services.task.start", return_value=None), patch(
            "app.utils.utils.get_uuid", return_value="task-456"
        ), patch.object(cli.logger, "error") as log_error:
            code = cli.run_cli(["--video-subject", "失败场景"])

        self.assertEqual(code, 1)
        log_error.assert_called_once()

    def test_run_cli_returns_error_for_structured_task_failure(self):
        """任务服务返回结构化失败信息时,CLI 仍必须以非零状态退出。"""
        failure = {
            "task_id": "task-structured-failure",
            "state": -1,
            "progress": 30,
            "failed_stage": "audio",
            "error": "TTS request timed out",
        }

        with patch("app.services.task.start", return_value=failure), patch(
            "app.utils.utils.get_uuid", return_value="task-structured-failure"
        ), patch.object(cli.logger, "error") as log_error, patch(
            "builtins.print"
        ) as print_mock:
            code = cli.run_cli(["--video-subject", "失败场景"])

        self.assertEqual(code, 1)
        print_mock.assert_not_called()
        self.assertIn("stage=audio", log_error.call_args.args[0])
        self.assertIn("TTS request timed out", log_error.call_args.args[0])

    def test_run_cli_prints_completed_videos_when_a_batch_fails(self):
        """Partial video results remain machine-readable with a failed exit code."""
        failure = {
            "task_id": "partial-cli",
            "state": -1,
            "progress": 75,
            "failed_stage": "video",
            "failed_video_index": 2,
            "error": "OSError: encoder failed",
            "videos": ["final-1.mp4"],
            "combined_videos": ["combined-1.mp4"],
        }
        with (
            patch("app.services.task.start", return_value=failure),
            patch("app.utils.utils.get_uuid", return_value="partial-cli"),
            patch.object(cli, "prepare_cli_files"),
            patch("builtins.print") as print_mock,
        ):
            code = cli.run_cli(["--video-subject", "Coffee", "--video-count", "3"])
        self.assertEqual(code, 1)
        print_mock.assert_called_once()
        self.assertEqual(json.loads(print_mock.call_args.args[0]), {
            "task_id": "partial-cli", "result": failure,
        })

    def test_subtitle_enabled_by_default(self):
        args = cli.parse_args(["--video-subject", "test"])
        params = cli.build_video_params(args)
        self.assertTrue(params.subtitle_enabled)

    def test_subtitle_disabled_with_no_flag(self):
        args = cli.parse_args(["--video-subject", "test", "--no-subtitle-enabled"])
        params = cli.build_video_params(args)
        self.assertFalse(params.subtitle_enabled)

    def test_coverr_video_source_accepted(self):
        args = cli.parse_args(["--video-subject", "test", "--video-source", "coverr"])
        params = cli.build_video_params(args)
        self.assertEqual(params.video_source, "coverr")

    def test_seedance_video_source_requires_explicit_charge_confirmation(self):
        with self.assertRaises(SystemExit) as raised:
            cli.parse_args(
                [
                    "--video-subject",
                    "test",
                    "--video-source",
                    "volcengine_seedance",
                ]
            )
        self.assertEqual(raised.exception.code, 2)

        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--video-source",
                "volcengine_seedance",
                "--confirm-seedance-charge",
            ]
        )
        self.assertEqual(
            cli.build_video_params(args).video_source, "volcengine_seedance"
        )

    def test_wavespeed_video_source_requires_explicit_charge_confirmation(self):
        # WaveSpeed is the WebUI's original per-request billed generator, gated
        # on the same "Confirm WaveSpeed Charge" checkbox the siblings use.
        # Rejecting the source outright kept the CLI from reaching a generator
        # that config.example.toml advertises.
        with self.assertRaises(SystemExit) as raised:
            cli.parse_args(["--video-subject", "test", "--video-source", "wavespeed"])
        self.assertEqual(raised.exception.code, 2)

        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--video-source",
                "wavespeed",
                "--confirm-wavespeed-charge",
            ]
        )
        self.assertEqual(cli.build_video_params(args).video_source, "wavespeed")

    def test_wavespeed_confirmation_is_not_required_before_material_stage(self):
        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--video-source",
                "wavespeed",
                "--stop-at",
                "script",
            ]
        )
        self.assertEqual(args.video_source, "wavespeed")

    def test_batch_wavespeed_source_uses_global_charge_confirmation(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            manifest = Path(temp_dir) / "tasks.json"
            manifest.write_text(
                json.dumps([{"video_subject": "ws", "video_source": "wavespeed"}]),
                encoding="utf-8",
            )
            with patch("app.services.task.start") as start:
                rejected = cli.run_cli(
                    ["--batch-file", str(manifest), "--stop-at", "materials"]
                )
            self.assertEqual(rejected, 2)
            start.assert_not_called()

            with (
                patch(
                    "app.services.task.start",
                    return_value={"state": 1, "materials": ["ok"]},
                ) as start,
                patch("app.utils.utils.get_uuid", return_value="task-ws"),
                redirect_stdout(io.StringIO()),
            ):
                accepted = cli.run_cli(
                    [
                        "--batch-file",
                        str(manifest),
                        "--stop-at",
                        "materials",
                        "--confirm-wavespeed-charge",
                    ]
                )

            self.assertEqual(accepted, 0)
            start.assert_called_once()

    def test_ofox_video_source_requires_explicit_charge_confirmation(self):
        with self.assertRaises(SystemExit) as raised:
            cli.parse_args(
                ["--video-subject", "test", "--video-source", "ofox"]
            )
        self.assertEqual(raised.exception.code, 2)

        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--video-source",
                "ofox",
                "--confirm-ofox-charge",
            ]
        )
        self.assertEqual(cli.build_video_params(args).video_source, "ofox")

    def test_ofox_confirmation_is_not_required_before_material_stage(self):
        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--video-source",
                "ofox",
                "--stop-at",
                "script",
            ]
        )
        self.assertEqual(args.video_source, "ofox")

    def test_batch_ofox_source_uses_global_charge_confirmation(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            manifest = Path(temp_dir) / "tasks.json"
            manifest.write_text(
                json.dumps(
                    [
                        {
                            "video_subject": "OFox batch task",
                            "video_source": "ofox",
                        }
                    ]
                ),
                encoding="utf-8",
            )
            with patch("app.services.task.start") as start:
                rejected = cli.run_cli(
                    ["--batch-file", str(manifest), "--stop-at", "materials"]
                )
            self.assertEqual(rejected, 2)
            start.assert_not_called()

            with (
                patch(
                    "app.services.task.start",
                    return_value={"state": 1, "materials": ["ok"]},
                ) as start,
                patch("app.utils.utils.get_uuid", return_value="task-ofox"),
                redirect_stdout(io.StringIO()),
            ):
                accepted = cli.run_cli(
                    [
                        "--batch-file",
                        str(manifest),
                        "--stop-at",
                        "materials",
                        "--confirm-ofox-charge",
                    ]
                )

            self.assertEqual(accepted, 0)
            start.assert_called_once()

    def test_seedance_confirmation_is_not_required_before_material_stage(self):
        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--video-source",
                "volcengine_seedance",
                "--stop-at",
                "script",
            ]
        )
        self.assertEqual(args.video_source, "volcengine_seedance")

    def test_metaso_minimax_video_source_requires_charge_confirmation(self):
        with self.assertRaises(SystemExit) as raised:
            cli.parse_args(
                [
                    "--video-subject",
                    "test",
                    "--video-source",
                    "metaso_minimax",
                ]
            )
        self.assertEqual(raised.exception.code, 2)

        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--video-source",
                "metaso_minimax",
                "--confirm-metaso-minimax-charge",
            ]
        )
        self.assertEqual(cli.build_video_params(args).video_source, "metaso_minimax")

    def test_metaso_confirmation_is_not_required_before_material_stage(self):
        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--video-source",
                "metaso_minimax",
                "--stop-at",
                "script",
            ]
        )
        self.assertEqual(args.video_source, "metaso_minimax")

    def test_muapi_video_source_requires_explicit_charge_confirmation(self):
        with self.assertRaises(SystemExit) as raised:
            cli.parse_args(
                ["--video-subject", "test", "--video-source", "muapi"]
            )
        self.assertEqual(raised.exception.code, 2)

        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--video-source",
                "muapi",
                "--confirm-muapi-charge",
            ]
        )
        self.assertEqual(cli.build_video_params(args).video_source, "muapi")

    def test_muapi_confirmation_is_not_required_before_material_stage(self):
        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--video-source",
                "muapi",
                "--stop-at",
                "script",
            ]
        )
        self.assertEqual(args.video_source, "muapi")

    def test_batch_muapi_source_uses_global_charge_confirmation(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            manifest = Path(temp_dir) / "tasks.json"
            manifest.write_text(
                json.dumps(
                    [{"video_subject": "MuAPI batch task", "video_source": "muapi"}]
                ),
                encoding="utf-8",
            )
            with patch("app.services.task.start") as start:
                rejected = cli.run_cli(
                    ["--batch-file", str(manifest), "--stop-at", "materials"]
                )
            self.assertEqual(rejected, 2)
            start.assert_not_called()

            with (
                patch(
                    "app.services.task.start",
                    return_value={"state": 1, "materials": ["ok"]},
                ) as start,
                patch("app.utils.utils.get_uuid", return_value="task-muapi"),
                redirect_stdout(io.StringIO()),
            ):
                accepted = cli.run_cli(
                    [
                        "--batch-file",
                        str(manifest),
                        "--stop-at",
                        "materials",
                        "--confirm-muapi-charge",
                    ]
                )

            self.assertEqual(accepted, 0)
            start.assert_called_once()

    def test_batch_seedance_source_uses_global_charge_confirmation(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            manifest = Path(temp_dir) / "tasks.json"
            manifest.write_text(
                json.dumps(
                    [
                        {
                            "video_subject": "Seedance batch task",
                            "video_source": "volcengine_seedance",
                        }
                    ]
                ),
                encoding="utf-8",
            )
            with patch("app.services.task.start") as start:
                rejected = cli.run_cli(
                    ["--batch-file", str(manifest), "--stop-at", "materials"]
                )
            self.assertEqual(rejected, 2)
            start.assert_not_called()

            with (
                patch(
                    "app.services.task.start",
                    return_value={"state": 1, "materials": ["ok"]},
                ) as start,
                patch("app.utils.utils.get_uuid", return_value="task-seedance"),
                redirect_stdout(io.StringIO()),
            ):
                accepted = cli.run_cli(
                    [
                        "--batch-file",
                        str(manifest),
                        "--stop-at",
                        "materials",
                        "--confirm-seedance-charge",
                    ]
                )

            self.assertEqual(accepted, 0)
            start.assert_called_once()

    def test_batch_metaso_source_uses_global_charge_confirmation(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            manifest = Path(temp_dir) / "tasks.json"
            manifest.write_text(
                json.dumps(
                    [
                        {
                            "video_subject": "Metaso batch task",
                            "video_source": "metaso_minimax",
                        }
                    ]
                ),
                encoding="utf-8",
            )
            with patch("app.services.task.start") as start:
                rejected = cli.run_cli(
                    ["--batch-file", str(manifest), "--stop-at", "materials"]
                )
            self.assertEqual(rejected, 2)
            start.assert_not_called()

            with (
                patch(
                    "app.services.task.start",
                    return_value={"state": 1, "materials": ["ok"]},
                ) as start,
                patch("app.utils.utils.get_uuid", return_value="task-metaso"),
                redirect_stdout(io.StringIO()),
            ):
                accepted = cli.run_cli(
                    [
                        "--batch-file",
                        str(manifest),
                        "--stop-at",
                        "materials",
                        "--confirm-metaso-minimax-charge",
                    ]
                )

            self.assertEqual(accepted, 0)
            start.assert_called_once()

    def test_build_video_params_with_script_video_and_audio_options(self):
        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--video-language",
                "en",
                "--paragraph-number",
                "3",
                "--video-script-prompt",
                "use a lighter tone",
                "--custom-system-prompt",
                "write concise short-form scripts",
                "--video-concat-mode",
                "sequential",
                "--video-transition-mode",
                "fade-in",
                "--video-clip-duration",
                "4",
                "--match-materials-to-script",
                "--voice-volume",
                "1.2",
                "--voice-rate",
                "1.1",
                "--bgm-type",
                "custom",
                "--bgm-file",
                "output001.mp3",
                "--bgm-volume",
                "0.3",
                "--n-threads",
                "4",
            ]
        )

        params = cli.build_video_params(args)

        self.assertEqual(params.video_language, "en")
        self.assertEqual(params.paragraph_number, 3)
        self.assertEqual(params.video_script_prompt, "use a lighter tone")
        self.assertEqual(params.custom_system_prompt, "write concise short-form scripts")
        self.assertEqual(params.video_concat_mode, "sequential")
        self.assertEqual(params.video_transition_mode, "FadeIn")
        self.assertEqual(params.video_clip_duration, 4)
        self.assertTrue(params.match_materials_to_script)
        self.assertEqual(params.voice_volume, 1.2)
        self.assertEqual(params.voice_rate, 1.1)
        self.assertEqual(params.bgm_type, "custom")
        self.assertEqual(params.bgm_file, "output001.mp3")
        self.assertEqual(params.bgm_volume, 0.3)
        self.assertEqual(params.n_threads, 4)

    def test_custom_audio_file_maps_to_video_params(self):
        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--custom-audio-file",
                "voiceover.mp3",
            ]
        )
        params = cli.build_video_params(args)

        self.assertEqual(params.custom_audio_file, "voiceover.mp3")

    def test_build_video_params_with_subtitle_style_options(self):
        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--font-name",
                "MicrosoftYaHeiBold.ttc",
                "--subtitle-position",
                "custom",
                "--custom-position",
                "42.5",
                "--text-fore-color",
                "#AABBCC",
                "--font-size",
                "72",
                "--stroke-color",
                "#112233",
                "--stroke-width",
                "2.5",
                "--subtitle-background-color",
                "#000001",
                "--rounded-subtitle-background",
            ]
        )

        params = cli.build_video_params(args)

        self.assertEqual(params.font_name, "MicrosoftYaHeiBold.ttc")
        self.assertEqual(params.subtitle_position, "custom")
        self.assertEqual(params.custom_position, 42.5)
        self.assertEqual(params.text_fore_color, "#AABBCC")
        self.assertEqual(params.font_size, 72)
        self.assertEqual(params.stroke_color, "#112233")
        self.assertEqual(params.stroke_width, 2.5)
        self.assertEqual(params.text_background_color, "#000001")
        self.assertTrue(params.rounded_subtitle_background)

    def test_disabled_subtitle_background_rejects_rounding(self):
        with self.assertRaises(SystemExit) as cm:
            cli.parse_args(
                [
                    "--video-subject",
                    "test",
                    "--no-subtitle-background-enabled",
                    "--rounded-subtitle-background",
                ]
            )

        self.assertEqual(cm.exception.code, 2)

    def test_bgm_type_none_maps_to_disabled_background_music(self):
        args = cli.parse_args(["--video-subject", "test", "--bgm-type", "none"])
        params = cli.build_video_params(args)
        self.assertEqual(params.bgm_type, "")

    def test_video_music_providers_are_selectable_from_the_cli(self):
        # --bgm-type must reach every video-matched music provider the runtime
        # dispatches on, otherwise CLI users cannot use a mode the WebUI and the
        # API already accept. Deriving the expectation from the runtime registry
        # keeps the two lists from drifting apart again.
        from app.services import task as task_service

        for provider in sorted(task_service._VIDEO_MUSIC_PROVIDERS):
            args = cli.parse_args(
                ["--video-subject", "test", "--bgm-type", provider]
            )
            params = cli.build_video_params(args)
            self.assertEqual(params.bgm_type, provider)

    def test_sonilo_prompt_implies_sonilo_bgm_mode(self):
        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--sonilo-bgm-prompt",
                "warm acoustic",
            ]
        )
        params = cli.build_video_params(args)
        self.assertEqual(params.bgm_type, "sonilo")
        self.assertEqual(params.sonilo_bgm_prompt, "warm acoustic")

    def test_video_music_prompt_reaches_every_ai_music_provider(self):
        # video_music_prompt 与供应商无关,WebUI 为每个 AI 配乐供应商都写入
        # 该字段。CLI 若只提供 Sonilo 专用参数,选中 ElevenLabs 的用户就无法
        # 传提示词。期望值从运行时注册表推导,避免两份清单再次漂移。
        from app.services import task as task_service

        for provider in sorted(task_service._VIDEO_MUSIC_PROVIDERS):
            args = cli.parse_args(
                [
                    "--video-subject",
                    "test",
                    "--bgm-type",
                    provider,
                    "--video-music-prompt",
                    "warm acoustic",
                ]
            )
            params = cli.build_video_params(args)
            self.assertEqual(params.bgm_type, provider)
            self.assertEqual(params.video_music_prompt, "warm acoustic")

    def test_video_music_prompt_requires_an_ai_music_provider(self):
        # 下游只在 AI 配乐供应商分支读取该提示词。同一个 --bgm-type random 在
        # 没有提示词时仍然可用,说明这里的拒绝来自提示词与供应商的组合,而不是
        # 参数本身不被识别。
        cli.parse_args(["--video-subject", "test", "--bgm-type", "random"])
        for bgm_type in ("random", "none"):
            error_output = io.StringIO()
            with redirect_stderr(error_output):
                with self.assertRaises(SystemExit) as cm:
                    cli.parse_args(
                        [
                            "--video-subject",
                            "test",
                            "--bgm-type",
                            bgm_type,
                            "--video-music-prompt",
                            "warm acoustic",
                        ]
                    )
            self.assertEqual(cm.exception.code, 2)
            self.assertIn(
                "--video-music-prompt requires --bgm-type sonilo or elevenlabs",
                error_output.getvalue(),
            )

    def test_local_material_filename_resolved_to_absolute_path(self):
        """After preprocess_video, material.url should be an absolute path, not a bare filename."""
        import os
        from app.utils import utils
        from app.services import video as vd
        from app.models.schema import MaterialInfo

        local_videos_dir = utils.storage_dir("local_videos", create=True)
        # Create a minimal valid video file for testing
        test_filename = "_cli_test_resolve.mp4"
        test_filepath = os.path.join(local_videos_dir, test_filename)
        # We need a real video file; use a tiny one via moviepy
        try:
            from moviepy import ColorClip
            clip = ColorClip(size=(640, 640), color=(0, 0, 0), duration=1)
            clip.write_videofile(test_filepath, fps=1, logger=None)
            clip.close()
        except Exception:
            self.skipTest("moviepy not available for creating test video")

        try:
            materials = [MaterialInfo(provider="local", url=test_filename, duration=0)]
            result = vd.preprocess_video(materials=materials, clip_duration=4)
            self.assertTrue(len(result) > 0, "preprocess_video should return valid materials")
            self.assertTrue(
                os.path.isabs(result[0].url),
                f"material url should be absolute path, got: {result[0].url}",
            )
            self.assertEqual(result[0].url, test_filepath)
        finally:
            if os.path.exists(test_filepath):
                os.remove(test_filepath)


    def test_local_source_requires_video_materials(self):
        with self.assertRaises(SystemExit) as cm:
            cli.parse_args(["--video-subject", "test", "--video-source", "local"])
        self.assertNotEqual(cm.exception.code, 0)

    def test_local_source_does_not_require_materials_before_material_stage(self):
        for stop_at in ("script", "audio", "subtitle"):
            with self.subTest(stop_at=stop_at):
                args = cli.parse_args(
                    [
                        "--video-subject",
                        "test",
                        "--video-source",
                        "local",
                        "--stop-at",
                        stop_at,
                    ]
                )
                self.assertEqual(args.stop_at, stop_at)

    def test_local_source_stop_at_terms_rejected(self):
        with self.assertRaises(SystemExit) as cm:
            cli.parse_args([
                "--video-subject", "test",
                "--video-source", "local",
                "--video-materials", "a.mp4",
                "--stop-at", "terms",
            ])
        self.assertNotEqual(cm.exception.code, 0)

    def test_video_materials_rejected_for_online_source(self):
        with self.assertRaises(SystemExit) as cm:
            cli.parse_args(
                [
                    "--video-subject",
                    "test",
                    "--video-source",
                    "pexels",
                    "--video-materials",
                    "a.mp4",
                ]
            )

        self.assertEqual(cm.exception.code, 2)

    def test_positive_volume_custom_bgm_requires_file_before_task_start(self):
        """启用自定义 BGM 时仍必须在任务启动前报告缺少文件。"""
        with (
            patch("app.services.task.start") as start,
            patch.object(cli.logger, "error") as log_error,
        ):
            code = cli.run_cli(
                [
                    "--video-subject",
                    "test",
                    "--bgm-type",
                    "custom",
                    "--stop-at",
                    "video",
                ]
            )

        self.assertEqual(code, 2)
        start.assert_not_called()
        self.assertIn(
            "--bgm-file is required",
            str(log_error.call_args),
        )

    def test_bgm_file_implies_custom_mode(self):
        args = cli.parse_args(
            ["--video-subject", "test", "--bgm-file", "output001.mp3"]
        )
        self.assertEqual(args.bgm_type, "custom")

    def test_zero_volume_custom_bgm_skips_file_requirement_and_resolution(self):
        """0 音量应忽略缺失或无效文件,与 WebUI 和视频服务保持一致。"""
        file_arguments = [[], ["--bgm-file", "missing-background.mp3"]]
        for extra_arguments in file_arguments:
            with self.subTest(extra_arguments=extra_arguments):
                args = cli.parse_args(
                    [
                        "--video-subject",
                        "test",
                        "--bgm-type",
                        "custom",
                        "--bgm-volume",
                        "0",
                        *extra_arguments,
                    ]
                )
                params = cli.build_video_params(args)
                params.subtitle_enabled = False
                with patch(
                    "app.services.bgm.resolve_bgm_file",
                    side_effect=AssertionError(
                        "zero-volume BGM must not resolve a file"
                    ),
                ) as resolver:
                    cli.prepare_cli_files(params, stop_at="video")

                resolver.assert_not_called()
                self.assertEqual(params.bgm_file, "")

    def test_custom_bgm_reuses_service_formats_and_managed_path_resolution(self):
        """CLI 必须跟随 BGM 服务的格式白名单,不能继续单独限制为 MP3。"""
        from app.services import bgm as bgm_service

        for extension in bgm_service.SUPPORTED_BGM_EXTENSIONS:
            with self.subTest(extension=extension):
                filename = f"uploaded{extension}"
                resolved_path = f"/managed/storage/bgm/{filename}"
                args = cli.parse_args(
                    [
                        "--video-subject",
                        "test",
                        "--bgm-type",
                        "custom",
                        "--bgm-file",
                        filename,
                    ]
                )
                params = cli.build_video_params(args)
                params.subtitle_enabled = False
                with patch.object(
                    bgm_service,
                    "resolve_bgm_file",
                    return_value=resolved_path,
                ) as resolver:
                    cli.prepare_cli_files(params, stop_at="video")

                resolver.assert_called_once_with(filename)
                self.assertEqual(params.bgm_file, resolved_path)

    def test_custom_bgm_reports_service_resolution_failure_before_task_start(self):
        """非法格式或越界路径应转换为包含统一格式范围的 CLI 错误。"""
        from app.services import bgm as bgm_service

        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--bgm-type",
                "custom",
                "--bgm-file",
                "unsafe.exe",
            ]
        )
        params = cli.build_video_params(args)
        params.subtitle_enabled = False
        with (
            patch.object(
                bgm_service,
                "resolve_bgm_file",
                side_effect=ValueError("unsupported background music path"),
            ),
            self.assertRaisesRegex(ValueError, "storage/bgm or resource/songs"),
        ):
            cli.prepare_cli_files(params, stop_at="video")

    def test_invalid_aspect_and_non_finite_numbers_are_argument_errors(self):
        invalid_argvs = [
            ["--video-subject", "test", "--video-aspect", "invalid"],
            ["--video-subject", "test", "--custom-position", "nan"],
            ["--video-subject", "test", "--voice-rate", "inf"],
        ]
        for argv in invalid_argvs:
            with self.subTest(argv=argv), self.assertRaises(SystemExit) as cm:
                cli.parse_args(argv)
            self.assertEqual(cm.exception.code, 2)

    def test_custom_position_requires_custom_subtitle_position(self):
        with self.assertRaises(SystemExit) as cm:
            cli.parse_args(
                ["--video-subject", "test", "--custom-position", "50"]
            )

        self.assertEqual(cm.exception.code, 2)

    def test_task_id_must_be_uuid(self):
        task_id = str(uuid4())
        args = cli.parse_args(
            ["--video-subject", "test", "--task-id", task_id]
        )
        self.assertEqual(args.task_id, task_id)

        with self.assertRaises(SystemExit) as cm:
            cli.parse_args(
                ["--video-subject", "test", "--task-id", "../../escape"]
            )
        self.assertEqual(cm.exception.code, 2)

    def test_prepare_cli_files_accepts_relative_and_absolute_materials(self):
        with (
            tempfile.TemporaryDirectory() as source_dir,
            tempfile.TemporaryDirectory() as managed_dir,
        ):
            relative_file = Path(source_dir) / "relative.mp4"
            absolute_file = Path(source_dir) / "absolute.jpg"
            relative_file.write_bytes(b"relative-video")
            absolute_file.write_bytes(b"absolute-image")
            old_cwd = os.getcwd()
            try:
                os.chdir(source_dir)
                args = cli.parse_args(
                    [
                        "--video-subject",
                        "test",
                        "--video-source",
                        "local",
                        "--video-materials",
                        f"relative.mp4,{absolute_file}",
                    ]
                )
                params = cli.build_video_params(args)
                with patch("app.utils.utils.storage_dir", return_value=managed_dir):
                    cli.prepare_cli_files(params, stop_at="video")
            finally:
                os.chdir(old_cwd)

            prepared_paths = [Path(item.url) for item in params.video_materials]
            self.assertTrue(all(path.parent == Path(managed_dir) for path in prepared_paths))
            self.assertEqual(
                {path.read_bytes() for path in prepared_paths},
                {b"relative-video", b"absolute-image"},
            )

    def test_prepare_cli_files_rejects_missing_material_before_task_start(self):
        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--video-source",
                "local",
                "--video-materials",
                "missing.mp4",
            ]
        )
        params = cli.build_video_params(args)

        with tempfile.TemporaryDirectory() as managed_dir, patch(
            "app.utils.utils.storage_dir", return_value=managed_dir
        ):
            with self.assertRaisesRegex(ValueError, "does not exist"):
                cli.prepare_cli_files(params, stop_at="video")

    def test_run_cli_rejects_missing_material_before_starting_task(self):
        with patch("app.services.task.start") as start:
            code = cli.run_cli(
                [
                    "--video-subject",
                    "test",
                    "--video-source",
                    "local",
                    "--video-materials",
                    "missing.mp4",
                ]
            )

        self.assertEqual(code, 2)
        start.assert_not_called()

    def test_prepare_cli_files_resolves_relative_custom_audio(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            audio_file = Path(temp_dir) / "voiceover.mp3"
            audio_file.write_bytes(b"audio")
            old_cwd = os.getcwd()
            try:
                os.chdir(temp_dir)
                args = cli.parse_args(
                    [
                        "--video-subject",
                        "test",
                        "--custom-audio-file",
                        "voiceover.mp3",
                        "--stop-at",
                        "audio",
                    ]
                )
                params = cli.build_video_params(args)
                cli.prepare_cli_files(params, stop_at="audio")
            finally:
                os.chdir(old_cwd)

            self.assertEqual(params.custom_audio_file, str(audio_file.resolve()))

    def test_batch_file_does_not_require_global_subject_and_conflicts_with_task_id(self):
        args = cli.parse_args(["--batch-file", "tasks.jsonl"])
        self.assertEqual(args.batch_file, "tasks.jsonl")

        with self.assertRaises(SystemExit) as cm:
            cli.parse_args(
                [
                    "--batch-file",
                    "tasks.jsonl",
                    "--task-id",
                    str(uuid4()),
                ]
            )

        self.assertEqual(cm.exception.code, 2)

    def test_batch_json_array_merges_cli_defaults_and_prints_summary(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            manifest = Path(temp_dir) / "tasks.json"
            manifest.write_text(
                json.dumps(
                    [
                        {"video_subject": "first subject"},
                        {"video_script": "prepared second script"},
                    ]
                ),
                encoding="utf-8",
            )
            output = io.StringIO()
            with (
                patch(
                    "app.services.task.start",
                    side_effect=[
                        {"state": 1, "script": "first"},
                        {"state": 1, "script": "second"},
                    ],
                ) as start,
                patch(
                    "app.utils.utils.get_uuid",
                    side_effect=["task-one", "task-two"],
                ),
                redirect_stdout(output),
            ):
                code = cli.run_cli(
                    [
                        "--batch-file",
                        str(manifest),
                        "--stop-at",
                        "script",
                        "--voice-name",
                        "global-voice",
                    ]
                )

        self.assertEqual(code, 0)
        self.assertEqual(start.call_count, 2)
        first_call, second_call = start.call_args_list
        self.assertEqual(first_call.kwargs["task_id"], "task-one")
        self.assertEqual(second_call.kwargs["task_id"], "task-two")
        self.assertEqual(first_call.kwargs["params"].video_subject, "first subject")
        self.assertEqual(
            second_call.kwargs["params"].video_script,
            "prepared second script",
        )
        self.assertEqual(first_call.kwargs["params"].voice_name, "global-voice")
        self.assertEqual(second_call.kwargs["params"].voice_name, "global-voice")
        self.assertIs(first_call.kwargs["allow_server_file_input"], True)
        self.assertIs(second_call.kwargs["allow_server_file_input"], True)
        summary = json.loads(output.getvalue())
        self.assertEqual(
            {key: summary[key] for key in ("total", "succeeded", "failed")},
            {"total": 2, "succeeded": 2, "failed": 0},
        )
        self.assertEqual(
            [task["status"] for task in summary["tasks"]],
            ["succeeded", "succeeded"],
        )
        self.assertEqual(
            set(summary["tasks"][0]),
            {"index", "task_id", "status", "result", "failed_stage", "error"},
        )

    def test_batch_accepts_openai_image_source(self):
        """批量入口必须接受单任务 CLI 已支持的 OpenAI 文生图素材源。"""
        with tempfile.TemporaryDirectory() as temp_dir:
            manifest = Path(temp_dir) / "tasks.json"
            manifest.write_text(
                json.dumps(
                    [
                        {
                            "video_subject": "batch image source",
                            "video_source": "openai_image",
                        }
                    ]
                ),
                encoding="utf-8",
            )
            args = cli.parse_args(
                ["--batch-file", str(manifest), "--stop-at", "script"]
            )

            tasks = cli._build_batch_tasks(args)

        self.assertEqual(len(tasks), 1)
        self.assertEqual(tasks[0].video_source, "openai_image")

    def test_batch_jsonl_continues_after_runtime_and_structured_failures(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            manifest = Path(temp_dir) / "tasks.jsonl"
            manifest.write_text(
                "\n".join(
                    json.dumps({"video_subject": subject})
                    for subject in ("one", "two", "three")
                ),
                encoding="utf-8",
            )
            output = io.StringIO()
            with (
                patch(
                    "app.services.task.start",
                    side_effect=[
                        {"state": 1, "script": "ok"},
                        RuntimeError("provider unavailable"),
                        {
                            "state": -1,
                            "failed_stage": "audio",
                            "error": "TTS failed",
                        },
                    ],
                ) as start,
                patch(
                    "app.utils.utils.get_uuid",
                    side_effect=["task-one", "task-two", "task-three"],
                ),
                patch.object(cli.logger, "exception"),
                patch.object(cli.logger, "error"),
                redirect_stdout(output),
            ):
                code = cli.run_cli(
                    ["--batch-file", str(manifest), "--stop-at", "script"]
                )

        self.assertEqual(code, 1)
        self.assertEqual(start.call_count, 3)
        summary = json.loads(output.getvalue())
        self.assertEqual(summary["succeeded"], 1)
        self.assertEqual(summary["failed"], 2)
        self.assertEqual(
            [task["status"] for task in summary["tasks"]],
            ["succeeded", "failed", "failed"],
        )
        self.assertEqual(summary["tasks"][1]["failed_stage"], "runtime")
        self.assertEqual(summary["tasks"][1]["error"], "provider unavailable")
        self.assertEqual(summary["tasks"][2]["failed_stage"], "audio")

    def test_invalid_later_batch_task_prevents_every_task_from_starting(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            manifest = Path(temp_dir) / "tasks.json"
            manifest.write_text(
                json.dumps(
                    [
                        {"video_subject": "valid"},
                        {"video_subject": "invalid", "unknown_option": True},
                    ]
                ),
                encoding="utf-8",
            )
            with (
                patch("app.services.task.start") as start,
                patch.object(cli.logger, "error") as log_error,
            ):
                code = cli.run_cli(
                    ["--batch-file", str(manifest), "--stop-at", "script"]
                )

        self.assertEqual(code, 2)
        start.assert_not_called()
        self.assertIn("unknown VideoParams fields", str(log_error.call_args))

    def test_missing_file_in_later_batch_task_prevents_every_task_from_starting(self):
        with (
            tempfile.TemporaryDirectory() as temp_dir,
            tempfile.TemporaryDirectory() as managed_dir,
        ):
            source_file = Path(temp_dir) / "valid.mp4"
            source_file.write_bytes(b"valid video")
            manifest = Path(temp_dir) / "tasks.json"
            manifest.write_text(
                json.dumps(
                    [
                        {
                            "video_subject": "valid local material",
                            "video_source": "local",
                            "video_materials": [
                                {"provider": "local", "url": "valid.mp4"}
                            ],
                        },
                        {
                            "video_subject": "missing local material",
                            "video_source": "local",
                            "video_materials": [
                                {"provider": "local", "url": "missing.mp4"}
                            ],
                        },
                    ]
                ),
                encoding="utf-8",
            )
            with (
                patch("app.services.task.start") as start,
                patch("app.utils.utils.storage_dir", return_value=managed_dir),
            ):
                code = cli.run_cli(
                    ["--batch-file", str(manifest), "--stop-at", "materials"]
                )

            self.assertEqual(code, 2)
            start.assert_not_called()
            self.assertEqual(os.listdir(managed_dir), [])

    def test_batch_reuses_one_managed_copy_for_repeated_local_material(self):
        with (
            tempfile.TemporaryDirectory() as manifest_dir,
            tempfile.TemporaryDirectory() as managed_dir,
        ):
            source_file = Path(manifest_dir) / "shared.mp4"
            source_file.write_bytes(b"shared video")
            manifest = Path(manifest_dir) / "tasks.json"
            manifest.write_text(
                json.dumps(
                    [
                        {
                            "video_subject": subject,
                            "video_source": "local",
                            "video_materials": [
                                {"provider": "local", "url": "shared.mp4"}
                            ],
                        }
                        for subject in ("first", "second")
                    ]
                ),
                encoding="utf-8",
            )
            with (
                patch(
                    "app.services.task.start",
                    side_effect=[
                        {"state": 1, "materials": ["first"]},
                        {"state": 1, "materials": ["second"]},
                    ],
                ) as start,
                patch(
                    "app.utils.utils.get_uuid",
                    side_effect=["task-one", "task-two"],
                ),
                patch("app.utils.utils.storage_dir", return_value=managed_dir),
                redirect_stdout(io.StringIO()),
            ):
                code = cli.run_cli(
                    ["--batch-file", str(manifest), "--stop-at", "materials"]
                )

            first_path = start.call_args_list[0].kwargs["params"].video_materials[0].url
            second_path = start.call_args_list[1].kwargs["params"].video_materials[0].url
            managed_files = os.listdir(managed_dir)

        self.assertEqual(code, 0)
        self.assertEqual(first_path, second_path)
        self.assertEqual(len(managed_files), 1)
        self.assertTrue(managed_files[0].startswith("cli-material-"))

    def test_batch_copy_failure_removes_all_managed_materials(self):
        with (
            tempfile.TemporaryDirectory() as manifest_dir,
            tempfile.TemporaryDirectory() as managed_dir,
        ):
            first_source = Path(manifest_dir) / "first.mp4"
            second_source = Path(manifest_dir) / "second.mp4"
            first_source.write_bytes(b"first video")
            second_source.write_bytes(b"second video")
            manifest = Path(manifest_dir) / "tasks.json"
            manifest.write_text(
                json.dumps(
                    [
                        {
                            "video_subject": name,
                            "video_source": "local",
                            "video_materials": [
                                {"provider": "local", "url": f"{name}.mp4"}
                            ],
                        }
                        for name in ("first", "second")
                    ]
                ),
                encoding="utf-8",
            )
            real_copy = cli.shutil.copy2

            def fail_second_copy(source, target):
                if os.path.basename(source) == "second.mp4":
                    Path(target).write_bytes(b"partial copy")
                    raise OSError("simulated copy failure")
                return real_copy(source, target)

            with (
                patch("app.services.task.start") as start,
                patch("app.utils.utils.storage_dir", return_value=managed_dir),
                patch.object(cli.shutil, "copy2", side_effect=fail_second_copy),
            ):
                code = cli.run_cli(
                    ["--batch-file", str(manifest), "--stop-at", "materials"]
                )

            self.assertEqual(code, 2)
            start.assert_not_called()
            self.assertEqual(os.listdir(managed_dir), [])

    def test_batch_rejects_non_object_and_unknown_material_fields(self):
        invalid_manifests = (
            ["not an object"],
            [
                {
                    "video_subject": "invalid material",
                    "video_source": "local",
                    "video_materials": [
                        {"provider": "local", "url": "clip.mp4", "secret": "x"}
                    ],
                }
            ],
        )
        for payload in invalid_manifests:
            with self.subTest(payload=payload), tempfile.TemporaryDirectory() as temp_dir:
                manifest = Path(temp_dir) / "tasks.json"
                manifest.write_text(json.dumps(payload), encoding="utf-8")
                with patch("app.services.task.start") as start:
                    code = cli.run_cli(
                        ["--batch-file", str(manifest), "--stop-at", "script"]
                    )

                self.assertEqual(code, 2)
                start.assert_not_called()

    def test_batch_validates_every_task_has_subject_or_script_before_start(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            manifest = Path(temp_dir) / "tasks.json"
            manifest.write_text(
                json.dumps([{"video_subject": "valid"}, {}]),
                encoding="utf-8",
            )
            with patch("app.services.task.start") as start:
                code = cli.run_cli(
                    ["--batch-file", str(manifest), "--stop-at", "script"]
                )

        self.assertEqual(code, 2)
        start.assert_not_called()

    def test_batch_rejects_invalid_subtitle_color_before_start(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            manifest = Path(temp_dir) / "tasks.json"
            manifest.write_text(
                json.dumps(
                    [
                        {
                            "video_subject": "invalid color",
                            "text_fore_color": "white",
                        }
                    ]
                ),
                encoding="utf-8",
            )
            with patch("app.services.task.start") as start:
                code = cli.run_cli(
                    ["--batch-file", str(manifest), "--stop-at", "script"]
                )

        self.assertEqual(code, 2)
        start.assert_not_called()

    def test_batch_rejects_invalid_video_clip_speed_before_start(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            manifest = Path(temp_dir) / "tasks.json"
            manifest.write_text(
                json.dumps(
                    [
                        {
                            "video_subject": "invalid speed",
                            "video_clip_speed": -1,
                        }
                    ]
                ),
                encoding="utf-8",
            )
            with patch("app.services.task.start") as start:
                code = cli.run_cli(
                    ["--batch-file", str(manifest), "--stop-at", "script"]
                )

        self.assertEqual(code, 2)
        start.assert_not_called()

    def test_video_clip_speed_is_reachable_from_the_cli(self):
        """
        WebUI 的滑块把 video_clip_speed 写进 config.toml,批量清单也接受该字段
        (见 _validate_batch_task_params),但 VideoParams 把它硬编码成 1.0 而不是
        读取 config.ui,因此单任务命令行此前既没有对应参数、也拿不到保存值。
        """
        explicit_params = cli.build_video_params(
            cli.parse_args(["--video-subject", "test", "--video-clip-speed", "1.5"])
        )
        self.assertEqual(explicit_params.video_clip_speed, 1.5)

        saved_args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, {"video_clip_speed": 1.25}, clear=True):
            saved_params = cli.build_video_params(saved_args)

        self.assertEqual(saved_params.video_clip_speed, 1.25)

    def test_video_clip_speed_range_matches_the_runtime_normalizer(self):
        """
        CLI 的取值范围必须与 app/utils/utils.py 的 normalize_clip_speed() 以及
        WebUI 滑块一致,否则命令行会接受运行时随后改写的取值。
        """
        from app.utils import utils

        self.assertEqual(cli._CLIP_SPEED_MIN, utils._CLIP_SPEED_MIN)
        self.assertEqual(cli._CLIP_SPEED_MAX, utils._CLIP_SPEED_MAX)

        for value in ("0.4", "3.0", "nan", "inf"):
            error_output = io.StringIO()
            with redirect_stderr(error_output):
                with self.assertRaises(SystemExit) as cm:
                    cli.parse_args(
                        ["--video-subject", "test", "--video-clip-speed", value]
                    )
            self.assertEqual(cm.exception.code, 2)
            self.assertIn("video-clip-speed", error_output.getvalue())

    def test_later_null_runtime_field_prevents_every_batch_task_from_starting(self):
        for field_name in ("video_aspect", "video_concat_mode"):
            with self.subTest(field_name=field_name), tempfile.TemporaryDirectory() as temp_dir:
                manifest = Path(temp_dir) / "tasks.json"
                manifest.write_text(
                    json.dumps(
                        [
                            {"video_subject": "valid first task"},
                            {
                                "video_subject": "invalid later task",
                                field_name: None,
                            },
                        ]
                    ),
                    encoding="utf-8",
                )
                with patch("app.services.task.start") as start:
                    code = cli.run_cli(
                        [
                            "--batch-file",
                            str(manifest),
                            "--stop-at",
                            "video",
                            "--no-subtitle-enabled",
                        ]
                    )

                self.assertEqual(code, 2)
                start.assert_not_called()

    def test_batch_manifest_limits_size_and_task_count(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            oversized = Path(temp_dir) / "oversized.jsonl"
            oversized.write_bytes(b"x" * (cli._BATCH_FILE_MAX_BYTES + 1))
            with self.assertRaisesRegex(ValueError, "1 MiB limit"):
                cli._load_batch_manifest(str(oversized))

            too_many = Path(temp_dir) / "too-many.json"
            too_many.write_text(
                json.dumps(
                    [
                        {"video_subject": f"task {index}"}
                        for index in range(cli._BATCH_TASK_MAX_COUNT + 1)
                    ]
                ),
                encoding="utf-8",
            )
            with self.assertRaisesRegex(ValueError, "the limit is"):
                cli._load_batch_manifest(str(too_many))

    def test_batch_jsonl_error_reports_source_line(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            manifest = Path(temp_dir) / "invalid.jsonl"
            manifest.write_text(
                '{"video_subject": "valid"}\n{invalid json}\n',
                encoding="utf-8",
            )

            with self.assertRaisesRegex(ValueError, "line 2"):
                cli._load_batch_manifest(str(manifest))

    def test_manifest_relative_custom_audio_uses_manifest_directory(self):
        with (
            tempfile.TemporaryDirectory() as manifest_dir,
            tempfile.TemporaryDirectory() as working_dir,
        ):
            audio_file = Path(manifest_dir) / "voice.mp3"
            audio_file.write_bytes(b"audio")
            manifest = Path(manifest_dir) / "tasks.json"
            manifest.write_text(
                json.dumps(
                    [
                        {
                            "video_subject": "manifest audio",
                            "custom_audio_file": "voice.mp3",
                        }
                    ]
                ),
                encoding="utf-8",
            )
            old_cwd = os.getcwd()
            try:
                os.chdir(working_dir)
                with (
                    patch(
                        "app.services.task.start",
                        return_value={"state": 1, "audio_file": "ok"},
                    ) as start,
                    patch("app.utils.utils.get_uuid", return_value="task-one"),
                    redirect_stdout(io.StringIO()),
                ):
                    code = cli.run_cli(
                        ["--batch-file", str(manifest), "--stop-at", "audio"]
                    )
            finally:
                os.chdir(old_cwd)

        self.assertEqual(code, 0)
        self.assertEqual(
            start.call_args.kwargs["params"].custom_audio_file,
            str(audio_file.resolve()),
        )

    def test_manifest_relative_local_material_uses_manifest_directory(self):
        with (
            tempfile.TemporaryDirectory() as manifest_dir,
            tempfile.TemporaryDirectory() as working_dir,
            tempfile.TemporaryDirectory() as managed_dir,
        ):
            source_file = Path(manifest_dir) / "clip.mp4"
            source_file.write_bytes(b"manifest video")
            manifest = Path(manifest_dir) / "tasks.json"
            manifest.write_text(
                json.dumps(
                    [
                        {
                            "video_subject": "manifest material",
                            "video_source": "local",
                            "video_materials": [
                                {
                                    "provider": "local",
                                    "url": "clip.mp4",
                                    "duration": 0,
                                }
                            ],
                        }
                    ]
                ),
                encoding="utf-8",
            )
            old_cwd = os.getcwd()
            try:
                os.chdir(working_dir)
                with (
                    patch(
                        "app.services.task.start",
                        return_value={"state": 1, "materials": ["ok"]},
                    ) as start,
                    patch("app.utils.utils.get_uuid", return_value="task-one"),
                    patch("app.utils.utils.storage_dir", return_value=managed_dir),
                    redirect_stdout(io.StringIO()),
                ):
                    code = cli.run_cli(
                        ["--batch-file", str(manifest), "--stop-at", "materials"]
                    )
            finally:
                os.chdir(old_cwd)

            prepared_file = Path(
                start.call_args.kwargs["params"].video_materials[0].url
            )
            self.assertEqual(code, 0)
            self.assertEqual(prepared_file.parent, Path(managed_dir))
            self.assertEqual(prepared_file.read_bytes(), b"manifest video")

    def test_global_relative_custom_audio_keeps_current_working_directory(self):
        with (
            tempfile.TemporaryDirectory() as manifest_dir,
            tempfile.TemporaryDirectory() as working_dir,
        ):
            audio_file = Path(working_dir) / "voice.mp3"
            audio_file.write_bytes(b"audio")
            manifest = Path(manifest_dir) / "tasks.json"
            manifest.write_text(
                json.dumps([{"video_subject": "global audio"}]),
                encoding="utf-8",
            )
            old_cwd = os.getcwd()
            try:
                os.chdir(working_dir)
                with (
                    patch(
                        "app.services.task.start",
                        return_value={"state": 1, "audio_file": "ok"},
                    ) as start,
                    patch("app.utils.utils.get_uuid", return_value="task-one"),
                    redirect_stdout(io.StringIO()),
                ):
                    code = cli.run_cli(
                        [
                            "--batch-file",
                            str(manifest),
                            "--custom-audio-file",
                            "voice.mp3",
                            "--stop-at",
                            "audio",
                        ]
                    )
            finally:
                os.chdir(old_cwd)

        self.assertEqual(code, 0)
        self.assertEqual(
            start.call_args.kwargs["params"].custom_audio_file,
            str(audio_file.resolve()),
        )

    def test_help_documents_defaults_paths_stages_and_exit_codes(self):
        output = io.StringIO()
        with redirect_stdout(output), self.assertRaises(SystemExit) as cm:
            cli.parse_args(["--help"])

        self.assertEqual(cm.exception.code, 0)
        help_text = output.getvalue()
        self.assertIn("zh-CN-XiaoxiaoNeural-Female", help_text)
        self.assertIn("current working directory", help_text)
        self.assertIn("Pipeline stages:", help_text)
        self.assertIn("Batch manifests:", help_text)
        self.assertIn("JSONL", help_text)
        self.assertIn("exit with 2", help_text)

    def test_help_does_not_initialize_application_or_write_logs(self):
        """帮助命令应独立于业务配置加载,便于用户查看和脚本采集。"""
        project_root = Path(__file__).parent.parent.parent
        result = subprocess.run(
            [sys.executable, str(project_root / "cli.py"), "--help"],
            cwd=project_root,
            capture_output=True,
            text=True,
            check=False,
        )

        self.assertEqual(result.returncode, 0)
        self.assertIn("Generate MoneyPrinterTurbo videos", result.stdout)
        self.assertEqual(result.stderr, "")


class TestCliUiDefaults(unittest.TestCase):
    """
    CLI 默认值应跟随 WebUI:显式命令行参数优先,其次是 config.toml 的 [ui]
    保存值,最后才是内置默认值。
    """

    UI_CONFIG = {
        "font_name": "MicrosoftYaHeiBold.ttc",
        "text_fore_color": "#123456",
        "font_size": 48,
        "subtitle_background_enabled": True,
        "subtitle_background_color": "#654321",
        "rounded_subtitle_background": True,
        "voice_name": "gemini:Puck-Male",
    }

    def test_ui_config_supplies_subtitle_defaults(self):
        args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, self.UI_CONFIG, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.font_name, "MicrosoftYaHeiBold.ttc")
        self.assertEqual(params.text_fore_color, "#123456")
        self.assertEqual(params.font_size, 48)
        self.assertEqual(params.text_background_color, "#654321")
        self.assertTrue(params.rounded_subtitle_background)

    def test_ui_config_supplies_voice_name(self):
        args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, self.UI_CONFIG, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.voice_name, "gemini:Puck-Male")

    def test_cli_flags_take_precedence_over_ui_config(self):
        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--font-name",
                "STHeitiLight.ttc",
                "--text-fore-color",
                "#AABBCC",
                "--font-size",
                "72",
                "--voice-name",
                "no-voice",
                "--no-rounded-subtitle-background",
            ]
        )

        with patch.dict(app_config.ui, self.UI_CONFIG, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.font_name, "STHeitiLight.ttc")
        self.assertEqual(params.text_fore_color, "#AABBCC")
        self.assertEqual(params.font_size, 72)
        self.assertEqual(params.voice_name, "no-voice")
        self.assertFalse(params.rounded_subtitle_background)

    def test_builtin_defaults_apply_when_ui_config_is_empty(self):
        args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, {}, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.font_name, "STHeitiMedium.ttc")
        self.assertEqual(params.text_fore_color, "#FFFFFF")
        self.assertEqual(params.font_size, 60)
        self.assertFalse(params.text_background_color)
        self.assertFalse(params.rounded_subtitle_background)

    def test_ui_config_can_disable_subtitle_background(self):
        """
        自相矛盾的 [ui] 配置不应让 CLI 中断:
        `--no-subtitle-background-enabled` 加上颜色作为命令行组合是参数错误,
        但作为保存的设置只表示背景被禁用。
        """
        ui_config = dict(self.UI_CONFIG)
        ui_config["subtitle_background_enabled"] = False

        args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertFalse(params.text_background_color)
        self.assertFalse(params.rounded_subtitle_background)

    def test_unusable_ui_config_values_fall_back_to_builtin_defaults(self):
        """损坏的 config.toml 不应触发 traceback。"""
        ui_config = {
            "font_size": "sechzig",
            "text_fore_color": 42,
            "font_name": "",
            "voice_name": None,
        }

        args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.font_size, 60)
        self.assertEqual(params.text_fore_color, "#FFFFFF")
        self.assertEqual(params.font_name, "STHeitiMedium.ttc")
        self.assertEqual(params.voice_name, "zh-CN-XiaoxiaoNeural-Female")

    def test_saved_no_voice_mode_disables_tts(self):
        """
        WebUI 把无配音作为独立的 voice_mode 保存,同时保留用户上一次真正选择
        的音色,以便切回自动配音。CLI 必须遵循该模式,否则会重新启用 TTS 并
        可能触发付费供应商请求。
        """
        ui_config = {"voice_mode": "none", "voice_name": "gemini:Puck-Male"}

        args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.voice_name, "no-voice")

    def test_explicit_voice_name_overrides_saved_no_voice_mode(self):
        """命令行显式指定的音色优先级最高,保存的无配音模式不得覆盖它。"""
        ui_config = {"voice_mode": "none", "voice_name": "gemini:Puck-Male"}

        args = cli.parse_args(
            ["--video-subject", "test", "--voice-name", "zh-CN-XiaoxiaoNeural-Female"]
        )

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.voice_name, "zh-CN-XiaoxiaoNeural-Female")

    def test_saved_tts_mode_keeps_saved_voice(self):
        """voice_mode 为自动配音时,保存的音色仍然生效。"""
        ui_config = {"voice_mode": "tts", "voice_name": "gemini:Puck-Male"}

        args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.voice_name, "gemini:Puck-Male")

    def test_enabling_background_without_color_keeps_saved_color(self):
        """
        只传 --subtitle-background-enabled 时用户并未覆盖颜色,应沿用 WebUI
        保存的颜色,而不是回退成黑色背景。
        """
        ui_config = {"subtitle_background_color": "#654321"}

        args = cli.parse_args(
            ["--video-subject", "test", "--subtitle-background-enabled"]
        )

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.text_background_color, "#654321")

    def test_enabling_background_falls_back_to_default_without_saved_color(self):
        """没有可用的保存颜色时,仅开启背景应回退为默认背景。"""
        args = cli.parse_args(
            ["--video-subject", "test", "--subtitle-background-enabled"]
        )

        with patch.dict(app_config.ui, {}, clear=True):
            params = cli.build_video_params(args)

        self.assertIs(params.text_background_color, True)

    def test_explicit_background_color_overrides_saved_color(self):
        """命令行显式指定的背景颜色优先于保存值。"""
        ui_config = {"subtitle_background_color": "#654321"}

        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--subtitle-background-enabled",
                "--subtitle-background-color",
                "#ABCDEF",
            ]
        )

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.text_background_color, "#ABCDEF")

    def test_saved_upload_mode_disables_tts(self):
        """
        上传自备音频的模式同样表示“不要自动配音”,而 [ui] 不保存文件路径,
        CLI 无法复现该上传。此时沿用保存的音色会静默触发付费 TTS 请求,
        因此与无配音一样映射为 no-voice;需要配音时显式传 --voice-name。
        """
        ui_config = {"voice_mode": "upload", "voice_name": "gemini:Puck-Male"}

        args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.voice_name, "no-voice")

    def test_explicit_voice_name_overrides_saved_upload_mode(self):
        """命令行显式指定的音色同样优先于保存的上传模式。"""
        ui_config = {"voice_mode": "upload", "voice_name": "gemini:Puck-Male"}

        args = cli.parse_args(
            ["--video-subject", "test", "--voice-name", "mimo:Female"]
        )

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.voice_name, "mimo:Female")

    def test_saved_color_alone_enables_background(self):
        """
        WebUI 总是同时写入开关和颜色,只保存颜色属于手工编辑的配置。
        此时保存的颜色本身就表明用户想要背景,因此按开启处理。
        """
        ui_config = {"subtitle_background_color": "#654321"}

        args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.text_background_color, "#654321")

    def test_ui_config_supplies_voice_and_stroke_defaults(self):
        """配音音量、语速、描边和字幕开关同样保存在 [ui] 中,需要一并沿用。"""
        ui_config = {
            "voice_volume": 0.5,
            "voice_rate": 1.3,
            "stroke_color": "#112233",
            "stroke_width": 2.5,
            "subtitle_enabled": False,
        }

        args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.voice_volume, 0.5)
        self.assertEqual(params.voice_rate, 1.3)
        self.assertEqual(params.stroke_color, "#112233")
        self.assertEqual(params.stroke_width, 2.5)
        self.assertFalse(params.subtitle_enabled)

    def test_cli_flags_take_precedence_over_saved_voice_and_stroke(self):
        """命令行显式传入的值优先于这些保存值。"""
        ui_config = {
            "voice_volume": 0.5,
            "voice_rate": 1.3,
            "stroke_color": "#112233",
            "stroke_width": 2.5,
            "subtitle_enabled": False,
        }

        args = cli.parse_args(
            [
                "--video-subject",
                "test",
                "--voice-volume",
                "0.9",
                "--voice-rate",
                "1.1",
                "--stroke-color",
                "#AABBCC",
                "--stroke-width",
                "3.5",
                "--subtitle-enabled",
            ]
        )

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.voice_volume, 0.9)
        self.assertEqual(params.voice_rate, 1.1)
        self.assertEqual(params.stroke_color, "#AABBCC")
        self.assertEqual(params.stroke_width, 3.5)
        self.assertTrue(params.subtitle_enabled)

    def test_saved_integers_are_accepted_for_float_fields(self):
        """TOML 中的整数同样是合法音量和语速,应转换后使用而不是丢弃。"""
        ui_config = {"voice_volume": 1, "voice_rate": 2, "stroke_width": 3}

        args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.voice_volume, 1.0)
        self.assertEqual(params.voice_rate, 2.0)
        self.assertEqual(params.stroke_width, 3.0)

    def test_saved_values_out_of_range_fall_back_to_builtin_defaults(self):
        """
        保存值按与命令行相同的规则校验:音量不可为负、语速必须为正、
        颜色必须是 #RRGGBB。不合法的值回退到内置默认值。
        """
        ui_config = {
            "voice_volume": -1.0,
            "voice_rate": 0,
            "stroke_color": "notacolor",
            "stroke_width": -2.0,
            "font_size": 0,
        }

        args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.voice_volume, 1.0)
        self.assertEqual(params.voice_rate, 1.0)
        self.assertEqual(params.stroke_color, "#000000")
        self.assertEqual(params.stroke_width, 1.5)
        self.assertEqual(params.font_size, 60)

    def test_stop_at_subtitle_overrides_saved_subtitle_disabled(self):
        """
        `--stop-at subtitle` 明确要求生成字幕。保存的关闭状态不应让该阶段
        变成空操作,也不应像显式 --no-subtitle-enabled 那样报参数错误。
        """
        ui_config = {"subtitle_enabled": False}

        args = cli.parse_args(
            ["--video-subject", "test", "--stop-at", "subtitle"]
        )

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertTrue(params.subtitle_enabled)

    def test_explicit_no_subtitle_still_rejects_stop_at_subtitle(self):
        """显式关闭字幕与 `--stop-at subtitle` 组合仍然是参数错误。"""
        with self.assertRaises(SystemExit) as cm:
            cli.parse_args(
                [
                    "--video-subject",
                    "test",
                    "--stop-at",
                    "subtitle",
                    "--no-subtitle-enabled",
                ]
            )

        self.assertEqual(cm.exception.code, 2)

    def test_saved_subtitle_position_is_validated_and_applied(self):
        """
        字幕位置此前只依赖 VideoParams 的字段默认值,该默认值在模块导入时
        求值一次,既无法校验也无法在测试中替换。现在与其它字段一样显式解析。
        """
        ui_config = {"subtitle_position": "custom", "custom_position": 42.5}

        args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.subtitle_position, "custom")
        self.assertEqual(params.custom_position, 42.5)

    def test_two_thirds_bottom_subtitle_position_is_supported(self):
        """
        WebUI 的「距底部 2/3」会把 two_thirds_bottom 写进 config.toml,
        app/services/video.py 也按该取值渲染。CLI 此前只认识另外四个位置,
        导致同一个 config.toml 在两个入口产出不同画面。
        """
        explicit_params = cli.build_video_params(
            cli.parse_args(
                [
                    "--video-subject",
                    "test",
                    "--subtitle-position",
                    "two_thirds_bottom",
                ]
            )
        )
        self.assertEqual(explicit_params.subtitle_position, "two_thirds_bottom")

        saved_args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(
            app_config.ui, {"subtitle_position": "two_thirds_bottom"}, clear=True
        ):
            saved_params = cli.build_video_params(saved_args)

        self.assertEqual(saved_params.subtitle_position, "two_thirds_bottom")

    def test_subtitle_positions_stay_aligned_with_the_webui(self):
        """
        两个入口共享同一份 config.toml,因此 CLI 必须接受 WebUI 能保存的每一个
        字幕位置,否则保存值会在命令行入口被静默换成 bottom。
        """
        source = (Path(__file__).parent.parent.parent / "webui" / "Main.py").read_text(
            encoding="utf-8"
        )
        webui_positions = set()
        for node in ast.walk(ast.parse(source)):
            if not isinstance(node, ast.Assign) or not any(
                isinstance(target, ast.Name) and target.id == "subtitle_positions"
                for target in node.targets
            ):
                continue
            webui_positions = {
                ast.literal_eval(element.elts[1]) for element in node.value.elts
            }

        self.assertTrue(webui_positions)
        self.assertEqual(
            sorted(webui_positions - set(cli._SUBTITLE_POSITION_VALUES)), []
        )

    def test_subtitle_style_options_follow_the_flag_then_the_saved_value(self):
        """
        展示模式与入场动画随「逐词字幕 + 弹跳动画」加入,当时只改了 WebUI 与模型
        字段默认值:命令行既没有开关,也不显式读取 [ui] 保存值。
        """
        for flag, field, value in (
            ("--subtitle-display-mode", "subtitle_display_mode", "word_by_word"),
            ("--subtitle-animation", "subtitle_animation", "pop_spring"),
        ):
            with self.subTest(field=field):
                explicit = cli.build_video_params(
                    cli.parse_args(["--video-subject", "test", flag, value])
                )
                self.assertEqual(getattr(explicit, field), value)

                args = cli.parse_args(["--video-subject", "test"])
                with patch.dict(app_config.ui, {field: value}, clear=True):
                    saved = cli.build_video_params(args)
                self.assertEqual(getattr(saved, field), value)

    def test_subtitle_style_values_stay_aligned_with_the_model_and_the_webui(self):
        """
        取值必须与 app/models/schema.py 的权威枚举一致,并覆盖 WebUI 下拉框能保存
        的每一个值;将来新增模式时这里会先失败,避免再次出现「WebUI 支持、命令行
        不支持」的落差。
        """
        for cli_values, model_values in (
            (cli._SUBTITLE_DISPLAY_MODE_VALUES, app_schema._SUBTITLE_DISPLAY_MODES),
            (cli._SUBTITLE_ANIMATION_VALUES, app_schema._SUBTITLE_ANIMATIONS),
        ):
            self.assertEqual(sorted(cli_values), sorted(model_values))

        source = (Path(__file__).parent.parent.parent / "webui" / "Main.py").read_text(
            encoding="utf-8"
        )
        for name, cli_values in (
            ("subtitle_display_modes", cli._SUBTITLE_DISPLAY_MODE_VALUES),
            ("subtitle_animations", cli._SUBTITLE_ANIMATION_VALUES),
        ):
            webui_values = set()
            for node in ast.walk(ast.parse(source)):
                if any(
                    isinstance(target, ast.Name) and target.id == name
                    for target in getattr(node, "targets", [])
                ):
                    webui_values = {
                        ast.literal_eval(element.elts[1])
                        for element in node.value.elts
                    }
            self.assertEqual(sorted(webui_values - set(cli_values)), [], name)

    def test_unusable_saved_subtitle_position_falls_back(self):
        """超出取值范围的保存位置回退到内置默认值。"""
        ui_config = {"subtitle_position": "diagonal", "custom_position": 150.0}

        args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertEqual(params.subtitle_position, "bottom")
        self.assertEqual(params.custom_position, 70.0)

    def test_invalid_saved_background_color_with_saved_enable_flag(self):
        """
        保存的背景颜色同样要按 #RRGGBB 校验。非法值若留在 VideoParams 中,
        渲染时会变成黑色,而同色检测比较的仍是原始非法字符串,导致黑底黑字
        无法被发现。
        """
        ui_config = {
            "subtitle_background_enabled": True,
            "subtitle_background_color": "not-a-color",
        }

        args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertIs(params.text_background_color, True)

    def test_invalid_saved_background_color_with_explicit_enable_flag(self):
        """显式开启背景时,非法的保存颜色同样回退到默认背景。"""
        ui_config = {"subtitle_background_color": "not-a-color"}

        args = cli.parse_args(
            ["--video-subject", "test", "--subtitle-background-enabled"]
        )

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertIs(params.text_background_color, True)

    def test_invalid_saved_background_color_without_enable_flag(self):
        """
        只保存了非法颜色且没有开关时,不应据此推断出需要背景,
        因此保持 VideoParams 的默认关闭状态。
        """
        ui_config = {"subtitle_background_color": "not-a-color"}

        args = cli.parse_args(["--video-subject", "test"])

        with patch.dict(app_config.ui, ui_config, clear=True):
            params = cli.build_video_params(args)

        self.assertFalse(params.text_background_color)


if __name__ == "__main__":
    unittest.main()