File size: 146,920 Bytes
457b8fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
# multi_api_key_manager.py
"""

Multi API Key Manager for Glossarion

Handles multiple API keys with round-robin load balancing and rate limit management

"""

import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext, filedialog
import ttkbootstrap as tb
import json
import os
import threading
import time
import queue
from typing import Dict, List, Optional, Tuple
import requests
from datetime import datetime, timedelta
import logging
from model_options import get_model_options
# Dialog for configuring per-key endpoint
try:
    from individual_endpoint_dialog import IndividualEndpointDialog
except Exception:
    IndividualEndpointDialog = None

logger = logging.getLogger(__name__)
class RateLimitCache:
    """Thread-safe rate limit cache"""
    def __init__(self):
        self._cache = {}  # key_id -> expiry_time
        self._lock = threading.Lock()
    
    def add_rate_limit(self, key_id: str, cooldown_seconds: int):
        """Add a key to rate limit cache"""
        with self._lock:
            self._cache[key_id] = time.time() + cooldown_seconds
            logger.info(f"Added {key_id} to rate limit cache for {cooldown_seconds}s")
    
    def is_rate_limited(self, key_id: str) -> bool:
        """Check if key is rate limited"""
        with self._lock:
            if key_id not in self._cache:
                return False
            
            if time.time() >= self._cache[key_id]:
                # Expired, remove it
                del self._cache[key_id]
                return False
            
            return True
    
    def clear_expired(self):
        """Remove expired entries"""
        with self._lock:
            current_time = time.time()
            expired = [k for k, v in self._cache.items() if current_time >= v]
            for k in expired:
                del self._cache[k]
    
    def get_remaining_cooldown(self, key_id: str) -> float:
        """Get remaining cooldown time in seconds"""
        with self._lock:
            if key_id not in self._cache:
                return 0
            remaining = self._cache[key_id] - time.time()
            return max(0, remaining)


class APIKeyEntry:
    """Enhanced API key entry with thread-safe operations"""
    def __init__(self, api_key: str, model: str, cooldown: int = 60, enabled: bool = True, 

                 google_credentials: str = None, azure_endpoint: str = None, google_region: str = None,

                 azure_api_version: str = None, use_individual_endpoint: bool = False):
        self.api_key = api_key
        self.model = model
        self.cooldown = cooldown
        self.enabled = enabled
        self.google_credentials = google_credentials  # Path to Google service account JSON
        self.azure_endpoint = azure_endpoint  # Azure endpoint URL (only used if use_individual_endpoint is True)
        self.google_region = google_region  # Google Cloud region (e.g., us-east5, us-central1)
        self.azure_api_version = azure_api_version or '2025-01-01-preview'  # Azure API version
        self.use_individual_endpoint = use_individual_endpoint  # Toggle to enable/disable individual endpoint
        self.last_error_time = None
        self.error_count = 0
        self.success_count = 0
        self.last_used_time = None
        self.times_used = 0  # Incremented whenever this key is assigned/used
        self.is_cooling_down = False
        
        # Add lock for thread-safe modifications
        self._lock = threading.Lock()
        
        # Add test result storage
        self.last_test_result = None
        self.last_test_time = None
        self.last_test_message = None
    
    def is_available(self) -> bool:
        with self._lock:
            if not self.enabled:
                return False
            if self.last_error_time and self.is_cooling_down:
                time_since_error = time.time() - self.last_error_time
                if time_since_error < self.cooldown:
                    return False
                else:
                    self.is_cooling_down = False
            return True
    
    def mark_error(self, error_code: int = None):
        with self._lock:
            self.error_count += 1
            self.times_used = getattr(self, 'times_used', 0) + 1
            self.last_error_time = time.time()
            if error_code == 429:
                self.is_cooling_down = True
    
    def mark_success(self):
        with self._lock:
            self.success_count += 1
            self.times_used = getattr(self, 'times_used', 0) + 1
            self.last_used_time = time.time()
            self.error_count = 0
    
    def set_test_result(self, result: str, message: str = None):
        """Store test result"""
        with self._lock:
            self.last_test_result = result
            self.last_test_time = time.time()
            self.last_test_message = message
            
    def to_dict(self):
        """Convert to dictionary for saving"""
        return {
            'api_key': self.api_key,
            'model': self.model,
            'cooldown': self.cooldown,
            'enabled': self.enabled,
            'google_credentials': self.google_credentials,
            'azure_endpoint': self.azure_endpoint,
            'google_region': self.google_region,
            'azure_api_version': self.azure_api_version,
            'use_individual_endpoint': self.use_individual_endpoint,
            # Persist times used optionally (non-breaking if ignored elsewhere)
            'times_used': getattr(self, 'times_used', 0)
        }
class APIKeyPool:
    """Thread-safe API key pool with proper rotation"""
    def __init__(self):
        self.keys: List[APIKeyEntry] = []
        self.lock = threading.Lock()  # This already exists
        self._rotation_index = 0
        self._thread_assignments = {}
        self._rate_limit_cache = RateLimitCache()
        
        # NEW LOCKS:
        self.key_locks = {}  # Will be populated when keys are loaded
        self.key_selection_lock = threading.Lock()  # For coordinating key selection across threads
        
        # Track which keys are currently being used by which threads
        self._keys_in_use = {}  # key_index -> set of thread_ids
        self._usage_lock = threading.Lock()
    
    def load_from_list(self, key_list: List[dict]):
        with self.lock:
            # Preserve existing counters by mapping old entries by (api_key, model)
            old_map = {}
            for old in getattr(self, 'keys', []):
                key = (getattr(old, 'api_key', ''), getattr(old, 'model', ''))
                old_map[key] = old
            
            self.keys.clear()
            self.key_locks.clear()  # Clear existing locks
            
            for i, key_data in enumerate(key_list):
                api_key = key_data.get('api_key', '')
                model = key_data.get('model', '')
                entry = APIKeyEntry(
                    api_key=api_key,
                    model=model,
                    cooldown=key_data.get('cooldown', 60),
                    enabled=key_data.get('enabled', True),
                    google_credentials=key_data.get('google_credentials'),
                    azure_endpoint=key_data.get('azure_endpoint'),
                    google_region=key_data.get('google_region'),
                    azure_api_version=key_data.get('azure_api_version'),
                    use_individual_endpoint=key_data.get('use_individual_endpoint', False)
                )
                # Restore counters if we had this key before
                old = old_map.get((api_key, model))
                if old is not None:
                    try:
                        entry.success_count = getattr(old, 'success_count', entry.success_count)
                        entry.error_count = getattr(old, 'error_count', entry.error_count)
                        entry.times_used = getattr(old, 'times_used', getattr(old, 'success_count', 0) + getattr(old, 'error_count', 0))
                        entry.last_used_time = getattr(old, 'last_used_time', None)
                        entry.last_error_time = getattr(old, 'last_error_time', None)
                        entry.is_cooling_down = getattr(old, 'is_cooling_down', False)
                        entry.last_test_result = getattr(old, 'last_test_result', None)
                        entry.last_test_time = getattr(old, 'last_test_time', None)
                        entry.last_test_message = getattr(old, 'last_test_message', None)
                    except Exception:
                        pass
                self.keys.append(entry)
                # Create a lock for each key
                self.key_locks[i] = threading.Lock()
            
            # Keep rotation index if possible
            if getattr(self, '_rotation_index', 0) >= len(self.keys):
                self._rotation_index = 0
            else:
                self._rotation_index = getattr(self, '_rotation_index', 0)
            self._keys_in_use.clear()
            logger.info(f"Loaded {len(self.keys)} API keys into pool with individual locks (preserved counters where possible)")
    
    def get_key_for_thread(self, force_rotation: bool = False, 

                          rotation_frequency: int = 1) -> Optional[Tuple[APIKeyEntry, int, str]]:
        """Get a key for the current thread with proper rotation logic"""
        thread_id = threading.current_thread().ident
        thread_name = threading.current_thread().name
        
        # Clear expired rate limits first
        self._rate_limit_cache.clear_expired()
        
        # Use key_selection_lock for the entire selection process
        with self.key_selection_lock:
            if not self.keys:
                return None
            
            # Check if thread already has an assignment
            if thread_id in self._thread_assignments and not force_rotation:
                key_index, assignment_time = self._thread_assignments[thread_id]
                if key_index < len(self.keys):
                    key = self.keys[key_index]
                    key_id = f"Key#{key_index+1} ({key.model})"
                    
                    # Check if the assigned key is still available
                    # Use the key-specific lock for checking availability
                    with self.key_locks.get(key_index, threading.Lock()):
                        if key.is_available() and not self._rate_limit_cache.is_rate_limited(key_id):
                            logger.debug(f"[Thread-{thread_name}] Reusing assigned {key_id}")
                            
                            # Track usage
                            with self._usage_lock:
                                if key_index not in self._keys_in_use:
                                    self._keys_in_use[key_index] = set()
                                self._keys_in_use[key_index].add(thread_id)
                            
                            return key, key_index, key_id
                        else:
                            # Remove invalid assignment
                            del self._thread_assignments[thread_id]
            
            # Find next available key using round-robin
            start_index = self._rotation_index
            attempts = 0
            
            while attempts < len(self.keys):
                # Get current index and immediately increment for next thread
                key_index = self._rotation_index
                self._rotation_index = (self._rotation_index + 1) % len(self.keys)
                
                key = self.keys[key_index]
                key_id = f"Key#{key_index+1} ({key.model})"
                
                # Use key-specific lock when checking and modifying key state
                with self.key_locks.get(key_index, threading.Lock()):
                    if key.is_available() and not self._rate_limit_cache.is_rate_limited(key_id):
                        # Assign to thread
                        self._thread_assignments[thread_id] = (key_index, time.time())
                        
                        # Increment usage counter on assignment
                        try:
                            key.times_used += 1
                        except Exception:
                            pass
                        
                        # Track usage
                        with self._usage_lock:
                            if key_index not in self._keys_in_use:
                                self._keys_in_use[key_index] = set()
                            self._keys_in_use[key_index].add(thread_id)
                        
                        # Clean up old assignments
                        current_time = time.time()
                        expired_threads = [
                            tid for tid, (_, ts) in self._thread_assignments.items()
                            if current_time - ts > 300  # 5 minutes
                        ]
                        for tid in expired_threads:
                            del self._thread_assignments[tid]
                            # Remove from usage tracking
                            with self._usage_lock:
                                for k_idx in list(self._keys_in_use.keys()):
                                    self._keys_in_use[k_idx].discard(tid)
                                    if not self._keys_in_use[k_idx]:
                                        del self._keys_in_use[k_idx]
                        
                        logger.info(f"[Thread-{thread_name}] Assigned {key_id}")
                        time.sleep(0.5)  # Brief pause to improve retry responsiveness
                        logger.debug("πŸ’€ Pausing briefly to improve retry responsiveness after key assignment")
                        return key, key_index, key_id
                
                attempts += 1
            
            # No available keys - find one with shortest cooldown
            best_key_index = None
            min_cooldown = float('inf')
            
            for i, key in enumerate(self.keys):
                if key.enabled:  # At least check if enabled
                    key_id = f"Key#{i+1} ({key.model})"
                    remaining = self._rate_limit_cache.get_remaining_cooldown(key_id)
                    
                    # Also check key's own cooldown
                    if key.is_cooling_down and key.last_error_time:
                        key_cooldown = key.cooldown - (time.time() - key.last_error_time)
                        remaining = max(remaining, key_cooldown)
                    
                    if remaining < min_cooldown:
                        min_cooldown = remaining
                        best_key_index = i
            
            if best_key_index is not None:
                key = self.keys[best_key_index]
                key_id = f"Key#{best_key_index+1} ({key.model})"
                logger.warning(f"[Thread-{thread_name}] All keys on cooldown, using {key_id} (cooldown: {min_cooldown:.1f}s)")
                self._thread_assignments[thread_id] = (best_key_index, time.time())
                time.sleep(0.5)  # Brief pause to improve retry responsiveness
                logger.debug("πŸ’€ Pausing briefly to improve retry responsiveness after cooldown key selection")
                return key, best_key_index, key_id
            
            logger.error(f"[Thread-{thread_name}] No keys available at all")
            return None
    
    def mark_key_error(self, key_index: int, error_code: int = None):
        """Mark a key as having an error (thread-safe with key-specific lock)"""
        if 0 <= key_index < len(self.keys):
            # Use key-specific lock for this operation
            with self.key_locks.get(key_index, threading.Lock()):
                # Mark error on the key itself
                self.keys[key_index].mark_error(error_code)
                
                # Add to rate limit cache if it's a 429
                if error_code == 429:
                    key = self.keys[key_index]
                    key_id = f"Key#{key_index+1} ({key.model})"
                    self._rate_limit_cache.add_rate_limit(key_id, key.cooldown)
                    
                    print(f"Marked key {key_id} with an error code")
                    time.sleep(0.5)  # Brief pause to improve retry responsiveness
                    logger.debug("πŸ’€ Pausing briefly to improve retry responsiveness after marking key error")

    def mark_key_success(self, key_index: int):
        """Mark a key as successful (thread-safe with key-specific lock)"""
        if 0 <= key_index < len(self.keys):
            # Use key-specific lock for this operation
            with self.key_locks.get(key_index, threading.Lock()):
                self.keys[key_index].mark_success()
                
                key = self.keys[key_index]
                print(f"Marked key {key_index} ({key.model}) as successful")
    
    def release_thread_assignment(self, thread_id: int = None):
        """Release key assignment for a thread"""
        if thread_id is None:
            thread_id = threading.current_thread().ident
        
        with self.key_selection_lock:
            # Remove from assignments
            if thread_id in self._thread_assignments:
                key_index, _ = self._thread_assignments[thread_id]
                del self._thread_assignments[thread_id]
                
                # Remove from usage tracking
                with self._usage_lock:
                    if key_index in self._keys_in_use:
                        self._keys_in_use[key_index].discard(thread_id)
                        if not self._keys_in_use[key_index]:
                            del self._keys_in_use[key_index]
                
                print(f"Released key assignment for thread {thread_id}")

    def get_all_keys(self) -> List[APIKeyEntry]:
        """Get all keys in the pool"""
        with self.lock:
            return self.keys.copy()

    @property
    def current_index(self):
        """Get the current rotation index"""
        with self.lock:
            return self._rotation_index

    @current_index.setter
    def current_index(self, value: int):
        """Set the current rotation index"""
        with self.lock:
            if self.keys:
                self._rotation_index = value % len(self.keys)
            else:
                self._rotation_index = 0
            
    def add_key(self, key_entry: APIKeyEntry):
        """Add a new key to the pool"""
        with self.lock:
            self.keys.append(key_entry)
            logger.info(f"Added key for model {key_entry.model} to pool")

    def remove_key(self, index: int):
        """Remove a key from the pool by index"""
        with self.lock:
            if 0 <= index < len(self.keys):
                removed_key = self.keys.pop(index)
                # Clean up any thread assignments for this key
                threads_to_remove = []
                for thread_id, (key_index, _) in self._thread_assignments.items():
                    if key_index == index:
                        threads_to_remove.append(thread_id)
                    elif key_index > index:
                        # Adjust indices for keys after the removed one
                        self._thread_assignments[thread_id] = (key_index - 1, self._thread_assignments[thread_id][1])
                
                for thread_id in threads_to_remove:
                    del self._thread_assignments[thread_id]
                
                # Reset rotation index if needed
                if self._rotation_index >= len(self.keys) and len(self.keys) > 0:
                    self._rotation_index = 0
                
                logger.info(f"Removed key for model {removed_key.model} from pool")

class MultiAPIKeyDialog:
    """Dialog for managing multiple API keys"""
    
    def __init__(self, parent, translator_gui):
        self.parent = parent
        self.translator_gui = translator_gui
        self.dialog = None
        # Keep a reference for icon image to avoid GC
        self._icon_photo_ref = None

        self.key_pool = APIKeyPool()
        self.tree = None
        self.test_results = queue.Queue()
        
        # Attempt to bind to UnifiedClient's shared pool so UI reflects live usage
        self._bind_shared_pool()
        
        # Load existing keys from config
        self._load_keys_from_config()
        
        # Create and show dialog
        self._create_dialog()
        
        # Auto-resize to fit content if WindowManager is available
        if hasattr(self.translator_gui, 'wm') and hasattr(self, 'canvas'):
            self.translator_gui.wm.auto_resize_dialog(self.dialog, self.canvas, 
                                                      max_width_ratio=0.9, 
                                                      max_height_ratio=1.55)
        
    def _set_icon(self, window):
        """Set Halgakos.ico as window icon if available."""
        try:
            base_dir = getattr(self.translator_gui, 'base_dir', os.getcwd())
            ico_path = os.path.join(base_dir, 'Halgakos.ico')
            if os.path.isfile(ico_path):
                try:
                    window.iconbitmap(ico_path)
                except Exception:
                    pass
                # Try iconphoto for better scaling
                try:
                    from PIL import Image, ImageTk
                    img = Image.open(ico_path)
                    if img.mode != 'RGBA':
                        img = img.convert('RGBA')
                    self._icon_photo_ref = ImageTk.PhotoImage(img)
                    window.iconphoto(False, self._icon_photo_ref)
                except Exception:
                    pass
        except Exception:
            pass

    def _bind_shared_pool(self):
        """Bind this dialog to the UnifiedClient's shared APIKeyPool if available.

        If UnifiedClient has no pool yet, register our pool as the shared pool.

        This keeps Times Used and other counters in sync across UI and runtime.

        """
        try:
            from unified_api_client import UnifiedClient
            # If UC already has a pool, use it; otherwise share ours
            if getattr(UnifiedClient, '_api_key_pool', None) is not None:
                self.key_pool = UnifiedClient._api_key_pool
            else:
                UnifiedClient._api_key_pool = self.key_pool
        except Exception:
            # If import fails (early load), continue with local pool
            pass

    def _load_keys_from_config(self):
        """Load API keys from translator GUI config"""
        if hasattr(self.translator_gui, 'config'):
            multi_api_keys = self.translator_gui.config.get('multi_api_keys', [])
            self.key_pool.load_from_list(multi_api_keys)
    
    def _update_rotation_display(self, *args):
        """Update the rotation description based on settings"""
        if self.force_rotation_var.get():
            freq = self.rotation_frequency_var.get()
            if freq == 1:
                desc = "Keys will rotate on every request (maximum distribution)"
            else:
                desc = f"Keys will rotate every {freq} requests"
        else:
            desc = "Keys will only rotate on errors or rate limits"
        
        self.rotation_desc_label.config(text=desc)
    
    def _save_keys_to_config(self):
        """Save API keys and rotation settings to translator GUI config"""
        if hasattr(self.translator_gui, 'config'):
            # Convert keys to list of dicts
            key_list = [key.to_dict() for key in self.key_pool.get_all_keys()]
            self.translator_gui.config['multi_api_keys'] = key_list
            
            # Save fallback settings
            self.translator_gui.config['use_fallback_keys'] = self.use_fallback_var.get()
            # Update the parent GUI's variable to stay in sync
            if hasattr(self.translator_gui, 'use_fallback_keys_var'):
                self.translator_gui.use_fallback_keys_var.set(self.use_fallback_var.get())
            # Fallback keys are already saved when added/removed
            
            # Use the current state of the toggle
            self.translator_gui.config['use_multi_api_keys'] = self.enabled_var.get()
            
            # Save rotation settings
            self.translator_gui.config['force_key_rotation'] = self.force_rotation_var.get()
            self.translator_gui.config['rotation_frequency'] = self.rotation_frequency_var.get()
            
            # Save config
            self.translator_gui.save_config(show_message=False)
    
    def _create_dialog(self):
        """Create the main dialog using WindowManager"""
        # Use WindowManager to create scrollable dialog
        if hasattr(self.translator_gui, 'wm'):
            self.dialog, scrollable_frame, self.canvas = self.translator_gui.wm.setup_scrollable(
                self.parent,
                "Multi API Key Manager",
                width=900,
                height=700,
                max_width_ratio=0.9,
                max_height_ratio=1.45
            )
        else:
            # Fallback to regular dialog
            self.dialog = tk.Toplevel(self.parent)
            self.dialog.title("Multi API Key Manager")
            self.dialog.geometry("900x700")
            scrollable_frame = self.dialog
            self.canvas = None
        
        # Main container with consistent padding
        main_frame = tk.Frame(scrollable_frame, padx=20, pady=20)
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # Store references
        self.main_frame = main_frame
        self.scrollable_frame = scrollable_frame
        
        # Title and description
        title_frame = tk.Frame(main_frame)
        title_frame.pack(fill=tk.X, pady=(0, 10))
        
        tk.Label(title_frame, text="Multi API Key Management", 
                font=('TkDefaultFont', 16, 'bold')).pack(side=tk.LEFT)
        
        # Enable/Disable toggle
        self.enabled_var = tk.BooleanVar(value=self.translator_gui.config.get('use_multi_api_keys', False))
        tb.Checkbutton(title_frame, text="Enable Multi-Key Mode", 
                      variable=self.enabled_var,
                      bootstyle="round-toggle",
                      command=self._toggle_multi_key_mode).pack(side=tk.RIGHT, padx=(20, 0))
        
        tk.Label(main_frame, 
                text="Manage multiple API keys with automatic rotation and rate limit handling.\n"
                     "Keys can be rotated automatically to distribute load evenly.\n"
                     "Rate-limited keys are automatically cooled down and skipped in rotation.",
                font=('TkDefaultFont', 10), fg='gray', justify=tk.LEFT).pack(anchor=tk.W, pady=(0, 15))
        
        # Rotation settings frame
        rotation_frame = tk.LabelFrame(main_frame, text="Rotation Settings", padx=15, pady=10)
        rotation_frame.pack(fill=tk.X, pady=(0, 15))
        
        # Force rotation toggle
        rotation_settings = tk.Frame(rotation_frame)
        rotation_settings.pack(fill=tk.X)
        
        self.force_rotation_var = tk.BooleanVar(value=self.translator_gui.config.get('force_key_rotation', True))
        tb.Checkbutton(rotation_settings, text="Force Key Rotation", 
                      variable=self.force_rotation_var,
                      bootstyle="round-toggle",
                      command=self._update_rotation_display).pack(side=tk.LEFT)
        
        # Rotation frequency
        tk.Label(rotation_settings, text="Every").pack(side=tk.LEFT, padx=(20, 5))
        self.rotation_frequency_var = tk.IntVar(value=self.translator_gui.config.get('rotation_frequency', 1))
        frequency_spinbox = tb.Spinbox(rotation_settings, from_=1, to=100, 
                                      textvariable=self.rotation_frequency_var,
                                      width=5, command=self._update_rotation_display)
        frequency_spinbox.pack(side=tk.LEFT)
        # Disable mouse wheel changing values (use main GUI helper if available)
        try:
            if hasattr(self.translator_gui, 'ui') and hasattr(self.translator_gui.ui, 'disable_spinbox_mousewheel'):
                self.translator_gui.ui.disable_spinbox_mousewheel(frequency_spinbox)
        except Exception:
            pass
        tk.Label(rotation_settings, text="requests").pack(side=tk.LEFT, padx=(5, 0))
        
        # Rotation description
        self.rotation_desc_label = tk.Label(rotation_frame, 
                                          text="", 
                                          font=('TkDefaultFont', 9), fg='blue')
        self.rotation_desc_label.pack(anchor=tk.W, pady=(5, 0))
        self._update_rotation_display()
        
        # Add key section
        self._create_add_key_section(main_frame)
        
        # Separator
        ttk.Separator(main_frame, orient='horizontal').pack(fill=tk.X, pady=15)
        
        # Key list section
        self._create_key_list_section(main_frame)
        
        # Create fallback container (hidden by default)
        self._create_fallback_section(main_frame)
        
        # Button bar at the bottom
        self._create_button_bar(main_frame)
        
        # Load existing keys into tree
        self._refresh_key_list()
        
        # Center dialog
        self.dialog.transient(self.parent)
        
        # Handle window close
        self.dialog.protocol("WM_DELETE_WINDOW", self._on_close)

    def _create_fallback_section(self, parent):
        """Create the fallback keys section at the bottom"""
        # Container that can be hidden
        self.fallback_container = tk.Frame(parent)
        
        # Always show fallback section (works in both single and multi-key mode)
        self.fallback_container.pack(fill=tk.X, pady=(10, 0))
        
        # Separator
        ttk.Separator(self.fallback_container, orient='horizontal').pack(fill=tk.X, pady=(0, 10))
        
        # Main fallback frame
        fallback_frame = tk.LabelFrame(self.fallback_container, 
                                       text="Fallback Keys (For Prohibited Content)", 
                                       padx=15, pady=15)
        fallback_frame.pack(fill=tk.X)
        
        # Description
        tk.Label(fallback_frame, 
                text="Configure fallback keys that will be used when content is blocked.\n"
                     "These should use different API keys or models that are less restrictive.\n"
                     "In Multi-Key Mode: tried when main rotation encounters prohibited content.\n"
                     "In Single-Key Mode: tried directly when main key fails, bypassing main key retry.",
                font=('TkDefaultFont', 10), fg='gray', justify=tk.LEFT).pack(anchor=tk.W, pady=(0, 10))
        
        # Enable fallback checkbox
        self.use_fallback_var = tk.BooleanVar(value=self.translator_gui.config.get('use_fallback_keys', False))
        tb.Checkbutton(fallback_frame, text="Enable Fallback Keys", 
                      variable=self.use_fallback_var,
                      bootstyle="round-toggle",
                      command=self._toggle_fallback_section).pack(anchor=tk.W, pady=(0, 10))
        
        # Add fallback key section
        add_fallback_frame = tk.Frame(fallback_frame)
        add_fallback_frame.pack(fill=tk.X, pady=(0, 10))
        
        # Configure grid for more columns
        add_fallback_frame.columnconfigure(1, weight=1)
        add_fallback_frame.columnconfigure(4, weight=1)
        # Don't give weight to column 3 to keep labels close to fields
        
        # Row 0: Fallback API Key and Model
        tk.Label(add_fallback_frame, text="Fallback API Key:").grid(row=0, column=0, sticky=tk.W, padx=(0, 10), pady=5)
        self.fallback_key_var = tk.StringVar()
        self.fallback_key_entry = tb.Entry(add_fallback_frame, textvariable=self.fallback_key_var, show='*')
        self.fallback_key_entry.grid(row=0, column=1, sticky=tk.EW, pady=5)
        
        # Toggle fallback visibility
        self.show_fallback_btn = tb.Button(add_fallback_frame, text="πŸ‘", width=3,
                                          command=self._toggle_fallback_visibility)
        self.show_fallback_btn.grid(row=0, column=2, padx=5, pady=5)
        
        # Fallback Model
        tk.Label(add_fallback_frame, text="Model:").grid(row=0, column=3, sticky=tk.W, padx=(20, 10), pady=5)
        self.fallback_model_var = tk.StringVar()
        fallback_models = get_model_options()
        self.fallback_model_combo = tb.Combobox(add_fallback_frame, textvariable=self.fallback_model_var,
                                               values=fallback_models, state='normal')
        self.fallback_model_combo.grid(row=0, column=4, sticky=tk.EW, pady=5)
        # Block mouse wheel on combobox to avoid accidental changes
        try:
            if hasattr(self.translator_gui, 'ui') and hasattr(self.translator_gui.ui, 'disable_spinbox_mousewheel'):
                self.translator_gui.ui.disable_spinbox_mousewheel(self.fallback_model_combo)
        except Exception:
            pass
        # Attach gentle autofill
        self._attach_model_autofill(self.fallback_model_combo, self.fallback_model_var)
        
        # Add fallback button
        tb.Button(add_fallback_frame, text="Add Fallback Key", 
                 command=self._add_fallback_key,
                 bootstyle="info").grid(row=0, column=5, sticky=tk.E, padx=(10, 0), pady=5)
        
        # Row 1: Google Credentials (optional, discretely styled)
        tk.Label(add_fallback_frame, text="Google Creds:", font=('TkDefaultFont', 8), 
                fg='gray').grid(row=1, column=0, sticky=tk.W, padx=(0, 10), pady=2)
        self.fallback_google_creds_var = tk.StringVar()
        self.fallback_google_creds_entry = tb.Entry(add_fallback_frame, textvariable=self.fallback_google_creds_var,
                                                   font=('TkDefaultFont', 7), state='normal')
        self.fallback_google_creds_entry.grid(row=1, column=1, sticky=tk.EW, pady=2)
        
        # Google credentials browse button (moved closer)
        tb.Button(add_fallback_frame, text="πŸ“", width=3, 
                 command=self._browse_fallback_google_credentials,
                 bootstyle="secondary-outline").grid(row=1, column=2, padx=(5, 0), pady=2)
        
        # Google region field for fallback
        tk.Label(add_fallback_frame, text="Region:", font=('TkDefaultFont', 10), 
                fg='gray').grid(row=1, column=3, sticky=tk.W, padx=(10, 5), pady=2)
        self.fallback_google_region_var = tk.StringVar(value='us-east5')  # Default region
        self.fallback_google_region_entry = tb.Entry(add_fallback_frame, textvariable=self.fallback_google_region_var,
                                                    font=('TkDefaultFont', 7), state='normal', width=10)
        self.fallback_google_region_entry.grid(row=1, column=4, sticky=tk.W, pady=2)
        
        # Row 2: Azure Endpoint (optional, discretely styled)
        tk.Label(add_fallback_frame, text="Azure Endpoint:", font=('TkDefaultFont', 8), 
                fg='gray').grid(row=2, column=0, sticky=tk.W, padx=(0, 10), pady=2)
        self.fallback_azure_endpoint_var = tk.StringVar()
        self.fallback_azure_endpoint_entry = tb.Entry(add_fallback_frame, textvariable=self.fallback_azure_endpoint_var,
                                                     font=('TkDefaultFont', 7), state='normal')
        self.fallback_azure_endpoint_entry.grid(row=2, column=1, columnspan=2, sticky=tk.EW, pady=2)
        
        # Azure API Version for fallback (small dropdown)
        tk.Label(add_fallback_frame, text="API Ver:", font=('TkDefaultFont', 10), 
                fg='gray').grid(row=2, column=3, sticky=tk.W, padx=(10, 5), pady=2)
        self.fallback_azure_api_version_var = tk.StringVar(value='2025-01-01-preview')
        fallback_azure_versions = [
            '2025-01-01-preview',
            '2024-12-01-preview', 
            '2024-10-01-preview',
            '2024-08-01-preview',
            '2024-06-01',
            '2024-02-01',
            '2023-12-01-preview'
        ]
        self.fallback_azure_api_version_combo = ttk.Combobox(add_fallback_frame, 
                                                            textvariable=self.fallback_azure_api_version_var,
                                                            values=fallback_azure_versions, width=18, 
                                                            state='normal', font=('TkDefaultFont', 7))
        self.fallback_azure_api_version_combo.grid(row=2, column=4, sticky=tk.W, pady=2)
        # Block mouse wheel on version combobox
        try:
            if hasattr(self.translator_gui, 'ui') and hasattr(self.translator_gui.ui, 'disable_spinbox_mousewheel'):
                self.translator_gui.ui.disable_spinbox_mousewheel(self.fallback_azure_api_version_combo)
        except Exception:
            pass
        
        # Fallback keys list
        self._create_fallback_list(fallback_frame)
        
        # Initially disable if checkbox is unchecked
        self._toggle_fallback_section()

    def _create_fallback_list(self, parent):
        """Create the fallback keys list"""
        list_frame = tk.Frame(parent)
        list_frame.pack(fill=tk.BOTH, expand=True)
        
        # Label
        tk.Label(list_frame, text="Fallback Keys (tried in order):", 
                font=('TkDefaultFont', 10, 'bold')).pack(anchor=tk.W, pady=(10, 5))
        
        # Container for tree and buttons
        container = tk.Frame(list_frame)
        container.pack(fill=tk.BOTH, expand=True)
        
        # Left side: Move buttons
        move_frame = tk.Frame(container)
        move_frame.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 5))
        
        tk.Label(move_frame, text="Order", font=('TkDefaultFont', 9, 'bold')).pack(pady=(0, 5))
        
        tb.Button(move_frame, text="↑", width=3,
                 command=lambda: self._move_fallback_key('up'),
                 bootstyle="secondary-outline").pack(pady=2)
        
        tb.Button(move_frame, text="↓", width=3,
                 command=lambda: self._move_fallback_key('down'),
                 bootstyle="secondary-outline").pack(pady=2)
        
        # Right side: Treeview
        tree_container = tk.Frame(container)
        tree_container.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        # Scrollbar
        scrollbar = ttk.Scrollbar(tree_container, orient=tk.VERTICAL)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # Treeview for fallback keys
        columns = ('Model', 'Status', 'Times Used')
        self.fallback_tree = ttk.Treeview(tree_container, columns=columns, show='tree headings',
                                          yscrollcommand=scrollbar.set, height=5)
        self.fallback_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        scrollbar.config(command=self.fallback_tree.yview)
        self.fallback_tree.bind('<Button-3>', self._show_fallback_context_menu)
        
        # Configure columns
        self.fallback_tree.heading('#0', text='API Key', anchor='w')
        self.fallback_tree.column('#0', width=220, minwidth=160, anchor='w')
        
        self.fallback_tree.heading('Model', text='Model', anchor='w')
        self.fallback_tree.column('Model', width=220, minwidth=140, anchor='w')
        
        self.fallback_tree.heading('Status', text='Status', anchor='center')
        self.fallback_tree.column('Status', width=120, minwidth=80, anchor='center')
        
        self.fallback_tree.heading('Times Used', text='Times Used', anchor='center')
        self.fallback_tree.column('Times Used', width=100, minwidth=70, anchor='center')
        
        # Action buttons - store reference for toggling
        self.fallback_action_frame = tk.Frame(list_frame)
        self.fallback_action_frame.pack(fill=tk.X, pady=(10, 0))
        
        tb.Button(self.fallback_action_frame, text="Test Selected", 
                 command=self._test_selected_fallback,
                 bootstyle="warning").pack(side=tk.LEFT, padx=(0, 5))

        tb.Button(self.fallback_action_frame, text="Test All", 
                 command=self._test_all_fallbacks,
                 bootstyle="warning").pack(side=tk.LEFT, padx=5)
    
        tb.Button(self.fallback_action_frame, text="Remove Selected", 
                 command=self._remove_selected_fallback,
                 bootstyle="danger").pack(side=tk.LEFT, padx=5)
        
        tb.Button(self.fallback_action_frame, text="Clear All", 
                 command=self._clear_all_fallbacks,
                 bootstyle="danger-outline").pack(side=tk.LEFT, padx=5)
        
        # Load existing fallback keys
        self._load_fallback_keys()

    def _test_all_fallbacks(self):
        """Test all fallback keys"""
        fallback_keys = self.translator_gui.config.get('fallback_keys', [])
        
        if not fallback_keys:
            messagebox.showwarning("Warning", "No fallback keys to test")
            return
        
        # Update UI to show testing status for all keys
        items = self.fallback_tree.get_children()
        for item in items:
            values = list(self.fallback_tree.item(item, 'values'))
            values[1] = "⏳ Testing..."
            self.fallback_tree.item(item, values=values)
        
        # Run tests in thread for all fallback keys
        # Ensure UnifiedClient uses the same shared pool instance
        try:
            from unified_api_client import UnifiedClient
            UnifiedClient._api_key_pool = self.key_pool
        except Exception:
            pass
        thread = threading.Thread(target=self._test_all_fallback_keys_batch)
        thread.daemon = True
        thread.start()


    def _test_all_fallback_keys_batch(self):
        """Test all fallback keys in batch"""
        from unified_api_client import UnifiedClient
        from concurrent.futures import ThreadPoolExecutor, as_completed
        
        fallback_keys = self.translator_gui.config.get('fallback_keys', [])
        
        def test_single_key(index, key_data):
            """Test a single fallback key"""
            api_key = key_data.get('api_key', '')
            model = key_data.get('model', '')
            
            try:
                client = UnifiedClient(
                    api_key=api_key,
                    model=model,
                    output_dir=None
                )
                
                messages = [
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": "Say 'API test successful' and nothing else."}
                ]
                
                response = client.send(
                    messages,
                    temperature=0.7,
                    max_tokens=100
                )
                
                if response and isinstance(response, tuple):
                    content, _ = response
                    if content and "test successful" in content.lower():
                        return (index, True, "Passed")
            except Exception as e:
                print(f"Fallback key test failed: {e}")
                return (index, False, str(e)[:30])
            
            return (index, False, "Failed")
        
        # Test all keys in parallel
        with ThreadPoolExecutor(max_workers=min(5, len(fallback_keys))) as executor:
            futures = []
            for i, key_data in enumerate(fallback_keys):
                future = executor.submit(test_single_key, i, key_data)
                futures.append(future)
            
            # Process results as they complete
            for future in as_completed(futures):
                result = future.result()
                if result:
                    index, success, message = result
                    # Update UI in main thread
                    self.dialog.after(0, lambda idx=index, s=success: 
                                     self._update_fallback_test_result(idx, s))
        
        # Show completion message
        successful = sum(1 for future in futures if future.result() and future.result()[1])
        total = len(fallback_keys)
        self.dialog.after(0, lambda: self._show_status(
            f"Fallback test complete: {successful}/{total} passed"))

    def _show_fallback_context_menu(self, event):
        """Show context menu for fallback keys - includes model name editing"""
        # Select item under cursor
        item = self.fallback_tree.identify_row(event.y)
        if item:
            # If the clicked item is not in selection, select only it
            if item not in self.fallback_tree.selection():
                self.fallback_tree.selection_set(item)
            
            # Create context menu
            menu = tk.Menu(self.dialog, tearoff=0)
            
            # Get index for position info
            index = self.fallback_tree.index(item)
            fallback_keys = self.translator_gui.config.get('fallback_keys', [])
            total = len(fallback_keys)
            
            # Reorder submenu
            if total > 1:  # Only show reorder if there's more than one key
                reorder_menu = tk.Menu(menu, tearoff=0)
                if index > 0:
                    reorder_menu.add_command(label="Move Up", 
                                            command=lambda: self._move_fallback_key('up'))
                if index < total - 1:
                    reorder_menu.add_command(label="Move Down", 
                                            command=lambda: self._move_fallback_key('down'))
                menu.add_cascade(label="Reorder", menu=reorder_menu)
                menu.add_separator()
            
            # Add Change Model option
            selected_count = len(self.fallback_tree.selection())
            if selected_count > 1:
                menu.add_command(label=f"Change Model ({selected_count} selected)", 
                               command=self._change_fallback_model_for_selected)
            else:
                menu.add_command(label="Change Model", 
                               command=self._change_fallback_model_for_selected)
            
            menu.add_separator()
            
            # Test and Remove options
            menu.add_command(label="Test", command=self._test_selected_fallback)
            menu.add_separator()
            menu.add_command(label="Remove", command=self._remove_selected_fallback)
            
            if total > 1:
                menu.add_command(label="Clear All", command=self._clear_all_fallbacks)
            
            # Show menu
            menu.post(event.x_root, event.y_root)


    def _change_fallback_model_for_selected(self):
        """Change model name for selected fallback keys"""
        selected = self.fallback_tree.selection()
        if not selected:
            return
        
        # Get fallback keys
        fallback_keys = self.translator_gui.config.get('fallback_keys', [])
        
        # Create simple dialog (same style as main tree)
        dialog = tk.Toplevel(self.dialog)
        dialog.title(f"Change Model for {len(selected)} Fallback Keys")
        dialog.geometry("400x130")
        dialog.transient(self.dialog)
        # Set icon
        self._set_icon(dialog)
        
        # Center the dialog
        dialog.update_idletasks()
        x = (dialog.winfo_screenwidth() // 2) - (dialog.winfo_width() // 2)
        y = (dialog.winfo_screenheight() // 2) - (dialog.winfo_height() // 2)
        dialog.geometry(f"+{x}+{y}")
        
        # Main frame
        main_frame = tk.Frame(dialog, padx=20, pady=20)
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # Label
        tk.Label(main_frame, text="Enter new model name (press Enter to apply):",
                font=('TkDefaultFont', 10)).pack(pady=(0, 10))
        
        # Model entry with dropdown
        model_var = tk.StringVar()
        
        # Full model list (same as main GUI)
        all_models = get_model_options()
        
        model_combo = ttk.Combobox(main_frame, values=all_models, 
                                   textvariable=model_var, width=45, height=12)
        model_combo.pack(pady=(0, 10))
        # Block mouse wheel on combobox
        try:
            if hasattr(self.translator_gui, 'ui') and hasattr(self.translator_gui.ui, 'disable_spinbox_mousewheel'):
                self.translator_gui.ui.disable_spinbox_mousewheel(model_combo)
        except Exception:
            pass
        # Attach gentle autofill
        self._attach_model_autofill(model_combo, model_var)
        
        # Get current model from first selected item as default
        selected_indices = [self.fallback_tree.index(item) for item in selected]
        if selected_indices and selected_indices[0] < len(fallback_keys):
            current_model = fallback_keys[selected_indices[0]].get('model', '')
            model_var.set(current_model)
            model_combo.select_range(0, tk.END)  # Select all text for easy replacement
        
        def apply_change(event=None):
            new_model = model_var.get().strip()
            if new_model:
                # Update all selected fallback keys
                for item in selected:
                    index = self.fallback_tree.index(item)
                    if index < len(fallback_keys):
                        fallback_keys[index]['model'] = new_model
                
                # Save to config
                self.translator_gui.config['fallback_keys'] = fallback_keys
                self.translator_gui.save_config(show_message=False)
                
                # Reload the list
                self._load_fallback_keys()
                
                # Show status
                self._show_status(f"Changed model to '{new_model}' for {len(selected)} fallback keys")
                
                dialog.destroy()
        
        # Focus on the combobox
        model_combo.focus()
        
        # Bind Enter key to apply
        dialog.bind('<Return>', apply_change)
        model_combo.bind('<Return>', apply_change)
        dialog.bind('<Escape>', lambda e: dialog.destroy())

    def _load_fallback_keys(self):
        """Load fallback keys from config"""
        fallback_keys = self.translator_gui.config.get('fallback_keys', [])
        
        # Clear tree
        for item in self.fallback_tree.get_children():
            self.fallback_tree.delete(item)
        
        # Add keys to tree
        for key_data in fallback_keys:
            api_key = key_data.get('api_key', '')
            model = key_data.get('model', '')
            times_used = int(key_data.get('times_used', 0))
            
            # Mask API key
            masked_key = api_key[:8] + "..." + api_key[-4:] if len(api_key) > 12 else api_key
            
            # Insert into tree
            self.fallback_tree.insert('', 'end',
                                     text=masked_key,
                                     values=(model, "Not tested", times_used),
                                     tags=('untested',))
        
        # Configure tags
        self.fallback_tree.tag_configure('untested', foreground='gray')
        self.fallback_tree.tag_configure('testing', foreground='blue', font=('TkDefaultFont', 10, 'bold'))
        self.fallback_tree.tag_configure('passed', foreground='green')
        self.fallback_tree.tag_configure('failed', foreground='red')

    def _add_fallback_key(self):
        """Add a new fallback key with optional Google credentials and Azure endpoint"""
        api_key = self.fallback_key_var.get().strip()
        model = self.fallback_model_var.get().strip()
        google_credentials = self.fallback_google_creds_var.get().strip() or None
        azure_endpoint = self.fallback_azure_endpoint_var.get().strip() or None
        google_region = self.fallback_google_region_var.get().strip() or None
        azure_api_version = self.fallback_azure_api_version_var.get().strip() or None
        
        if not api_key or not model:
            messagebox.showerror("Error", "Please enter both API key and model name")
            return
        
        # Get current fallback keys
        fallback_keys = self.translator_gui.config.get('fallback_keys', [])
        
        # Add new key with additional fields
        fallback_keys.append({
            'api_key': api_key,
            'model': model,
            'google_credentials': google_credentials,
            'azure_endpoint': azure_endpoint,
            'google_region': google_region,
            'azure_api_version': azure_api_version,
            'times_used': 0
        })
        
        # Save to config
        self.translator_gui.config['fallback_keys'] = fallback_keys
        self.translator_gui.save_config(show_message=False)
        
        # Clear inputs
        self.fallback_key_var.set("")
        self.fallback_model_var.set("")
        self.fallback_google_creds_var.set("")
        self.fallback_azure_endpoint_var.set("")
        self.fallback_google_region_var.set("us-east5")
        self.fallback_azure_api_version_var.set('2025-01-01-preview')
        
        # Reload list
        self._load_fallback_keys()
        
        # Show success
        extras = []
        if google_credentials:
            extras.append(f"Google: {os.path.basename(google_credentials)}")
        if azure_endpoint:
            extras.append(f"Azure: {azure_endpoint[:30]}...")
        
        extra_info = f" ({', '.join(extras)})" if extras else ""
        self._show_status(f"Added fallback key for model: {model}{extra_info}")

    def _move_fallback_key(self, direction):
        """Move selected fallback key up or down"""
        selected = self.fallback_tree.selection()
        if not selected:
            return
        
        item = selected[0]
        index = self.fallback_tree.index(item)
        
        # Get current fallback keys
        fallback_keys = self.translator_gui.config.get('fallback_keys', [])
        
        if index >= len(fallback_keys):
            return
        
        new_index = index
        if direction == 'up' and index > 0:
            new_index = index - 1
        elif direction == 'down' and index < len(fallback_keys) - 1:
            new_index = index + 1
        
        if new_index != index:
            # Swap keys
            fallback_keys[index], fallback_keys[new_index] = fallback_keys[new_index], fallback_keys[index]
            
            # Save to config
            self.translator_gui.config['fallback_keys'] = fallback_keys
            self.translator_gui.save_config(show_message=False)
            
            # Reload list
            self._load_fallback_keys()
            
            # Reselect item
            items = self.fallback_tree.get_children()
            if new_index < len(items):
                self.fallback_tree.selection_set(items[new_index])
                self.fallback_tree.focus(items[new_index])

    def _test_selected_fallback(self):
        """Test selected fallback key"""
        selected = self.fallback_tree.selection()
        if not selected:
            messagebox.showwarning("Warning", "Please select a fallback key to test")
            return
        
        index = self.fallback_tree.index(selected[0])
        fallback_keys = self.translator_gui.config.get('fallback_keys', [])
        
        if index >= len(fallback_keys):
            return
        
        # Update UI to show testing status immediately
        items = self.fallback_tree.get_children()
        if index < len(items):
            item = items[index]
            values = list(self.fallback_tree.item(item, 'values'))
            values[1] = "⏳ Testing..."
            self.fallback_tree.item(item, values=values)
        
        key_data = fallback_keys[index]
        
        # Ensure UnifiedClient uses the same shared pool instance
        try:
            from unified_api_client import UnifiedClient
            UnifiedClient._api_key_pool = self.key_pool
        except Exception:
            pass
        # Run test in thread
        thread = threading.Thread(target=self._test_single_fallback_key, args=(key_data, index))
        thread.daemon = True
        thread.start()

    def _update_fallback_test_result(self, index, success):
        """Update fallback tree item with test result and bump times used"""
        # Increment times_used in config
        fallback_keys = self.translator_gui.config.get('fallback_keys', [])
        if index < len(fallback_keys):
            try:
                fallback_keys[index]['times_used'] = int(fallback_keys[index].get('times_used', 0)) + 1
                # Persist
                self.translator_gui.config['fallback_keys'] = fallback_keys
                self.translator_gui.save_config(show_message=False)
            except Exception:
                pass
        
        items = self.fallback_tree.get_children()
        if index < len(items):
            item = items[index]
            values = list(self.fallback_tree.item(item, 'values'))
            # Update status
            if len(values) < 3:
                values = values + [0] * (3 - len(values))
            values[1] = "βœ… Passed" if success else "❌ Failed"
            # Update times used cell
            try:
                values[2] = int(values[2]) + 1
            except Exception:
                values[2] = 1
            self.fallback_tree.item(item, values=values)

    def _test_single_fallback_key(self, key_data, index):
        """Test a single fallback key"""
        from unified_api_client import UnifiedClient
        
        api_key = key_data.get('api_key', '')
        model = key_data.get('model', '')
        
        try:
            client = UnifiedClient(
                api_key=api_key,
                model=model,
                output_dir=None
            )
            
            messages = [
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": "Say 'API test successful' and nothing else."}
            ]
            
            response = client.send(
                messages,
                temperature=0.7,
                max_tokens=100
            )
            
            if response and isinstance(response, tuple):
                content, _ = response
                if content and "test successful" in content.lower():
                    # Update tree item to show success
                    self.dialog.after(0, lambda: self._update_fallback_test_result(index, True))
                    return
        except Exception as e:
            print(f"Fallback key test failed: {e}")
        
        # Update tree item to show failure
        self.dialog.after(0, lambda: self._update_fallback_test_result(index, False))

    def _remove_selected_fallback(self):
        """Remove selected fallback key"""
        selected = self.fallback_tree.selection()
        if not selected:
            return
        
        if messagebox.askyesno("Confirm", "Remove selected fallback key?"):
            index = self.fallback_tree.index(selected[0])
            
            # Get current fallback keys
            fallback_keys = self.translator_gui.config.get('fallback_keys', [])
            
            if index < len(fallback_keys):
                del fallback_keys[index]
                
                # Save to config
                self.translator_gui.config['fallback_keys'] = fallback_keys
                self.translator_gui.save_config(show_message=False)
                
                # Reload list
                self._load_fallback_keys()
                
                self._show_status("Removed fallback key")

    def _clear_all_fallbacks(self):
        """Clear all fallback keys"""
        if not self.fallback_tree.get_children():
            return
        
        if messagebox.askyesno("Confirm", "Remove ALL fallback keys?"):
            # Clear fallback keys
            self.translator_gui.config['fallback_keys'] = []
            self.translator_gui.save_config(show_message=False)
            
            # Reload list
            self._load_fallback_keys()
            
            self._show_status("Cleared all fallback keys")

    def _toggle_fallback_section(self):
        """Enable/disable fallback section based on checkbox"""
        enabled = self.use_fallback_var.get()
        
        if enabled:
            # Show and enable all fallback widgets
            state = tk.NORMAL
            
            # Enable input widgets
            self.fallback_key_entry.config(state=state)
            self.fallback_model_combo.config(state=state)
            self.fallback_google_creds_entry.config(state=state)
            self.fallback_google_region_entry.config(state=state)
            self.fallback_azure_endpoint_entry.config(state=state)
            self.show_fallback_btn.config(state=state)
            
            # Enable add button
            for widget in self.fallback_key_entry.master.winfo_children():
                if isinstance(widget, tb.Button) and "Add Fallback" in str(widget.cget('text')):
                    widget.config(state=state)
            
            # Show the tree container
            self.fallback_tree.master.master.pack(fill=tk.BOTH, expand=True)
            
            # Show the action buttons frame
            if hasattr(self, 'fallback_action_frame'):
                self.fallback_action_frame.pack(fill=tk.X, pady=(10, 0))
            
        else:
            # Hide and disable all fallback widgets
            state = tk.DISABLED
            
            # Disable input widgets
            self.fallback_key_entry.config(state=state)
            self.fallback_model_combo.config(state=state)
            self.fallback_google_creds_entry.config(state=state)
            self.fallback_google_region_entry.config(state=state)
            self.fallback_azure_endpoint_entry.config(state=state)
            self.show_fallback_btn.config(state=state)
            
            # Disable add button
            for widget in self.fallback_key_entry.master.winfo_children():
                if isinstance(widget, tb.Button) and "Add Fallback" in str(widget.cget('text')):
                    widget.config(state=state)
            
            # Hide the tree container
            self.fallback_tree.master.master.pack_forget()
            
            # Hide the action buttons frame
            if hasattr(self, 'fallback_action_frame'):
                self.fallback_action_frame.pack_forget()
            
            # Clear selection
            self.fallback_tree.selection_remove(*self.fallback_tree.selection())

    def _toggle_fallback_visibility(self):
        """Toggle fallback key visibility"""
        if self.fallback_key_entry.cget('show') == '*':
            self.fallback_key_entry.config(show='')
            self.show_fallback_btn.config(text='πŸ”’')
        else:
            self.fallback_key_entry.config(show='*')
            self.show_fallback_btn.config(text='πŸ‘')

    def _create_button_bar(self, parent):
        """Create the bottom button bar"""
        self.button_frame = tk.Frame(parent)
        self.button_frame.pack(fill=tk.X, pady=(20, 0))
        
        # Save button
        tb.Button(self.button_frame, text="Save & Close", command=self._save_and_close,
                 bootstyle="success").pack(side=tk.RIGHT, padx=(5, 0))
        
        # Cancel button  
        tb.Button(self.button_frame, text="Cancel", command=self._on_close,
                 bootstyle="secondary").pack(side=tk.RIGHT)
        
        # Import/Export
        tb.Button(self.button_frame, text="Import", command=self._import_keys,
                 bootstyle="info-outline").pack(side=tk.LEFT, padx=(0, 5))
        
        tb.Button(self.button_frame, text="Export", command=self._export_keys,
                 bootstyle="info-outline").pack(side=tk.LEFT)
 
    def _create_key_list_section(self, parent):
        """Create the key list section with inline editing and rearrangement controls"""
        list_frame = tk.LabelFrame(parent, text="API Keys", padx=15, pady=15)
        list_frame.pack(fill=tk.BOTH, expand=True)
        
        # Add primary key indicator frame at the top
        primary_frame = tk.Frame(list_frame, bg='#FF8C00', relief=tk.RAISED, bd=2)
        primary_frame.pack(fill=tk.X, pady=(0, 10))
        
        self.primary_key_label = tk.Label(primary_frame, 
                                          text="⭐ PRIMARY KEY: Position #1 will be used first in rotation ⭐",
                                          bg='#FF8C00', fg='white', 
                                          font=('TkDefaultFont', 11, 'bold'),
                                          pady=5)
        self.primary_key_label.pack(fill=tk.X)
        
        # Main container with treeview and controls
        main_container = tk.Frame(list_frame)
        main_container.pack(fill=tk.BOTH, expand=True)
        
        # Left side: Move buttons
        move_frame = tk.Frame(main_container)
        move_frame.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 5))
        
        tk.Label(move_frame, text="Reorder", font=('TkDefaultFont', 9, 'bold')).pack(pady=(0, 5))
        
        # Move to top button
        tb.Button(move_frame, text="⬆⬆", width=3, 
                 command=lambda: self._move_key('top'),
                 bootstyle="secondary-outline").pack(pady=2)
        
        # Move up button
        tb.Button(move_frame, text="⬆", width=3,
                 command=lambda: self._move_key('up'),
                 bootstyle="secondary-outline").pack(pady=2)
        
        # Move down button
        tb.Button(move_frame, text="⬇", width=3,
                 command=lambda: self._move_key('down'),
                 bootstyle="secondary-outline").pack(pady=2)
        
        # Move to bottom button
        tb.Button(move_frame, text="⬇⬇", width=3,
                 command=lambda: self._move_key('bottom'),
                 bootstyle="secondary-outline").pack(pady=2)
        
        # Spacer
        tk.Frame(move_frame).pack(pady=10)
        
        # Position label
        self.position_label = tk.Label(move_frame, text="", font=('TkDefaultFont', 9), fg='gray')
        self.position_label.pack()
        
        # Right side: Treeview with scrollbar
        tree_frame = tk.Frame(main_container)
        tree_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        # Scrollbar
        scrollbar = ttk.Scrollbar(tree_frame, orient=tk.VERTICAL)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # Treeview
        columns = ('Model', 'Cooldown', 'Status', 'Success', 'Errors', 'Times Used')
        self.tree = ttk.Treeview(tree_frame, columns=columns, show='tree headings',
                                yscrollcommand=scrollbar.set, height=10)
        self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        scrollbar.config(command=self.tree.yview)
        
        # Configure columns with better widths and anchoring
        self.tree.heading('#0', text='API Key', anchor='w')
        self.tree.column('#0', width=180, minwidth=150, anchor='w')
        
        self.tree.heading('Model', text='Model', anchor='w')
        self.tree.column('Model', width=260, minwidth=160, anchor='w')
        
        self.tree.heading('Cooldown', text='Cooldown', anchor='center')
        self.tree.column('Cooldown', width=80, minwidth=60, anchor='center')
        
        self.tree.heading('Status', text='Status', anchor='center')
        self.tree.column('Status', width=160, minwidth=100, anchor='center')
        
        self.tree.heading('Success', text='βœ“', anchor='center')
        self.tree.column('Success', width=40, minwidth=30, anchor='center')
        
        self.tree.heading('Errors', text='βœ—', anchor='center')
        self.tree.column('Errors', width=40, minwidth=30, anchor='center')
        
        self.tree.heading('Times Used', text='Times Used', anchor='center')
        self.tree.column('Times Used', width=90, minwidth=60, anchor='center')
        
        # Configure tree style for better appearance
        style = ttk.Style()
        style.configure("Treeview.Heading", font=('TkDefaultFont', 11, 'bold'))
        
        # Bind events for inline editing
        self.tree.bind('<Button-1>', self._on_click)
        self.tree.bind('<Button-3>', self._show_context_menu)
        self.tree.bind('<<TreeviewSelect>>', self._on_selection_change)
        
        # Enable drag and drop
        self.tree.bind('<Button-1>', self._on_drag_start, add='+')
        self.tree.bind('<B1-Motion>', self._on_drag_motion)
        self.tree.bind('<ButtonRelease-1>', self._on_drag_release)
        
        # Track editing state
        self.edit_widget = None
        
        # Track drag state
        self.drag_start_item = None
        self.drag_start_y = None
        
        # Action buttons
        action_frame = tk.Frame(list_frame)
        action_frame.pack(fill=tk.X, pady=(10, 0))
        
        tb.Button(action_frame, text="Test Selected", command=self._test_selected,
                 bootstyle="warning").pack(side=tk.LEFT, padx=(0, 5))
        
        tb.Button(action_frame, text="Test All", command=self._test_all,
                 bootstyle="warning").pack(side=tk.LEFT, padx=5)
        
        tb.Button(action_frame, text="Enable Selected", command=self._enable_selected,
                 bootstyle="success").pack(side=tk.LEFT, padx=5)
        
        tb.Button(action_frame, text="Disable Selected", command=self._disable_selected,
                 bootstyle="danger").pack(side=tk.LEFT, padx=5)
        
        tb.Button(action_frame, text="Remove Selected", command=self._remove_selected,
                 bootstyle="danger").pack(side=tk.LEFT, padx=5)
        
        # Stats label
        self.stats_label = tk.Label(action_frame, text="", font=('TkDefaultFont', 11), fg='gray')
        self.stats_label.pack(side=tk.RIGHT)
 
    def _create_add_key_section(self, parent):
        """Create the add key section with Google credentials and Azure endpoint support"""
        add_frame = tk.LabelFrame(parent, text="Add New API Key", padx=15, pady=15)
        add_frame.pack(fill=tk.X, pady=(0, 10))
        
        # Grid configuration - expand for more columns
        add_frame.columnconfigure(1, weight=1)
        add_frame.columnconfigure(4, weight=1)
        # Don't give weight to column 3 to keep labels close to fields
        
        # Row 0: API Key and Model
        tk.Label(add_frame, text="API Key:").grid(row=0, column=0, sticky=tk.W, padx=(0, 10), pady=5)
        self.api_key_var = tk.StringVar()
        self.api_key_entry = tb.Entry(add_frame, textvariable=self.api_key_var, show='*')
        self.api_key_entry.grid(row=0, column=1, sticky=tk.EW, pady=5)
        
        # Toggle visibility button
        self.show_key_btn = tb.Button(add_frame, text="πŸ‘", width=3,
                                     command=self._toggle_key_visibility)
        self.show_key_btn.grid(row=0, column=2, padx=5, pady=5)
        
        # Model
        tk.Label(add_frame, text="Model:").grid(row=0, column=3, sticky=tk.W, padx=(20, 10), pady=5)
        self.model_var = tk.StringVar()
        add_models = get_model_options()
        self.model_combo = tb.Combobox(add_frame, textvariable=self.model_var, values=add_models, state='normal')
        self.model_combo.grid(row=0, column=4, sticky=tk.EW, pady=5)
        # Block mouse wheel on combobox
        try:
            if hasattr(self.translator_gui, 'ui') and hasattr(self.translator_gui.ui, 'disable_spinbox_mousewheel'):
                self.translator_gui.ui.disable_spinbox_mousewheel(self.model_combo)
        except Exception:
            pass
        # Attach gentle autofill
        self._attach_model_autofill(self.model_combo, self.model_var)
        
        # Row 1: Cooldown and optional credentials
        tk.Label(add_frame, text="Cooldown (s):").grid(row=1, column=0, sticky=tk.W, padx=(0, 10), pady=5)
        self.cooldown_var = tk.IntVar(value=60)
        cooldown_frame = tk.Frame(add_frame)
        cooldown_frame.grid(row=1, column=1, sticky=tk.W, pady=5)
        
        cooldown_spinbox = tb.Spinbox(cooldown_frame, from_=10, to=3600, textvariable=self.cooldown_var,
                  width=10)
        cooldown_spinbox.pack(side=tk.LEFT)
        # Disable mouse wheel for cooldown
        try:
            if hasattr(self.translator_gui, 'ui') and hasattr(self.translator_gui.ui, 'disable_spinbox_mousewheel'):
                self.translator_gui.ui.disable_spinbox_mousewheel(cooldown_spinbox)
        except Exception:
            pass
        tk.Label(cooldown_frame, text="(10-3600)", font=('TkDefaultFont', 9), 
                fg='gray').pack(side=tk.LEFT, padx=(10, 0))
        
        # Add button and Copy Current Key button
        button_frame = tk.Frame(add_frame)
        button_frame.grid(row=1, column=4, sticky=tk.E, pady=5)
        
        tb.Button(button_frame, text="Add Key", command=self._add_key,
                 bootstyle="success").pack(side=tk.LEFT, padx=(0, 5))
        
        tb.Button(button_frame, text="Copy Current Key", 
                 command=self._copy_current_settings,
                 bootstyle="info-outline").pack(side=tk.LEFT)
        
        # Row 2: Google Credentials (optional, discretely styled)
        tk.Label(add_frame, text="Google Creds:", font=('TkDefaultFont', 9), 
                fg='gray').grid(row=2, column=0, sticky=tk.W, padx=(0, 10), pady=2)
        self.google_creds_var = tk.StringVar()
        self.google_creds_entry = tb.Entry(add_frame, textvariable=self.google_creds_var,
                                          font=('TkDefaultFont', 8), state='normal')
        self.google_creds_entry.grid(row=2, column=1, sticky=tk.EW, pady=2)
        
        # Google credentials browse button (moved closer)
        tb.Button(add_frame, text="πŸ“", width=3, 
                 command=self._browse_google_credentials,
                 bootstyle="secondary-outline").grid(row=2, column=2, padx=(5, 0), pady=2)
        
        # Google region field
        tk.Label(add_frame, text="Region:", font=('TkDefaultFont', 11), 
                fg='gray').grid(row=2, column=3, sticky=tk.W, padx=(10, 5), pady=2)
        self.google_region_var = tk.StringVar(value='us-east5')  # Default region
        self.google_region_entry = tb.Entry(add_frame, textvariable=self.google_region_var,
                                           font=('TkDefaultFont', 8), state='normal', width=12)
        self.google_region_entry.grid(row=2, column=4, sticky=tk.W, pady=2)
        
        # Row 3: Individual Endpoint Toggle
        self.use_individual_endpoint_var = tk.BooleanVar(value=False)
        individual_endpoint_toggle = tb.Checkbutton(add_frame, text="Use Individual Endpoint", 
                                                   variable=self.use_individual_endpoint_var,
                                                   bootstyle="round-toggle",
                                                   command=self._toggle_individual_endpoint_fields)
        individual_endpoint_toggle.grid(row=3, column=0, columnspan=2, sticky=tk.W, padx=(0, 10), pady=5)
        
        # Row 4: Individual Endpoint (initially hidden)
        self.individual_endpoint_label = tk.Label(add_frame, text="Individual Endpoint:", font=('TkDefaultFont', 9), 
                                                fg='gray')
        self.individual_endpoint_label.grid(row=4, column=0, sticky=tk.W, padx=(0, 10), pady=2)
        self.azure_endpoint_var = tk.StringVar()
        self.azure_endpoint_entry = tb.Entry(add_frame, textvariable=self.azure_endpoint_var,
                                            font=('TkDefaultFont', 8), state='disabled')
        self.azure_endpoint_entry.grid(row=4, column=1, columnspan=2, sticky=tk.EW, pady=2)
        
        # Individual Endpoint API Version (small dropdown, initially hidden)
        self.individual_api_version_label = tk.Label(add_frame, text="API Ver:", font=('TkDefaultFont', 11), 
                                                    fg='gray')
        self.individual_api_version_label.grid(row=4, column=3, sticky=tk.W, padx=(10, 5), pady=2)
        self.azure_api_version_var = tk.StringVar(value='2025-01-01-preview')
        azure_versions = [
            '2025-01-01-preview',
            '2024-12-01-preview', 
            '2024-10-01-preview',
            '2024-08-01-preview',
            '2024-06-01',
            '2024-02-01',
            '2023-12-01-preview'
        ]
        self.azure_api_version_combo = ttk.Combobox(add_frame, textvariable=self.azure_api_version_var,
                                                   values=azure_versions, width=18, state='disabled',
                                                   font=('TkDefaultFont', 7))
        self.azure_api_version_combo.grid(row=4, column=4, sticky=tk.W, pady=2)
        # Block mouse wheel on version combobox
        try:
            if hasattr(self.translator_gui, 'ui') and hasattr(self.translator_gui.ui, 'disable_spinbox_mousewheel'):
                self.translator_gui.ui.disable_spinbox_mousewheel(self.azure_api_version_combo)
        except Exception:
            pass
        
        # Initially hide the endpoint fields
        self._toggle_individual_endpoint_fields()
        
        # Setup inline editor hooks to use model options as a dropdown too
        # (Optional enhancement could be added later)
        
        # Row 5: (Copy Current Key button moved up next to Add Key)
    
    def _toggle_individual_endpoint_fields(self):
        """Toggle visibility and state of individual endpoint fields"""
        enabled = self.use_individual_endpoint_var.get()
        
        if enabled:
            # Show and enable endpoint fields
            state = tk.NORMAL
            self.individual_endpoint_label.grid()
            self.azure_endpoint_entry.grid()
            self.individual_api_version_label.grid() 
            self.azure_api_version_combo.grid()
            
            self.azure_endpoint_entry.config(state=state)
            self.azure_api_version_combo.config(state='readonly')
        else:
            # Hide and disable endpoint fields
            state = tk.DISABLED
            self.individual_endpoint_label.grid_remove()
            self.azure_endpoint_entry.grid_remove()
            self.individual_api_version_label.grid_remove()
            self.azure_api_version_combo.grid_remove()
            
            # Clear the fields when disabled
            self.azure_endpoint_var.set("")
            self.azure_api_version_var.set('2025-01-01-preview')
    
    def _move_key(self, direction):
        """Move selected key in the specified direction"""
        selected = self.tree.selection()
        if not selected or len(selected) != 1:
            return
        
        item = selected[0]
        index = self.tree.index(item)
        
        if index >= len(self.key_pool.keys):
            return
        
        new_index = index
        
        if direction == 'up' and index > 0:
            new_index = index - 1
        elif direction == 'down' and index < len(self.key_pool.keys) - 1:
            new_index = index + 1
        elif direction == 'top':
            new_index = 0
        elif direction == 'bottom':
            new_index = len(self.key_pool.keys) - 1
        
        if new_index != index:
            # Swap keys in the pool
            with self.key_pool.lock:
                self.key_pool.keys[index], self.key_pool.keys[new_index] = \
                    self.key_pool.keys[new_index], self.key_pool.keys[index]
            
            # Refresh display
            self._refresh_key_list()
            
            # Reselect the moved item
            items = self.tree.get_children()
            if new_index < len(items):
                self.tree.selection_set(items[new_index])
                self.tree.focus(items[new_index])
                self.tree.see(items[new_index])
            
            # Show status
            self._show_status(f"Moved key to position {new_index + 1}")
            
    def _on_selection_change(self, event):
        """Update position label when selection changes"""
        selected = self.tree.selection()
        if selected:
            index = self.tree.index(selected[0])
            total = len(self.key_pool.keys)
            self.position_label.config(text=f"#{index + 1}/{total}")
        else:
            self.position_label.config(text="")

    def _on_drag_start(self, event):
        """Start drag operation"""
        # Check if we clicked on an item
        item = self.tree.identify_row(event.y)
        if item:
            self.drag_start_item = item
            self.drag_start_y = event.y
            # Select the item being dragged
            self.tree.selection_set(item)
            # Set cursor
            self.tree.config(cursor="hand2")

    def _on_drag_motion(self, event):
        """Handle drag motion"""
        if not self.drag_start_item:
            return
        
        # Get the item under the cursor
        target_item = self.tree.identify_row(event.y)
        
        if target_item and target_item != self.drag_start_item:
            # Visual feedback - change cursor
            self.tree.config(cursor="sb_v_double_arrow")

    def _on_drag_release(self, event):
        """Complete drag operation"""
        if not self.drag_start_item:
            return
        
        # Reset cursor
        self.tree.config(cursor="")
        
        # Get the target item
        target_item = self.tree.identify_row(event.y)
        
        if target_item and target_item != self.drag_start_item:
            # Get indices
            source_index = self.tree.index(self.drag_start_item)
            target_index = self.tree.index(target_item)
            
            # Reorder the keys in the pool
            with self.key_pool.lock:
                # Remove from source position
                key = self.key_pool.keys.pop(source_index)
                # Insert at target position
                self.key_pool.keys.insert(target_index, key)
            
            # Refresh display
            self._refresh_key_list()
            
            # Reselect the moved item
            items = self.tree.get_children()
            if target_index < len(items):
                self.tree.selection_set(items[target_index])
                self.tree.focus(items[target_index])
                self.tree.see(items[target_index])
            
            # Show status
            self._show_status(f"Moved key from position {source_index + 1} to {target_index + 1}")
        
        # Reset drag state
        self.drag_start_item = None
        self.drag_start_y = None

    def _refresh_key_list(self):
        """Refresh the key list display preserving test results and highlighting key #1"""
        # Clear tree
        for item in self.tree.get_children():
            self.tree.delete(item)
        
        # Update primary key label if it exists
        if hasattr(self, 'primary_key_label'):
            keys = self.key_pool.get_all_keys()
            if keys:
                first_key = keys[0]
                masked = first_key.api_key[:8] + "..." + first_key.api_key[-4:] if len(first_key.api_key) > 12 else first_key.api_key
                self.primary_key_label.config(text=f"⭐ PRIMARY KEY: {first_key.model} ({masked}) ⭐")
        
        # Add keys
        keys = self.key_pool.get_all_keys()
        for i, key in enumerate(keys):
            # Mask API key for display
            masked_key = key.api_key[:8] + "..." + key.api_key[-4:] if len(key.api_key) > 12 else key.api_key
            
            # Position indicator
            position = f"#{i+1}"
            if i == 0:
                position = "⭐ #1"
            
            # Determine status based on test results and current state
            if key.last_test_result is None and hasattr(key, '_testing'):
                status = "⏳ Testing..."
                tags = ('testing',)
            elif not key.enabled:
                status = "Disabled"
                tags = ('disabled',)
            elif key.last_test_result == 'passed':
                status = "βœ… Passed"
                tags = ('passed',)
            elif key.last_test_result == 'failed':
                status = "❌ Failed"
                tags = ('failed',)
            elif key.last_test_result == 'rate_limited':
                status = "⚠️ Rate Limited"
                tags = ('ratelimited',)
            elif key.last_test_result == 'error':
                status = "❌ Error"
                if key.last_test_message:
                    status += f": {key.last_test_message[:20]}..."
                tags = ('error',)
            elif key.is_cooling_down and key.last_error_time:
                remaining = int(key.cooldown - (time.time() - key.last_error_time))
                if remaining > 0:
                    status = f"Cooling ({remaining}s)"
                    tags = ('cooling',)
                else:
                    key.is_cooling_down = False
                    status = "Active"
                    tags = ('active',)
            else:
                status = "Active"
                tags = ('active',)
            
            # Times used (counter)
            times_used = getattr(key, 'times_used', key.success_count + key.error_count)
            
            # Insert into tree with position column
            self.tree.insert('', 'end', 
                           text=masked_key,
                           values=(position, key.model, f"{key.cooldown}s", status, 
                                 key.success_count, key.error_count, times_used),
                           tags=tags)
        
        # Configure tags (these may or may not work depending on ttkbootstrap theme)
        self.tree.tag_configure('active', foreground='green')
        self.tree.tag_configure('cooling', foreground='orange')
        self.tree.tag_configure('disabled', foreground='gray')
        self.tree.tag_configure('testing', foreground='blue')
        self.tree.tag_configure('passed', foreground='dark green')
        self.tree.tag_configure('failed', foreground='red')
        self.tree.tag_configure('ratelimited', foreground='orange')
        self.tree.tag_configure('error', foreground='dark red')
        
        # Update stats
        active_count = sum(1 for k in keys if k.enabled and not k.is_cooling_down)
        total_count = len(keys)
        passed_count = sum(1 for k in keys if k.last_test_result == 'passed')
        self.stats_label.config(text=f"Keys: {active_count} active / {total_count} total | {passed_count} passed tests")

    def _on_click(self, event):
        """Handle click on tree item for inline editing"""
        # Close any existing edit widget
        if self.edit_widget:
            self.edit_widget.destroy()
            self.edit_widget = None
        
        # Identify what was clicked
        region = self.tree.identify_region(event.x, event.y)
        if region != "cell":
            return
        
        item = self.tree.identify_row(event.y)
        column = self.tree.identify_column(event.x)
        
        if not item:
            return
        
        # Get column index
        col_index = int(column.replace('#', ''))
        
        # Get the key index
        index = self.tree.index(item)
        if index >= len(self.key_pool.keys):
            return
        
        key = self.key_pool.keys[index]
        
        # Only allow editing Model (column #1) and Cooldown (column #2)
        if col_index == 1:  # Model column
            self._edit_model_inline(item, column, key)
        elif col_index == 2:  # Cooldown column
            self._edit_cooldown_inline(item, column, key)

    def _edit_model_inline(self, item, column, key):
        """Create inline editor for model name"""
        # Get the bounding box of the cell
        x, y, width, height = self.tree.bbox(item, column)
        
        # Expand the width to show more text (make it wider than the column)
        expanded_width = max(width + 100, 250)  # At least 250 pixels wide
        expanded_height = height + 8  # Add some padding to the height
        
        # Create entry widget
        edit_var = tk.StringVar(value=key.model)
        self.edit_widget = tb.Entry(self.tree, textvariable=edit_var, font=('TkDefaultFont', 11))
        
        def save_edit():
            new_value = edit_var.get().strip()
            if new_value and new_value != key.model:
                key.model = new_value
                self._refresh_key_list()
                self._show_status(f"Updated model to: {new_value}")
            if self.edit_widget:
                self.edit_widget.destroy()
                self.edit_widget = None
        
        def cancel_edit(event=None):
            if self.edit_widget:
                self.edit_widget.destroy()
                self.edit_widget = None
        
        # Place and configure the entry with expanded dimensions
        # Adjust y position slightly to center it better
        self.edit_widget.place(x=x, y=y-2, width=expanded_width, height=expanded_height)
        self.edit_widget.focus()
        self.edit_widget.select_range(0, tk.END)
        
        # Make sure the widget appears on top
        self.edit_widget.lift()
        
        # Bind events
        self.edit_widget.bind('<Return>', lambda e: save_edit())
        self.edit_widget.bind('<Escape>', cancel_edit)
        self.edit_widget.bind('<FocusOut>', lambda e: save_edit())
        
        # Prevent the click from selecting the item
        return "break"

    def _edit_cooldown_inline(self, item, column, key):
        """Create inline editor for cooldown"""
        # Get the bounding box of the cell
        x, y, width, height = self.tree.bbox(item, column)
        
        # Create spinbox widget
        edit_var = tk.IntVar(value=key.cooldown)
        self.edit_widget = tb.Spinbox(self.tree, from_=10, to=3600, 
                                      textvariable=edit_var, width=10)
        # Disable mouse wheel changing values on inline editor
        try:
            if hasattr(self.translator_gui, 'ui') and hasattr(self.translator_gui.ui, 'disable_spinbox_mousewheel'):
                self.translator_gui.ui.disable_spinbox_mousewheel(self.edit_widget)
        except Exception:
            pass
        
        def save_edit():
            new_value = edit_var.get()
            if new_value != key.cooldown:
                key.cooldown = new_value
                self._refresh_key_list()
                self._show_status(f"Updated cooldown to: {new_value}s")
            if self.edit_widget:
                self.edit_widget.destroy()
                self.edit_widget = None
        
        def cancel_edit(event=None):
            if self.edit_widget:
                self.edit_widget.destroy()
                self.edit_widget = None
        
        # Place and configure the spinbox
        self.edit_widget.place(x=x, y=y, width=width, height=height)
        self.edit_widget.focus()
        
        # Bind events
        self.edit_widget.bind('<Return>', lambda e: save_edit())
        self.edit_widget.bind('<Escape>', cancel_edit)
        self.edit_widget.bind('<FocusOut>', lambda e: save_edit())
        
        # Prevent the click from selecting the item
        return "break"

    def _show_context_menu(self, event):
        """Show context menu with reorder options"""
        # Select item under cursor
        item = self.tree.identify_row(event.y)
        if item:
            # If the clicked item is not in selection, select only it
            if item not in self.tree.selection():
                self.tree.selection_set(item)
            
            # Create context menu
            menu = tk.Menu(self.dialog, tearoff=0)
            
            # Reorder submenu
            reorder_menu = tk.Menu(menu, tearoff=0)
            reorder_menu.add_command(label="Move to Top", command=lambda: self._move_key('top'))
            reorder_menu.add_command(label="Move Up", command=lambda: self._move_key('up'))
            reorder_menu.add_command(label="Move Down", command=lambda: self._move_key('down'))
            reorder_menu.add_command(label="Move to Bottom", command=lambda: self._move_key('bottom'))
            menu.add_cascade(label="Reorder", menu=reorder_menu)
            
            menu.add_separator()
            
            # Add change model option
            selected_count = len(self.tree.selection())
            if selected_count > 1:
                menu.add_command(label=f"Change Model ({selected_count} selected)", 
                               command=self._change_model_for_selected)
            else:
                menu.add_command(label="Change Model", 
                               command=self._change_model_for_selected)
            
            menu.add_separator()
            
            # Individual Endpoint options
            index = self.tree.index(item)
            if index < len(self.key_pool.keys):
                key = self.key_pool.keys[index]
                endpoint_enabled = getattr(key, 'use_individual_endpoint', False)
                endpoint_url = getattr(key, 'azure_endpoint', '')
                
                if endpoint_enabled and endpoint_url:
                    menu.add_command(label="βœ… Individual Endpoint", 
                                   command=lambda: self._configure_individual_endpoint(index))
                    menu.add_command(label="Disable Individual Endpoint", 
                                   command=lambda: self._toggle_individual_endpoint(index, False))
                else:
                    menu.add_command(label="πŸ”§ Configure Individual Endpoint", 
                                   command=lambda: self._configure_individual_endpoint(index))
            
            menu.add_separator()
            menu.add_command(label="Test", command=self._test_selected)
            menu.add_command(label="Enable", command=self._enable_selected)
            menu.add_command(label="Disable", command=self._disable_selected)
            menu.add_separator()
            menu.add_command(label="Remove", command=self._remove_selected)
            
            # Show menu
            menu.post(event.x_root, event.y_root)

    def _change_model_for_selected(self):
        """Change model for all selected entries"""
        selected = self.tree.selection()
        if not selected:
            return
        
        # Create simple dialog
        dialog = tk.Toplevel(self.dialog)
        dialog.title(f"Change Model for {len(selected)} Keys")
        dialog.geometry("400x130")
        dialog.transient(self.dialog)
        # Set icon
        self._set_icon(dialog)
        
        # Center the dialog
        dialog.update_idletasks()
        x = (dialog.winfo_screenwidth() // 2) - (dialog.winfo_width() // 2)
        y = (dialog.winfo_screenheight() // 2) - (dialog.winfo_height() // 2)
        dialog.geometry(f"+{x}+{y}")
        
        # Main frame
        main_frame = tk.Frame(dialog, padx=20, pady=20)
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # Label
        tk.Label(main_frame, text="Enter new model name (press Enter to apply):",
                font=('TkDefaultFont', 10)).pack(pady=(0, 10))
        
        # Model entry with dropdown
        model_var = tk.StringVar()
        
        # Full model list (same as main GUI)
        all_models = get_model_options()
        
        model_combo = ttk.Combobox(main_frame, values=all_models, 
                                   textvariable=model_var, width=45, height=12)
        model_combo.pack(pady=(0, 10))
        
        # Block mouse wheel on combobox
        try:
            if hasattr(self.translator_gui, 'ui') and hasattr(self.translator_gui.ui, 'disable_spinbox_mousewheel'):
                self.translator_gui.ui.disable_spinbox_mousewheel(model_combo)
        except Exception:
            pass
        
        # Attach gentle autofill
        self._attach_model_autofill(model_combo, model_var)
        # Get current model from first selected item as default
        selected_indices = [self.tree.index(item) for item in selected]
        if selected_indices and selected_indices[0] < len(self.key_pool.keys):
            current_model = self.key_pool.keys[selected_indices[0]].model
            model_var.set(current_model)
            model_combo.select_range(0, tk.END)  # Select all text for easy replacement
        
        def apply_change(event=None):
            new_model = model_var.get().strip()
            if new_model:
                # Update all selected keys
                for item in selected:
                    index = self.tree.index(item)
                    if index < len(self.key_pool.keys):
                        self.key_pool.keys[index].model = new_model
                
                # Refresh the display
                self._refresh_key_list()
                
                # Show status
                self._show_status(f"Changed model to '{new_model}' for {len(selected)} keys")
                
                dialog.destroy()
        
        # Focus on the combobox
        model_combo.focus()
        
        # Bind Enter key to apply
        dialog.bind('<Return>', apply_change)
        model_combo.bind('<Return>', apply_change)
        dialog.bind('<Escape>', lambda e: dialog.destroy())
    
    def _configure_individual_endpoint(self, key_index):
        """Configure individual endpoint for a specific key"""
        if key_index >= len(self.key_pool.keys):
            return
        
        key = self.key_pool.keys[key_index]
        
        # Create individual endpoint dialog using the class
        if IndividualEndpointDialog is None:
            messagebox.showerror("Error", "IndividualEndpointDialog is not available.")
            return
        IndividualEndpointDialog(self.dialog, self.translator_gui, key, self._refresh_key_list, self._show_status)
    
    def _toggle_endpoint_fields(self, enable_var, endpoint_entry, version_combo):
        """Toggle endpoint configuration fields based on enable state"""
        if enable_var.get():
            endpoint_entry.config(state='normal')
            version_combo.config(state='readonly')
        else:
            endpoint_entry.config(state='disabled')
            version_combo.config(state='disabled')
    
    def _toggle_individual_endpoint(self, key_index, enabled):
        """Quick toggle individual endpoint on/off"""
        if key_index >= len(self.key_pool.keys):
            return
        
        key = self.key_pool.keys[key_index]
        key.use_individual_endpoint = enabled
        
        # Refresh display
        self._refresh_key_list()
        
        # Show status
        status = "enabled" if enabled else "disabled"
        self._show_status(f"Individual endpoint {status} for {key.model}")

    # Additional helper method to swap keys programmatically
    def swap_keys(self, index1: int, index2: int):
        """Swap two keys by their indices"""
        with self.key_pool.lock:
            if 0 <= index1 < len(self.key_pool.keys) and 0 <= index2 < len(self.key_pool.keys):
                self.key_pool.keys[index1], self.key_pool.keys[index2] = \
                    self.key_pool.keys[index2], self.key_pool.keys[index1]
                self._refresh_key_list()
                return True
        return False

    # Method to move a key to a specific position
    def move_key_to_position(self, from_index: int, to_index: int):
        """Move a key from one position to another"""
        with self.key_pool.lock:
            if 0 <= from_index < len(self.key_pool.keys) and 0 <= to_index < len(self.key_pool.keys):
                key = self.key_pool.keys.pop(from_index)
                self.key_pool.keys.insert(to_index, key)
                self._refresh_key_list()
                return True
        return False
    
    def _create_button_bar(self, parent):
        """Create the bottom button bar"""
        button_frame = tk.Frame(parent)
        button_frame.pack(fill=tk.X, pady=(20, 0))
        
        # Save button
        tb.Button(button_frame, text="Save & Close", command=self._save_and_close,
                 bootstyle="success").pack(side=tk.RIGHT, padx=(5, 0))
        
        # Cancel button  
        tb.Button(button_frame, text="Cancel", command=self._on_close,
                 bootstyle="secondary").pack(side=tk.RIGHT)
        
        # Import/Export
        tb.Button(button_frame, text="Import", command=self._import_keys,
                 bootstyle="info-outline").pack(side=tk.LEFT, padx=(0, 5))
        
        tb.Button(button_frame, text="Export", command=self._export_keys,
                 bootstyle="info-outline").pack(side=tk.LEFT)
    
    def _browse_google_credentials(self):
        """Browse for Google Cloud credentials JSON file"""
        filename = filedialog.askopenfilename(
            title="Select Google Cloud Credentials JSON",
            filetypes=[("JSON files", "*.json"), ("All files", "*.*")]
        )
        
        if filename:
            try:
                # Validate it's a valid Google Cloud credentials file
                with open(filename, 'r') as f:
                    creds_data = json.load(f)
                    if 'type' in creds_data and 'project_id' in creds_data:
                        self.google_creds_var.set(filename)
                        self._show_status(f"Selected Google credentials: {os.path.basename(filename)}")
                    else:
                        messagebox.showerror(
                            "Error", 
                            "Invalid Google Cloud credentials file. Please select a valid service account JSON file."
                        )
            except Exception as e:
                messagebox.showerror("Error", f"Failed to load credentials: {str(e)}")
    
    def _browse_fallback_google_credentials(self):
        """Browse for Google Cloud credentials JSON file for fallback keys"""
        filename = filedialog.askopenfilename(
            title="Select Google Cloud Credentials JSON for Fallback",
            filetypes=[("JSON files", "*.json"), ("All files", "*.*")]
        )
        
        if filename:
            try:
                # Validate it's a valid Google Cloud credentials file
                with open(filename, 'r') as f:
                    creds_data = json.load(f)
                    if 'type' in creds_data and 'project_id' in creds_data:
                        self.fallback_google_creds_var.set(filename)
                        self._show_status(f"Selected fallback Google credentials: {os.path.basename(filename)}")
                    else:
                        messagebox.showerror(
                            "Error", 
                            "Invalid Google Cloud credentials file. Please select a valid service account JSON file."
                        )
            except Exception as e:
                messagebox.showerror("Error", f"Failed to load credentials: {str(e)}")
    
    def _attach_model_autofill(self, combo: ttk.Combobox, var: tk.StringVar, on_change=None):
        """Attach the same gentle autofill/scroll behavior as the main GUI.

        - No filtering; keeps full list intact.

        - Gentle autofill only when appending at end; Backspace/Delete respected.

        - Scroll/highlight match if dropdown is open.

        """
        import tkinter as _tk
        import logging as _logging

        # Store full values list on the widget
        try:
            combo._all_values = list(combo['values'])
        except Exception:
            combo._all_values = []
        combo._prev_text = var.get() if var else combo.get()

        def _scroll_to_value(_combo: ttk.Combobox, value: str):
            try:
                values = getattr(_combo, '_all_values', []) or list(_combo['values'])
                if value not in values:
                    return
                index = values.index(value)
                popdown = _combo.tk.eval(f'ttk::combobox::PopdownWindow {_combo._w}')
                listbox = f'{popdown}.f.l'
                tkobj = _combo.tk
                tkobj.call(listbox, 'see', index)
                tkobj.call(listbox, 'selection', 'clear', 0, 'end')
                tkobj.call(listbox, 'selection', 'set', index)
                tkobj.call(listbox, 'activate', index)
            except Exception:
                pass

        def _on_keyrelease(event=None):
            try:
                typed = combo.get()
                prev = getattr(combo, '_prev_text', '')
                keysym = (getattr(event, 'keysym', '') or '').lower()

                if keysym in {'up', 'down', 'left', 'right', 'return', 'escape', 'tab'}:
                    return

                source = getattr(combo, '_all_values', []) or list(combo['values'])

                first_match = None
                if typed:
                    lowered = typed.lower()
                    pref = [v for v in source if v.lower().startswith(lowered)]
                    cont = [v for v in source if lowered in v.lower()] if not pref else []
                    if pref:
                        first_match = pref[0]
                    elif cont:
                        first_match = cont[0]

                grew = len(typed) > len(prev) and typed.startswith(prev)
                is_del = keysym in {'backspace', 'delete'} or len(typed) < len(prev)
                try:
                    at_end = combo.index(_tk.INSERT) == len(typed)
                except Exception:
                    at_end = True
                try:
                    has_sel = combo.selection_present()
                except Exception:
                    has_sel = False

                # Gentle autofill
                if first_match and grew and at_end and not has_sel and not is_del:
                    if first_match.lower().startswith(typed.lower()) and first_match != typed:
                        combo.set(first_match)
                        try:
                            combo.icursor(len(typed))
                            combo.selection_range(len(typed), len(first_match))
                        except Exception:
                            pass

                # If dropdown is open, scroll/highlight (no auto-open)
                if first_match:
                    _scroll_to_value(combo, first_match)

                combo._prev_text = typed
                if on_change and typed != prev:
                    on_change()
            except Exception as e:
                try:
                    _logging.debug(f"Combobox autocomplete error: {e}")
                except Exception:
                    pass

        combo.bind('<KeyRelease>', _on_keyrelease)
        
        def _on_return(event=None):
            try:
                typed = combo.get()
                source = getattr(combo, '_all_values', []) or list(combo['values'])
                match = None
                if typed:
                    lowered = typed.lower()
                    pref = [v for v in source if v.lower().startswith(lowered)]
                    cont = [v for v in source if lowered in v.lower()] if not pref else []
                    match = pref[0] if pref else (cont[0] if cont else None)
                if match and match != typed:
                    combo.set(match)
                # Place caret at end and clear selection
                try:
                    combo.icursor('end')
                    try:
                        combo.selection_clear()
                    except Exception:
                        combo.selection_range(0, 0)
                except Exception:
                    pass
                combo._prev_text = combo.get()
                if on_change:
                    on_change()
            except Exception as e:
                try:
                    _logging.debug(f"Combobox enter-commit error: {e}")
                except Exception:
                    pass
            # Do not return "break" so outer dialogs bound to <Return> still fire
            return None

        combo.bind('<Return>', _on_return)
        combo.bind('<<ComboboxSelected>>', lambda e: on_change() if on_change else None)
        combo.bind('<FocusOut>', lambda e: on_change() if on_change else None)

    def _toggle_key_visibility(self):
        """Toggle API key visibility"""
        if self.api_key_entry.cget('show') == '*':
            self.api_key_entry.config(show='')
            self.show_key_btn.config(text='πŸ”’')
        else:
            self.api_key_entry.config(show='*')
            self.show_key_btn.config(text='πŸ‘')
    
    def _toggle_multi_key_mode(self):
        """Toggle multi-key mode"""
        enabled = self.enabled_var.get()
        self.translator_gui.config['use_multi_api_keys'] = enabled
        
        # Save the config immediately
        self.translator_gui.save_config(show_message=False)
        
        # Fallback section is always visible now (works in both modes)
        # No need to show/hide fallback section based on multi-key mode
        
        # Update other UI elements
        for widget in [self.api_key_entry, self.model_combo]:
            if widget:
                widget.config(state=tk.NORMAL if enabled else tk.DISABLED)
        
        # Handle Treeview separately - it doesn't support state property
        if self.tree:
            if enabled:
                # Re-enable tree interactions by restoring original bindings
                self.tree.bind('<Button-1>', self._on_click)
                self.tree.bind('<Button-3>', self._show_context_menu)
                self.tree.bind('<<TreeviewSelect>>', self._on_selection_change)
                
                # Re-enable drag and drop
                self.tree.bind('<Button-1>', self._on_drag_start, add='+')
                self.tree.bind('<B1-Motion>', self._on_drag_motion)
                self.tree.bind('<ButtonRelease-1>', self._on_drag_release)
            else:
                # Disable tree interactions
                self.tree.unbind('<Button-1>')
                self.tree.unbind('<Button-3>')
                self.tree.unbind('<<TreeviewSelect>>')
                self.tree.unbind('<B1-Motion>')
                self.tree.unbind('<ButtonRelease-1>')
        
        # Update action buttons state
        for child in self.dialog.winfo_children():
            if isinstance(child, tk.Frame):
                for subchild in child.winfo_children():
                    if isinstance(subchild, tk.Frame):
                        for button in subchild.winfo_children():
                            if isinstance(button, (tb.Button, ttk.Button)) and button.cget('text') in [
                                'Test Selected', 'Test All', 'Enable Selected', 
                                'Disable Selected', 'Remove Selected', 'Add Key'
                            ]:
                                button.config(state=tk.NORMAL if enabled else tk.DISABLED)
    
    def _copy_current_settings(self):
        """Copy current API key and model from main GUI"""
        if hasattr(self.translator_gui, 'api_key_var'):
            self.api_key_var.set(self.translator_gui.api_key_var.get())
        if hasattr(self.translator_gui, 'model_var'):
            self.model_var.set(self.translator_gui.model_var.get())
    
    def _add_key(self):
        """Add a new API key with optional Google credentials and individual endpoint"""
        api_key = self.api_key_var.get().strip()
        model = self.model_var.get().strip()
        cooldown = self.cooldown_var.get()
        google_credentials = self.google_creds_var.get().strip() or None
        google_region = self.google_region_var.get().strip() or None
        
        # Only use individual endpoint if toggle is enabled
        use_individual_endpoint = self.use_individual_endpoint_var.get()
        azure_endpoint = self.azure_endpoint_var.get().strip() if use_individual_endpoint else None
        azure_api_version = self.azure_api_version_var.get().strip() if use_individual_endpoint else None
        
        if not api_key or not model:
            messagebox.showerror("Error", "Please enter both API key and model name")
            return
        
        # Add to pool with new fields
        key_entry = APIKeyEntry(api_key, model, cooldown, enabled=True, 
                               google_credentials=google_credentials, 
                               azure_endpoint=azure_endpoint,
                               google_region=google_region,
                               azure_api_version=azure_api_version,
                               use_individual_endpoint=use_individual_endpoint)
        self.key_pool.add_key(key_entry)
        
        # Clear inputs
        self.api_key_var.set("")
        self.model_var.set("")
        self.cooldown_var.set(60)
        self.google_creds_var.set("")
        self.azure_endpoint_var.set("")
        self.google_region_var.set("us-east5")
        self.azure_api_version_var.set('2025-01-01-preview')
        self.use_individual_endpoint_var.set(False)
        # Update the UI to hide endpoint fields
        self._toggle_individual_endpoint_fields()
        
        # Refresh list
        self._refresh_key_list()
        
        # Show success
        extras = []
        if google_credentials:
            extras.append(f"Google: {os.path.basename(google_credentials)}")
        if azure_endpoint:
            extras.append(f"Azure: {azure_endpoint[:30]}...")
        
        extra_info = f" ({', '.join(extras)})" if extras else ""
        self._show_status(f"Added key for model: {model}{extra_info}")
    
    def _refresh_key_list(self):
        """Refresh the key list display"""
        # Clear tree
        for item in self.tree.get_children():
            self.tree.delete(item)
        
        # Add keys
        keys = self.key_pool.get_all_keys()
        for i, key in enumerate(keys):
            # Mask API key for display
            masked_key = key.api_key[:8] + "..." + key.api_key[-4:] if len(key.api_key) > 12 else key.api_key
            
            # Status
            if not key.enabled:
                status = "Disabled"
                tags = ('disabled',)
            elif key.is_cooling_down:
                remaining = int(key.cooldown - (time.time() - key.last_error_time))
                status = f"Cooling ({remaining}s)"
                tags = ('cooling',)
            else:
                status = "Active"
                tags = ('active',)
            
            # Times used (counter)
            times_used = getattr(key, 'times_used', key.success_count + key.error_count)
            
            # Insert into tree
            self.tree.insert('', 'end', 
                           text=masked_key,
                           values=(key.model, f"{key.cooldown}s", status, 
                                 key.success_count, key.error_count, times_used),
                           tags=tags)
        
        # Configure tags
        self.tree.tag_configure('active', foreground='green')
        self.tree.tag_configure('cooling', foreground='orange')
        self.tree.tag_configure('disabled', foreground='gray')
        
        # Update stats
        active_count = sum(1 for k in keys if k.enabled and not k.is_cooling_down)
        total_count = len(keys)
        self.stats_label.config(text=f"Keys: {active_count} active / {total_count} total")
    
    
    def _test_selected(self):
        """Test selected API keys with inline progress"""
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("Warning", "Please select keys to test")
            return
        
        # Get selected indices
        indices = [self.tree.index(item) for item in selected]
        
        # Ensure UnifiedClient uses the same shared pool instance
        try:
            from unified_api_client import UnifiedClient
            UnifiedClient._api_key_pool = self.key_pool
        except Exception:
            pass
        # Start testing in thread
        thread = threading.Thread(target=self._run_inline_tests, args=(indices,))
        thread.daemon = True
        thread.start()

    def _test_all(self):
        """Test all API keys with inline progress"""
        if not self.key_pool.keys:
            messagebox.showwarning("Warning", "No keys to test")
            return
        
        indices = list(range(len(self.key_pool.keys)))
        
        # Start testing in thread
        thread = threading.Thread(target=self._run_inline_tests, args=(indices,))
        thread.daemon = True
        thread.start()

    def _run_inline_tests(self, indices: List[int]):
        """Run API tests with persistent inline results"""
        from concurrent.futures import ThreadPoolExecutor, as_completed
        import os
        
        print(f"[DEBUG] Starting tests for {len(indices)} keys")
        
        # Mark all selected keys as testing
        for index in indices:
            if index < len(self.key_pool.keys):
                key = self.key_pool.keys[index]
                key.last_test_result = None
                key._testing = True
                print(f"[DEBUG] Marked key {index} as testing")
        
        # Refresh once to show "Testing..." status
        self.dialog.after(0, self._refresh_key_list)
        
        # Create thread pool for parallel testing
        max_workers = min(10, len(indices))
        
        def test_single_key(index):
            """Test a single API key directly"""
            print(f"[DEBUG] Testing key at index {index}")
            
            if index >= len(self.key_pool.keys):
                return None
                
            key = self.key_pool.keys[index]
            
            try:
                # Simple test - just check if we can import the libraries
                # This is a minimal test to see if the function completes
                print(f"[DEBUG] Testing {key.model} with key {key.api_key[:8]}...")
                
                # Simulate a test
                import time
                time.sleep(1)  # Simulate API call
                
                # For now, just mark as passed to test the flow
                key.mark_success()
                key.set_test_result('passed', 'Test successful')
                print(f"[DEBUG] Key {index} test completed - PASSED")
                time.sleep(0.5)  # Brief pause to improve retry responsiveness
                logger.debug("πŸ’€ Pausing briefly to improve retry responsiveness after test completion")
                return (index, True, "Test passed")
                
            except Exception as e:
                print(f"[DEBUG] Key {index} test failed: {e}")
                key.mark_error()
                key.set_test_result('error', str(e)[:30])
                return (index, False, f"Error: {str(e)[:50]}...")
        
        # Run tests in parallel
        results = []
        with ThreadPoolExecutor(max_workers=max_workers) as executor:
            # Submit all test tasks
            future_to_index = {executor.submit(test_single_key, i): i for i in indices}
            
            # Process results as they complete
            for future in as_completed(future_to_index):
                result = future.result()
                if result:
                    results.append(result)
                    print(f"[DEBUG] Got result: {result}")
        
        print(f"[DEBUG] All tests complete. Results: {len(results)}")
        
        # Calculate summary
        success_count = sum(1 for _, success, _ in results if success)
        total_count = len(results)
        
        # Clear testing flags
        for index in indices:
            if index < len(self.key_pool.keys):
                key = self.key_pool.keys[index]
                if hasattr(key, '_testing'):
                    delattr(key, '_testing')
                    print(f"[DEBUG] Cleared testing flag for key {index}")
        
        # Update UI in main thread
        print(f"[DEBUG] Refreshing UI with results")
        self.dialog.after(0, self._refresh_key_list)
        self.dialog.after(0, lambda: self.stats_label.config(
            text=f"Test complete: {success_count}/{total_count} passed"))
        


    def _update_tree_item(self, index: int):
        """Update a single tree item based on current key state"""
        def update():
            # Find the tree item for this index
            items = self.tree.get_children()
            if index < len(items):
                item = items[index]
                key = self.key_pool.keys[index]
                
                # Determine status and tags
                if key.last_test_result is None:
                    # Currently testing
                    status = "⏳ Testing..."
                    tags = ('testing',)
                elif not key.enabled:
                    status = "Disabled"
                    tags = ('disabled',)
                elif key.last_test_result == 'passed':
                    if key.is_cooling_down:
                        remaining = int(key.cooldown - (time.time() - key.last_error_time))
                        status = f"βœ… Passed (cooling {remaining}s)"
                        tags = ('passed_cooling',)
                    else:
                        status = "βœ… Passed"
                        tags = ('passed',)
                elif key.last_test_result == 'failed':
                    status = "❌ Failed"
                    tags = ('failed',)
                elif key.last_test_result == 'rate_limited':
                    remaining = int(key.cooldown - (time.time() - key.last_error_time))
                    status = f"⚠️ Rate Limited ({remaining}s)"
                    tags = ('ratelimited',)
                elif key.last_test_result == 'error':
                    status = "❌ Error"
                    if key.last_test_message:
                        status += f": {key.last_test_message[:20]}..."
                    tags = ('error',)
                elif key.is_cooling_down:
                    remaining = int(key.cooldown - (time.time() - key.last_error_time))
                    status = f"Cooling ({remaining}s)"
                    tags = ('cooling',)
                else:
                    status = "Active"
                    tags = ('active',)
                
                # Get current values
                values = list(self.tree.item(item, 'values'))
                
                # Update status column
                values[2] = status
                
                # Update success/error counts
                values[3] = key.success_count
                values[4] = key.error_count
                
                # Update times used (counter)
                values[5] = getattr(key, 'times_used', key.success_count + key.error_count)
                
                # Update the item
                self.tree.item(item, values=values, tags=tags)
        
        # Run in main thread
        self.dialog.after(0, update)

    def _refresh_key_list(self):
        """Refresh the key list display preserving test results"""
        # Clear tree
        for item in self.tree.get_children():
            self.tree.delete(item)
        
        # Add keys
        keys = self.key_pool.get_all_keys()
        for i, key in enumerate(keys):
            # Mask API key for display
            masked_key = key.api_key[:8] + "..." + key.api_key[-4:] if len(key.api_key) > 12 else key.api_key
            
            # Determine status based on test results and current state
            if key.last_test_result is None and hasattr(key, '_testing'):
                # Currently testing (temporary flag)
                status = "⏳ Testing..."
                tags = ('testing',)
            elif not key.enabled:
                status = "Disabled"
                tags = ('disabled',)
            elif key.last_test_result == 'passed':
                status = "βœ… Passed"
                tags = ('passed',)
            elif key.last_test_result == 'failed':
                status = "❌ Failed"
                tags = ('failed',)
            elif key.last_test_result == 'rate_limited':
                status = "⚠️ Rate Limited"
                tags = ('ratelimited',)
            elif key.last_test_result == 'error':
                status = "❌ Error"
                if key.last_test_message:
                    status += f": {key.last_test_message[:20]}..."
                tags = ('error',)
            elif key.is_cooling_down and key.last_error_time:
                remaining = int(key.cooldown - (time.time() - key.last_error_time))
                if remaining > 0:
                    status = f"Cooling ({remaining}s)"
                    tags = ('cooling',)
                else:
                    key.is_cooling_down = False
                    status = "Active"
                    tags = ('active',)
            else:
                status = "Active"
                tags = ('active',)
            
            # Times used (counter)
            times_used = getattr(key, 'times_used', key.success_count + key.error_count)
            
            # Insert into tree
            self.tree.insert('', 'end', 
                           text=masked_key,
                           values=(key.model, f"{key.cooldown}s", status, 
                                 key.success_count, key.error_count, times_used),
                           tags=tags)
        
        # Configure tags
        self.tree.tag_configure('active', foreground='green')
        self.tree.tag_configure('cooling', foreground='orange')
        self.tree.tag_configure('disabled', foreground='gray')
        self.tree.tag_configure('testing', foreground='blue', font=('TkDefaultFont', 11))
        self.tree.tag_configure('passed', foreground='dark green', font=('TkDefaultFont', 11))
        self.tree.tag_configure('failed', foreground='red')
        self.tree.tag_configure('ratelimited', foreground='orange')
        self.tree.tag_configure('error', foreground='dark red')
        
        # Update stats
        active_count = sum(1 for k in keys if k.enabled and not k.is_cooling_down)
        total_count = len(keys)
        passed_count = sum(1 for k in keys if k.last_test_result == 'passed')
        self.stats_label.config(text=f"Keys: {active_count} active / {total_count} total | {passed_count} passed tests")
    
    def _create_progress_dialog(self):
        """Create simple progress dialog at mouse cursor position"""
        self.progress_dialog = tk.Toplevel(self.dialog)
        self.progress_dialog.title("Testing API Keys")
        
        # Get mouse position
        x = self.progress_dialog.winfo_pointerx()
        y = self.progress_dialog.winfo_pointery()
        
        # Set geometry at cursor position (offset slightly so cursor is inside window)
        self.progress_dialog.geometry(f"500x400+{x-50}+{y-30}")
        
        # Add label
        label = tb.Label(self.progress_dialog, text="Testing in progress...", 
                        font=('TkDefaultFont', 10, 'bold'))
        label.pack(pady=10)
        
        # Add text widget for results
        self.progress_text = scrolledtext.ScrolledText(self.progress_dialog, 
                                                      wrap=tk.WORD, width=60, height=20)
        self.progress_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0, 10))
        
        # Add close button (initially disabled)
        self.close_button = tb.Button(self.progress_dialog, text="Close", 
                                     command=self.progress_dialog.destroy,
                                     bootstyle="secondary", state=tk.DISABLED)
        self.close_button.pack(pady=(0, 10))
        
        self.progress_dialog.transient(self.dialog)

    def _run_tests(self, indices: List[int]):
        """Run API tests for specified keys in parallel"""
        from unified_api_client import UnifiedClient
        from concurrent.futures import ThreadPoolExecutor, as_completed
        import os
        
        # Get Gemini endpoint settings
        use_gemini_endpoint = os.getenv("USE_GEMINI_OPENAI_ENDPOINT", "0") == "1"
        gemini_endpoint = os.getenv("GEMINI_OPENAI_ENDPOINT", "")
        
        # Create thread pool for parallel testing
        max_workers = min(10, len(indices))  # Limit to 10 concurrent tests
        
        def test_single_key(index):
            """Test a single API key"""
            if index >= len(self.key_pool.keys):
                return None
                
            key = self.key_pool.keys[index]
            
            # Create a key identifier
            key_preview = f"{key.api_key[:8]}...{key.api_key[-4:]}" if len(key.api_key) > 12 else key.api_key
            test_label = f"{key.model} [{key_preview}]"
            
            # Update UI to show test started
            self.dialog.after(0, lambda label=test_label: self.progress_text.insert(tk.END, f"Testing {label}... "))
            self.dialog.after(0, lambda: self.progress_text.see(tk.END))
            
            try:
                # Count this usage for times used in testing as well
                try:
                    key.times_used += 1
                except Exception:
                    pass
                
                # Check if this is a Gemini model with custom endpoint
                is_gemini_model = key.model.lower().startswith('gemini')
                
                if is_gemini_model and use_gemini_endpoint and gemini_endpoint:
                    # Test Gemini with OpenAI-compatible endpoint
                    import openai
                    
                    endpoint_url = gemini_endpoint
                    if not endpoint_url.endswith('/openai/'):
                        endpoint_url = endpoint_url.rstrip('/') + '/openai/'
                    
                    client = openai.OpenAI(
                        api_key=key.api_key,
                        base_url=endpoint_url,
                        timeout=10.0
                    )
                    
                    response = client.chat.completions.create(
                        model=key.model.replace('gemini/', ''),
                        messages=[
                            {"role": "system", "content": "You are a helpful assistant."},
                            {"role": "user", "content": "Say 'API test successful' and nothing else."}
                        ],
                        max_tokens=100,
                        temperature=0.7
                    )
                    
                    content = response.choices[0].message.content
                    if content and "test successful" in content.lower():
                        self.dialog.after(0, lambda label=test_label: self._update_test_result(label, True))
                        key.mark_success()
                        return (index, True, "Test passed")
                    else:
                        self.dialog.after(0, lambda label=test_label: self._update_test_result(label, False))
                        key.mark_error()
                        return (index, False, "Unexpected response")
                else:
                    # Use UnifiedClient for non-Gemini or regular Gemini
                    client = UnifiedClient(
                        api_key=key.api_key,
                        model=key.model,
                        output_dir=None
                    )
                    
                    messages = [
                        {"role": "system", "content": "You are a helpful assistant."},
                        {"role": "user", "content": "Say 'API test successful' and nothing else."}
                    ]
                    
                    response = client.send(
                        messages,
                        temperature=0.7,
                        max_tokens=100
                    )
                    
                    if response and isinstance(response, tuple):
                        content, finish_reason = response
                        if content and "test successful" in content.lower():
                            self.dialog.after(0, lambda label=test_label: self._update_test_result(label, True))
                            key.mark_success()
                            return (index, True, "Test passed")
                        else:
                            self.dialog.after(0, lambda label=test_label: self._update_test_result(label, False))
                            key.mark_error()
                            return (index, False, "Unexpected response")
                    else:
                        self.dialog.after(0, lambda label=test_label: self._update_test_result(label, False))
                        key.mark_error()
                        return (index, False, "No response")
                        
            except Exception as e:
                error_msg = str(e)
                error_code = None
                
                if "429" in error_msg or "rate limit" in error_msg.lower():
                    error_code = 429
                    
                self.dialog.after(0, lambda label=test_label: self._update_test_result(label, False, error=True))
                key.mark_error(error_code)
                return (index, False, f"Error: {error_msg}")
        
        # Run tests in parallel
        with ThreadPoolExecutor(max_workers=max_workers) as executor:
            # Submit all test tasks
            future_to_index = {executor.submit(test_single_key, i): i for i in indices}
            
            # Process results as they complete
            for future in as_completed(future_to_index):
                result = future.result()
                if result:
                    self.test_results.put(result)
        
        # Show completion and close button
        self.dialog.after(0, self._show_completion)
        
        # Process final results
        self.dialog.after(0, self._process_test_results)

    def _update_test_result(self, test_label, success, error=False):
        """Update the progress text with test result"""
        # Find the line with this test label
        content = self.progress_text.get("1.0", tk.END)
        lines = content.split('\n')
        
        for i, line in enumerate(lines):
            if test_label in line and not any(status in line for status in ["βœ…", "❌"]):
                # This is our line, update it
                if error:
                    result_text = "❌ ERROR"
                elif success:
                    result_text = "βœ… PASSED"
                else:
                    result_text = "❌ FAILED"
                
                # Calculate position
                line_num = i + 1
                line_end = f"{line_num}.end"
                
                self.progress_text.insert(line_end, result_text)
                self.progress_text.insert(line_end, "\n")
                self.progress_text.see(tk.END)
                break

    def _show_completion(self):
        """Show completion in the same dialog"""
        self.progress_text.insert(tk.END, "\n--- Testing Complete ---\n")
        self.progress_text.see(tk.END)
        
    def _process_test_results(self):
        """Process test results and show in the same dialog"""
        results = []
        
        # Get all results
        while not self.test_results.empty():
            try:
                results.append(self.test_results.get_nowait())
            except:
                break
        
        if results:
            # Build result message
            success_count = sum(1 for _, success, _ in results if success)
            total_count = len(results)
            
            # Update everything at once after all tests complete
            def final_update():
                # Clear testing flags
                for index in indices:
                    if index < len(self.key_pool.keys):
                        key = self.key_pool.keys[index]
                        if hasattr(key, '_testing'):
                            delattr(key, '_testing')
                
                self._refresh_key_list()
                self.stats_label.config(text=f"Test complete: {success_count}/{total_count} passed")

            # Use lambda to capture the variables in scope
            self.dialog.after(0, lambda: final_update())
            
            # Add summary to the same dialog
            self.progress_text.insert(tk.END, f"\nSummary: {success_count}/{total_count} passed\n")
            self.progress_text.insert(tk.END, "-" * 50 + "\n\n")
            
            for i, success, msg in results:
                key = self.key_pool.keys[i]
                # Show key identifier in results too
                key_preview = f"{key.api_key[:8]}...{key.api_key[-4:]}" if len(key.api_key) > 12 else key.api_key
                status = "βœ…" if success else "❌"
                self.progress_text.insert(tk.END, f"{status} {key.model} [{key_preview}]: {msg}\n")
            
            self.progress_text.see(tk.END)
            
            # Enable close button now that testing is complete
            self.close_button.config(state=tk.NORMAL)
            
            # Update the dialog title
            self.progress_dialog.title(f"API Test Results - {success_count}/{total_count} passed")
            
            # Refresh list
            self._refresh_key_list()
    
    def _enable_selected(self):
        """Enable selected keys"""
        selected = self.tree.selection()
        for item in selected:
            index = self.tree.index(item)
            if index < len(self.key_pool.keys):
                self.key_pool.keys[index].enabled = True
        
        self._refresh_key_list()
        self._show_status(f"Enabled {len(selected)} key(s)")
    
    def _disable_selected(self):
        """Disable selected keys"""
        selected = self.tree.selection()
        for item in selected:
            index = self.tree.index(item)
            if index < len(self.key_pool.keys):
                self.key_pool.keys[index].enabled = False
        
        self._refresh_key_list()
        self._show_status(f"Disabled {len(selected)} key(s)")
    
    def _remove_selected(self):
        """Remove selected keys"""
        selected = self.tree.selection()
        if not selected:
            return
        
        if messagebox.askyesno("Confirm", f"Remove {len(selected)} selected key(s)?"):
            # Get indices in reverse order to avoid index shifting
            indices = sorted([self.tree.index(item) for item in selected], reverse=True)
            
            for index in indices:
                self.key_pool.remove_key(index)
            
            self._refresh_key_list()
            self._show_status(f"Removed {len(selected)} key(s)")
    
    def _edit_cooldown(self):
        """Edit cooldown for selected key"""
        selected = self.tree.selection()
        if not selected or len(selected) != 1:
            messagebox.showwarning("Warning", "Please select exactly one key")
            return
        
        index = self.tree.index(selected[0])
        if index >= len(self.key_pool.keys):
            return
        
        key = self.key_pool.keys[index]
        
        # Create simple dialog
        dialog = tk.Toplevel(self.dialog)
        dialog.title("Edit Cooldown")
        dialog.geometry("300x150")
        
        tk.Label(dialog, text=f"Cooldown for {key.model}:").pack(pady=10)
        
        cooldown_var = tk.IntVar(value=key.cooldown)
        tb.Spinbox(dialog, from_=10, to=3600, textvariable=cooldown_var,
                  width=10).pack(pady=5)
        

    
    def _import_keys(self):
        """Import keys from JSON file"""
        from tkinter import filedialog
        
        filename = filedialog.askopenfilename(
            title="Import API Keys",
            filetypes=[("JSON files", "*.json"), ("All files", "*.*")]
        )
        
        if filename:
            try:
                with open(filename, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                
                if isinstance(data, list):
                    # Load keys
                    imported_count = 0
                    for key_data in data:
                        if isinstance(key_data, dict) and 'api_key' in key_data and 'model' in key_data:
                            self.key_pool.add_key(APIKeyEntry.from_dict(key_data))
                            imported_count += 1
                    
                    self._refresh_key_list()
                    messagebox.showinfo("Success", f"Imported {imported_count} API keys")
                else:
                    messagebox.showerror("Error", "Invalid file format")
                    
            except Exception as e:
                messagebox.showerror("Error", f"Failed to import: {str(e)}")
    
    def _export_keys(self):
        """Export keys to JSON file"""
        from tkinter import filedialog
        
        if not self.key_pool.keys:
            messagebox.showwarning("Warning", "No keys to export")
            return
        
        filename = filedialog.asksaveasfilename(
            title="Export API Keys",
            defaultextension=".json",
            filetypes=[("JSON files", "*.json"), ("All files", "*.*")]
        )
        
        if filename:
            try:
                # Convert keys to list of dicts
                key_list = [key.to_dict() for key in self.key_pool.get_all_keys()]
                
                with open(filename, 'w', encoding='utf-8') as f:
                    json.dump(key_list, f, indent=2, ensure_ascii=False)
                
                messagebox.showinfo("Success", f"Exported {len(key_list)} API keys")
                
            except Exception as e:
                messagebox.showerror("Error", f"Failed to export: {str(e)}")
    
    def _show_status(self, message: str):
        """Show status message"""
        self.stats_label.config(text=message)
    
    def _save_and_close(self):
        """Save configuration and close"""
        self._save_keys_to_config()
        messagebox.showinfo("Success", "API key configuration saved")
        self.dialog.destroy()
    
    def _on_close(self):
        """Handle dialog close"""
        self.dialog.destroy()