File size: 92,681 Bytes
72ee1b8
96d375d
72ee1b8
96d375d
 
 
72ee1b8
 
 
 
 
 
 
603907f
 
96d375d
603907f
72ee1b8
 
 
 
c877e71
72ee1b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
961c37a
e8adbc2
29b0788
72ee1b8
4c812e6
961c37a
021f64c
a81cfbc
bf7d85f
96d375d
bf7d85f
96d375d
 
 
 
 
 
 
 
 
 
 
 
 
 
603907f
 
 
 
 
 
 
 
 
96d375d
603907f
 
 
 
96d375d
 
 
 
603907f
 
 
 
 
96d375d
 
 
 
603907f
 
 
 
 
96d375d
 
 
603907f
96d375d
603907f
 
 
 
 
 
 
 
 
 
 
96d375d
 
 
 
 
 
 
 
 
 
 
 
 
603907f
 
 
 
 
96d375d
 
603907f
c877e71
bf7d85f
 
 
 
72ee1b8
357eb85
72ee1b8
 
357eb85
72ee1b8
 
 
b3b2188
fbc5d17
4c812e6
ce6dc43
72ee1b8
 
ac49b2f
c1d10f3
cbfc72f
92b6bc9
72ee1b8
 
c6bf417
2caeb98
bd261f2
a807cb9
72ee1b8
 
2c309e7
d3cd464
 
 
28436fc
 
c877e71
 
 
 
72ee1b8
 
 
 
 
 
 
961c37a
 
72ee1b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129e92c
 
72ee1b8
bf7d85f
c877e71
bf7d85f
 
 
c877e71
 
 
 
 
 
 
bf7d85f
 
 
c877e71
bf7d85f
 
 
c877e71
bf7d85f
 
603907f
 
 
 
 
 
bf7d85f
29b0788
96d375d
29b0788
 
 
 
5e67d9c
c877e71
96d375d
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
c877e71
 
 
 
 
 
5e67d9c
603907f
96d375d
603907f
bf7d85f
96d375d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603907f
96d375d
 
 
 
 
bf7d85f
603907f
96d375d
603907f
 
 
 
 
 
bf7d85f
603907f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
603907f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf7d85f
96d375d
603907f
 
bf7d85f
96d375d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603907f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
603907f
 
 
 
 
bf7d85f
603907f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf7d85f
603907f
 
 
 
 
 
 
 
 
 
 
72ee1b8
 
c877e71
961c37a
 
c877e71
 
96d375d
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
961c37a
 
c877e71
72ee1b8
 
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
357eb85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05d83a9
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
72ee1b8
c877e71
 
 
96d375d
c877e71
96d375d
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05d83a9
c877e71
 
 
 
05d83a9
c877e71
 
 
 
05d83a9
c877e71
 
 
 
 
 
 
 
05d83a9
c877e71
 
 
 
 
 
 
 
05d83a9
c877e71
 
 
 
05d83a9
c877e71
 
 
 
 
 
 
 
05d83a9
c877e71
 
 
96d375d
c877e71
 
 
 
 
 
 
 
 
 
 
96d375d
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72ee1b8
c877e71
 
 
 
 
 
96d375d
 
 
 
 
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72ee1b8
 
96d375d
72ee1b8
 
c877e71
 
 
 
 
 
 
 
96d375d
c877e71
 
 
 
 
 
 
96d375d
 
 
 
 
 
 
 
 
 
 
 
c877e71
 
96d375d
 
 
 
 
c877e71
 
 
 
96d375d
 
 
 
 
 
 
c877e71
 
96d375d
c877e71
 
 
 
 
 
96d375d
 
 
c877e71
96d375d
 
 
 
 
 
 
c877e71
 
96d375d
 
 
 
c877e71
96d375d
c877e71
 
 
 
72ee1b8
 
c877e71
603907f
c877e71
72ee1b8
 
 
961c37a
c877e71
72ee1b8
c877e71
72ee1b8
 
 
c877e71
72ee1b8
c877e71
 
5a805c8
 
c877e71
5a805c8
 
c877e71
 
ee7b9aa
c877e71
603907f
 
 
 
c877e71
72ee1b8
c877e71
72ee1b8
 
961c37a
72ee1b8
 
c877e71
 
72ee1b8
c877e71
603907f
 
 
 
c877e71
72ee1b8
c877e71
72ee1b8
129e92c
c877e71
 
e62967a
129e92c
 
 
e62967a
129e92c
 
 
c877e71
e62967a
 
 
 
7ceb2d7
 
 
 
e62967a
7ceb2d7
 
 
 
 
 
 
 
 
 
 
 
 
 
e62967a
7ceb2d7
96d375d
e62967a
 
96d375d
e62967a
c877e71
e62967a
 
 
 
603907f
 
e62967a
7ceb2d7
e62967a
 
603907f
 
 
 
 
 
 
 
 
96d375d
 
72ee1b8
c877e71
96d375d
 
 
 
 
 
 
 
 
 
72ee1b8
 
 
96d375d
603907f
 
96d375d
 
 
 
603907f
 
96d375d
603907f
 
c877e71
 
96d375d
603907f
c877e71
 
96d375d
 
 
 
 
c877e71
 
 
 
 
72ee1b8
c877e71
 
 
 
 
 
 
96d375d
 
 
 
 
 
 
c877e71
96d375d
 
 
 
 
c877e71
 
 
96d375d
 
 
 
 
 
c877e71
 
 
 
 
 
96d375d
 
 
 
 
 
 
 
 
c877e71
 
 
 
 
96d375d
 
c877e71
96d375d
 
 
c877e71
 
 
 
 
96d375d
 
c877e71
 
 
 
 
 
 
 
 
 
 
96d375d
c877e71
 
 
96d375d
 
 
 
 
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
 
 
 
 
c877e71
 
96d375d
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
 
 
 
 
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
 
 
 
 
 
 
c877e71
96d375d
 
 
 
 
c877e71
 
 
96d375d
 
 
 
 
 
c877e71
 
 
 
 
 
96d375d
 
 
 
 
 
 
 
 
c877e71
 
 
 
 
96d375d
 
c877e71
96d375d
 
 
c877e71
 
 
 
 
96d375d
 
c877e71
 
 
 
 
 
 
96d375d
c877e71
 
96d375d
 
 
 
 
c877e71
96d375d
c877e71
 
 
 
 
96d375d
 
 
 
 
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
 
 
 
 
c877e71
 
 
 
96d375d
 
 
 
 
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
 
 
 
 
 
 
c877e71
96d375d
 
 
 
 
c877e71
 
 
96d375d
 
 
 
 
 
c877e71
 
 
 
 
 
96d375d
 
 
 
 
 
 
 
 
c877e71
 
 
 
 
96d375d
 
c877e71
96d375d
 
 
c877e71
 
 
 
 
96d375d
 
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
 
 
 
 
 
 
 
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
c877e71
96d375d
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
 
 
 
 
 
c877e71
 
 
 
96d375d
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
 
 
 
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
 
 
 
c877e71
 
 
 
 
 
 
 
 
 
96d375d
c877e71
 
 
 
96d375d
c877e71
 
 
 
 
 
 
96d375d
c877e71
 
 
 
 
 
 
 
 
 
 
 
 
96d375d
603907f
 
 
 
 
 
 
 
72ee1b8
603907f
 
96d375d
603907f
 
 
 
 
 
96d375d
 
 
 
 
 
 
 
 
 
 
 
 
 
603907f
 
 
 
 
96d375d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603907f
 
 
 
 
 
96d375d
 
 
603907f
72ee1b8
603907f
 
96d375d
603907f
 
 
 
 
 
 
 
 
 
 
 
 
72ee1b8
603907f
 
 
 
 
 
 
72ee1b8
603907f
 
96d375d
603907f
 
 
 
 
 
 
 
 
 
 
 
72ee1b8
d3cd464
72ee1b8
 
 
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
"""
ArchNemix Controller Space  v1.8
════════════════════════════════════════════════════════════════════════════════
ADDED: Enhanced error tracking with exact backend URL for each failed stage
ADDED: Detailed debugging information for pipeline failures
ADDED: Failure context including stage, backend URL, job ID, and error message
"""

import os
import uuid
import asyncio
import logging
from datetime import datetime, timedelta
from typing import Dict, Any, Optional, Tuple, List
from enum import Enum
from dataclasses import dataclass, asdict, field
from collections import defaultdict

import httpx
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, Response, RedirectResponse, StreamingResponse
from pydantic import BaseModel

from dataset import DatasetStore

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)s | %(message)s",
)
logger = logging.getLogger(__name__)

# =============================================================================
# CONFIGURATION
# =============================================================================

APP_KEY    = os.getenv("APP_KEY", "")
HF_TOKEN   = os.getenv("HF_TOKEN", "")
HF_DATASET = os.getenv("HF_DATASET", "")
HF_DATASET_2 = os.getenv("HF_DATASET_2", "")
ADMIN_KEY  = os.getenv("ADMIN_KEY", "")  # Secret key that bypasses rate limiting

pipeline_heartbeats: Dict[str, datetime] = {}
FRONTEND_HEARTBEAT_GRACE = 45
FFMPEG_QUEUE_DEPTH = 2

# ═════════════════════════════════════════════════════════════════════════════
# ENHANCED ADMIN ANALYTICS STORAGE - v1.8
# ═════════════════════════════════════════════════════════════════════════════
@dataclass
class StageFailureDetail:
    """Detailed information about a stage failure"""
    stage: str
    backend_url: str
    backend_type: str
    job_id: str
    error_message: str
    error_type: str  # e.g., "timeout", "backend_error", "save_failed", "user_cancelled"
    submitted_at: Optional[datetime] = None
    failed_at: datetime = field(default_factory=datetime.utcnow)
    http_status: Optional[int] = None
    response_body: Optional[str] = None

@dataclass
class JobAnalytics:
    """Track detailed analytics for a single job/pipeline"""
    pipeline_id: str
    created_at: datetime
    user_ip: str  # anonymized in logs
    is_admin: bool
    rate_limited: bool = False
    
    # Stage tracking with backend details
    tts_submitted_at: Optional[datetime] = None
    tts_completed_at: Optional[datetime] = None
    tts_status: str = "idle"
    tts_error: Optional[str] = None
    tts_backend: Optional[str] = None  # Exact URL of backend space
    tts_backend_type: Optional[str] = None
    tts_job_id: Optional[str] = None
    tts_failure_detail: Optional[StageFailureDetail] = None
    
    align_submitted_at: Optional[datetime] = None
    align_completed_at: Optional[datetime] = None
    align_status: str = "idle"
    align_error: Optional[str] = None
    align_backend: Optional[str] = None  # Exact URL of backend space
    align_backend_type: Optional[str] = None
    align_job_id: Optional[str] = None
    align_failure_detail: Optional[StageFailureDetail] = None
    
    video_submitted_at: Optional[datetime] = None
    video_completed_at: Optional[datetime] = None
    video_status: str = "idle"
    video_error: Optional[str] = None
    video_backend: Optional[str] = None  # Exact URL of backend space
    video_backend_type: Optional[str] = None
    video_job_id: Optional[str] = None
    video_storage_method: Optional[str] = None  # "dataset" or "ffmpeg_fallback"
    video_failure_detail: Optional[StageFailureDetail] = None
    
    # Final outcome
    final_status: str = "pending"  # "success", "failed", "cancelled"
    completed_at: Optional[datetime] = None
    
    def to_dict(self) -> Dict:
        d = asdict(self)
        # Convert datetimes to ISO strings
        for key, value in d.items():
            if isinstance(value, datetime):
                d[key] = value.isoformat()
            elif isinstance(value, StageFailureDetail):
                d[key] = {
                    "stage": value.stage,
                    "backend_url": value.backend_url,
                    "backend_type": value.backend_type,
                    "job_id": value.job_id,
                    "error_message": value.error_message,
                    "error_type": value.error_type,
                    "submitted_at": value.submitted_at.isoformat() if value.submitted_at else None,
                    "failed_at": value.failed_at.isoformat(),
                    "http_status": value.http_status,
                    "response_body": value.response_body[:500] if value.response_body else None,  # Truncate long responses
                }
        return d

# Global analytics storage
analytics_storage: Dict[str, JobAnalytics] = {}  # pipeline_id -> analytics
stage_failure_stats: Dict[str, Dict[str, int]] = defaultdict(lambda: defaultdict(int))
# stage_failure_stats["tts"]["timeout"] = 5
# stage_failure_stats["tts"]["backend_error"] = 3

# Rate limiting storage
rate_limit_storage: Dict[str, list[datetime]] = {}
RATE_LIMIT_MAX_PER_HOUR = 10
RATE_LIMIT_WINDOW_HOURS = 1

ALLOWED_ORIGINS = [
    "https://shortgenx.pages.dev",
    "http://localhost:3000",
    "http://127.0.0.1:3000",
    "https://ytshortmakerarchx-archnemix-controller.hf.space",
]

TTS_SPACES = [
    "https://archnemix-kokoro-tts-polyglot-kokoro-tts-rust.hf.space",
    "https://Archnemix-Kokoro-TTS-Polyglot-kokoro-tts-GO.hf.space",
    "https://Archnemix-Kokoro-TTS-Polyglot-kokorotts-python.hf.space",
    "https://archnemix-kokoro-tts-polyglot-kokoro-tts-nodejs.hf.space",
]
MFA_SPACES = [
    "https://montreal-forced-align-polygot-mfa-node-js.hf.space",
    "https://montreal-forced-align-polygot-MFA-GO.hf.space",
    "https://montreal-forced-align-polygot-MFA-RUST.hf.space",
    "https://montreal-forced-align-polygot-MFA-python.hf.space",
]
QWEN_SPACES = [
    "https://qwen-forced-aligner-polygot-qwenforcedaligner-nodejs.hf.space",
    "https://qwen-forced-aligner-polygot-qwenforcedaligner-go.hf.space",
    "https://Qwen-Forced-Aligner-polygot-Qwenforcedaligner-rust.hf.space",
    "https://Qwen-Forced-Aligner-polygot-qwenforcedaligner-python.hf.space",
]
FFMPEG_SPACES = [
    "https://archnemix-ffmpeg-polyglot-ffmpeg-rust.hf.space",
    "https://archnemix-ffmpeg-polyglot-ffmpeg-nodejs.hf.space",             
    "https://archnemix-ffmpeg-polyglot-ffmpeg-GO.hf.space",
    "https://archnemix-ffmpeg-polyglot-ffmpeg-python.hf.space",
]

non_used_spaces = [
    "Currently None",
]

ALL_SPACES: Dict[str, list] = {
    "tts":    TTS_SPACES,
    "mfa":    MFA_SPACES,
    "qwen":   QWEN_SPACES,
    "ffmpeg": FFMPEG_SPACES,
}

SESSION_TTL        = 3600
STATUS_POLL_EVERY  = 10
HTTP_TIMEOUT       = 15.0

# =============================================================================
# STAGE CONSTANTS
# =============================================================================

class Stage:
    TTS   = "tts"
    ALIGN = "align"
    VIDEO = "video"

class StageStatus:
    IDLE      = "idle"
    RUNNING   = "running"
    DONE      = "done"
    FAILED    = "failed"

# =============================================================================
# IN-MEMORY STATE
# =============================================================================

pipelines:    Dict[str, Dict[str, Any]] = {}
status_cache: Dict[str, Dict[str, Any]] = {}

# =============================================================================
# RATE LIMITING HELPERS
# =============================================================================

def _get_client_ip(request: Request) -> str:
    """
    Extract real client IP from request.
    Checks headers in order:
      1. CF-Connecting-IP (Cloudflare)
      2. X-Forwarded-For (standard proxy header)
      3. request.client.host (direct connection)
    """
    cf_ip = request.headers.get("CF-Connecting-IP")
    if cf_ip:
        return cf_ip.strip()
    
    forwarded = request.headers.get("X-Forwarded-For")
    if forwarded:
        return forwarded.split(",")[0].strip()
    
    return request.client.host if request.client else "unknown"

def _anonymize_ip(ip: str) -> str:
    """Anonymize IP for privacy in analytics (keep only first 3 octets)"""
    parts = ip.split('.')
    if len(parts) >= 3:
        return f"{parts[0]}.{parts[1]}.{parts[2]}.xxx"
    return "unknown"

def _is_admin_request(request: Request) -> bool:
    """Check if request has admin credentials via API key header."""
    admin_header = request.headers.get("X-Admin-Key")
    if ADMIN_KEY and admin_header and admin_header == ADMIN_KEY:
        return True
    return False

def _cleanup_old_timestamps(ip: str) -> None:
    """Remove timestamps older than RATE_LIMIT_WINDOW_HOURS from storage."""
    if ip not in rate_limit_storage:
        return
    
    cutoff = datetime.utcnow() - timedelta(hours=RATE_LIMIT_WINDOW_HOURS)
    rate_limit_storage[ip] = [
        ts for ts in rate_limit_storage[ip]
        if ts > cutoff
    ]
    
    if not rate_limit_storage[ip]:
        del rate_limit_storage[ip]

def _check_rate_limit(ip: str) -> Tuple[bool, int, int]:
    """Check if IP has exceeded rate limit."""
    _cleanup_old_timestamps(ip)
    
    if ip not in rate_limit_storage:
        return True, 0, 0
    
    current_count = len(rate_limit_storage[ip])
    
    if current_count >= RATE_LIMIT_MAX_PER_HOUR:
        oldest_timestamp = min(rate_limit_storage[ip])
        expires_at = oldest_timestamp + timedelta(hours=RATE_LIMIT_WINDOW_HOURS)
        seconds_until_expiry = int((expires_at - datetime.utcnow()).total_seconds())
        
        return False, current_count, max(0, seconds_until_expiry)
    
    return True, current_count, 0

def _record_request(ip: str) -> None:
    """Record a new pipeline start request for this IP."""
    _cleanup_old_timestamps(ip)
    
    if ip not in rate_limit_storage:
        rate_limit_storage[ip] = []
    
    rate_limit_storage[ip].append(datetime.utcnow())

# =============================================================================
# ENHANCED ANALYTICS HELPERS
# =============================================================================

def _record_stage_failure(
    analytics: JobAnalytics, 
    stage: str, 
    backend_url: str, 
    backend_type: str,
    job_id: str,
    error_message: str,
    error_type: str,
    http_status: Optional[int] = None,
    response_body: Optional[str] = None
):
    """Record detailed stage failure information"""
    failure_detail = StageFailureDetail(
        stage=stage,
        backend_url=backend_url,
        backend_type=backend_type,
        job_id=job_id,
        error_message=error_message,
        error_type=error_type,
        http_status=http_status,
        response_body=response_body,
        submitted_at=datetime.utcnow() if stage == "tts" else None
    )
    
    # Store failure detail in the appropriate stage
    if stage == "tts":
        analytics.tts_failure_detail = failure_detail
        analytics.tts_error = error_message
        analytics.tts_status = "failed"
    elif stage == "align":
        analytics.align_failure_detail = failure_detail
        analytics.align_error = error_message
        analytics.align_status = "failed"
    elif stage == "video":
        analytics.video_failure_detail = failure_detail
        analytics.video_error = error_message
        analytics.video_status = "failed"
    
    # Update global failure stats
    stage_failure_stats[stage][error_type] += 1
    
    logger.error(
        f"Pipeline {analytics.pipeline_id[:8]} {stage} failed on {backend_url} "
        f"(job: {job_id}) - {error_type}: {error_message[:200]}"
    )

def _get_analytics_summary() -> Dict:
    """Generate comprehensive analytics summary with backend breakdown"""
    total_pipelines = len(analytics_storage)
    if total_pipelines == 0:
        return {
            "total_pipelines": 0,
            "message": "No analytics data available yet"
        }
    
    # Count by status
    successful = sum(1 for a in analytics_storage.values() if a.final_status == "success")
    failed = sum(1 for a in analytics_storage.values() if a.final_status == "failed")
    cancelled = sum(1 for a in analytics_storage.values() if a.final_status == "cancelled")
    pending = sum(1 for a in analytics_storage.values() if a.final_status == "pending")
    
    # Count by user type
    admin_users = sum(1 for a in analytics_storage.values() if a.is_admin)
    normal_users = total_pipelines - admin_users
    
    # Rate limit hits
    rate_limited = sum(1 for a in analytics_storage.values() if a.rate_limited)
    
    # Stage success rates
    tts_success = sum(1 for a in analytics_storage.values() if a.tts_status == "done")
    align_success = sum(1 for a in analytics_storage.values() if a.align_status == "done")
    video_success = sum(1 for a in analytics_storage.values() if a.video_status == "done")
    
    tts_failed = sum(1 for a in analytics_storage.values() if a.tts_status == "failed")
    align_failed = sum(1 for a in analytics_storage.values() if a.align_status == "failed")
    video_failed = sum(1 for a in analytics_storage.values() if a.video_status == "failed")
    
    # Calculate average processing times
    tts_times = []
    for a in analytics_storage.values():
        if a.tts_submitted_at and a.tts_completed_at:
            duration = (a.tts_completed_at - a.tts_submitted_at).total_seconds()
            tts_times.append(duration)
    
    align_times = []
    for a in analytics_storage.values():
        if a.align_submitted_at and a.align_completed_at:
            duration = (a.align_completed_at - a.align_submitted_at).total_seconds()
            align_times.append(duration)
    
    video_times = []
    for a in analytics_storage.values():
        if a.video_submitted_at and a.video_completed_at:
            duration = (a.video_completed_at - a.video_submitted_at).total_seconds()
            video_times.append(duration)
    
    # Failure breakdown by stage and error type
    failure_breakdown = {
        "tts": dict(stage_failure_stats.get("tts", {})),
        "align": dict(stage_failure_stats.get("align", {})),
        "video": dict(stage_failure_stats.get("video", {})),
    }
    
    # Storage method stats
    dataset_storage = sum(1 for a in analytics_storage.values() if a.video_storage_method == "dataset")
    ffmpeg_fallback = sum(1 for a in analytics_storage.values() if a.video_storage_method == "ffmpeg_fallback")
    
    # Backend usage statistics
    backend_usage = defaultdict(int)
    for a in analytics_storage.values():
        if a.tts_backend:
            backend_usage[a.tts_backend] += 1
        if a.align_backend:
            backend_usage[a.align_backend] += 1
        if a.video_backend:
            backend_usage[a.video_backend] += 1
    
    # Backend failure rates
    backend_failures = defaultdict(int)
    backend_total_usage = defaultdict(int)
    for a in analytics_storage.values():
        if a.tts_backend:
            backend_total_usage[a.tts_backend] += 1
            if a.tts_status == "failed":
                backend_failures[a.tts_backend] += 1
        if a.align_backend:
            backend_total_usage[a.align_backend] += 1
            if a.align_status == "failed":
                backend_failures[a.align_backend] += 1
        if a.video_backend:
            backend_total_usage[a.video_backend] += 1
            if a.video_status == "failed":
                backend_failures[a.video_backend] += 1
    
    backend_stats = {}
    for url in set(list(backend_total_usage.keys()) + list(backend_failures.keys())):
        total = backend_total_usage.get(url, 0)
        failed_count = backend_failures.get(url, 0)
        backend_stats[url] = {
            "total_uses": total,
            "failures": failed_count,
            "failure_rate": round(failed_count / total * 100, 1) if total > 0 else 0,
            "backend_type": next(
                (t for t, urls in ALL_SPACES.items() if url in urls),
                "unknown"
            )
        }
    
    return {
        "total_pipelines": total_pipelines,
        "successful": successful,
        "failed": failed,
        "cancelled": cancelled,
        "pending": pending,
        "success_rate": round(successful / total_pipelines * 100, 1) if total_pipelines > 0 else 0,
        "users": {
            "admin": admin_users,
            "normal": normal_users,
            "rate_limited": rate_limited,
        },
        "stage_success": {
            "tts": {"success": tts_success, "failed": tts_failed, "rate": round(tts_success / (tts_success + tts_failed) * 100, 1) if (tts_success + tts_failed) > 0 else 0},
            "align": {"success": align_success, "failed": align_failed, "rate": round(align_success / (align_success + align_failed) * 100, 1) if (align_success + align_failed) > 0 else 0},
            "video": {"success": video_success, "failed": video_failed, "rate": round(video_success / (video_success + video_failed) * 100, 1) if (video_success + video_failed) > 0 else 0},
        },
        "avg_processing_time_seconds": {
            "tts": round(sum(tts_times) / len(tts_times), 1) if tts_times else 0,
            "align": round(sum(align_times) / len(align_times), 1) if align_times else 0,
            "video": round(sum(video_times) / len(video_times), 1) if video_times else 0,
        },
        "failure_breakdown": failure_breakdown,
        "video_storage": {
            "dataset_primary": dataset_storage,
            "ffmpeg_fallback": ffmpeg_fallback,
            "fallback_rate": round(ffmpeg_fallback / (dataset_storage + ffmpeg_fallback) * 100, 1) if (dataset_storage + ffmpeg_fallback) > 0 else 0,
        },
        "backend_stats": backend_stats,
        "time_range": {
            "oldest": min((a.created_at for a in analytics_storage.values()), default=datetime.utcnow()).isoformat(),
            "newest": max((a.created_at for a in analytics_storage.values()), default=datetime.utcnow()).isoformat(),
        }
    }

def _get_active_jobs() -> List[Dict]:
    """Get all currently running jobs with details"""
    active_jobs = []
    
    for pid, pipeline in pipelines.items():
        running_stages = []
        for stage_name in [Stage.TTS, Stage.ALIGN, Stage.VIDEO]:
            s = pipeline["stages"][stage_name]
            if s["status"] == StageStatus.RUNNING:
                running_stages.append({
                    "stage": stage_name,
                    "backend_url": s.get("backend_url"),
                    "backend_job_id": s.get("backend_job_id"),
                    "submitted_at": s.get("submitted_at"),
                    "progress": s.get("progress", 0),
                    "message": s.get("message", ""),
                })
        
        if running_stages:
            analytics = analytics_storage.get(pid)
            active_jobs.append({
                "pipeline_id": pid,
                "created_at": pipeline["created_at"],
                "running_stages": running_stages,
                "user_ip": analytics.user_ip if analytics else "unknown",
                "is_admin": analytics.is_admin if analytics else False,
            })
    
    return active_jobs

# =============================================================================
# RATE LIMIT CLEANUP LOOP
# =============================================================================

async def _rate_limit_cleanup_loop():
    while True:
        await asyncio.sleep(300)
        cutoff = datetime.utcnow() - timedelta(hours=RATE_LIMIT_WINDOW_HOURS)
        cleaned_ips = 0
        
        for ip in list(rate_limit_storage.keys()):
            rate_limit_storage[ip] = [
                ts for ts in rate_limit_storage[ip]
                if ts > cutoff
            ]
            
            if not rate_limit_storage[ip]:
                del rate_limit_storage[ip]
                cleaned_ips += 1
        
        if cleaned_ips > 0:
            logger.info(f"Rate limit cleanup: removed {cleaned_ips} expired IP entries")

# =============================================================================
# REQUEST / RESPONSE MODELS
# =============================================================================

class PipelineStartRequest(BaseModel):
    text:  str
    voice: str   = "male_high"
    rate:  float = 1.0
    language:    str = "English"
    pass_number: int = 1
    background: str            = "mc1"
    duration:   Optional[float] = None

class RerunTTSRequest(BaseModel):
    text:  Optional[str]   = None
    voice: Optional[str]   = None
    rate:  Optional[float] = None

class AlignSubmitRequest(BaseModel):
    language:     Optional[str] = None
    pass_number:  Optional[int] = None
    aligner_type: Optional[str] = None

class VideoSubmitRequest(BaseModel):
    subtitles_ass: str
    background:    Optional[str]   = None
    duration:      Optional[float] = None

# =============================================================================
# FASTAPI APP
# =============================================================================

app = FastAPI(
    title="ArchNemix Controller v1",
    version="1.8.0",
    docs_url="/docs",
    redoc_url=None,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["GET", "POST", "DELETE", "OPTIONS"],
    allow_headers=["*"],
    expose_headers=["X-Pipeline-ID", "X-Session-ID"],
)

@app.middleware("http")
async def enforce_cors_origin(request: Request, call_next):
    """
    Extra security: Reject requests from non-allowed origins with clear error.
    This complements CORS middleware for better security.
    """
    origin = request.headers.get("origin")
    
    # Allow requests with no origin (same-origin, API calls from servers)
    if not origin:
        response = await call_next(request)
        return response
    
    # Check if origin is in allowed list
    is_allowed = origin in ALLOWED_ORIGINS
    
    # Allow localhost development ports (any port)
    if not is_allowed:
        is_allowed = any(
            origin.startswith(f"http://localhost:3000") or 
            origin.startswith(f"http://127.0.0.1:3000")
        )
    
    if not is_allowed:
        logger.warning(f"[CORS SECURITY] Rejected request from unauthorized origin: {origin}")
        return JSONResponse(
            status_code=403,
            content={
                "error": "cors_origin_not_allowed",
                "message": f"Origin '{origin}' is not allowed to access this service.",
                "allowed_origins": ["shortgenx.pages.dev", "localhost:3000"]
            }
        )
    
    response = await call_next(request)
    return response

# =============================================================================
# HTTP CLIENT
# =============================================================================

_http: Optional[httpx.AsyncClient] = None

def http() -> httpx.AsyncClient:
    return _http

# =============================================================================
# DATASET STORE
# =============================================================================

_store: Optional[DatasetStore] = None

def store() -> DatasetStore:
    return _store

# =============================================================================
# SAFE JSON HELPER
# =============================================================================

def _safe_json(r: httpx.Response) -> Any:
    try:
        return r.json()
    except Exception:
        return {
            "error":      "backend_error",
            "error_code": "EMPTY_RESPONSE",
            "detail":     r.text or f"Backend returned HTTP {r.status_code} with no body.",
        }

# =============================================================================
# STATUS CACHE (keep all existing functions)
# =============================================================================

async def _check_one(url: str, stype: str) -> Dict[str, Any]:
    dead = {
        "url": url, "type": stype,
        "online": False, "worker_ready": False,
        "can_submit": False, "slot_available": False, "queue_full": True,
        "running": 0, "waiting": 0,
        "checked_at": datetime.utcnow().isoformat(),
    }
    try:
        if stype in ("mfa", "qwen"):
            r = await http().get(f"{url}/queue/status", timeout=5.0)
        else:
            r = await http().get(f"{url}/queue", timeout=5.0)
 
        if r.status_code != 200:
            return dead
 
        d = r.json()
 
        running        = int(d.get("running", 0))
        waiting        = int(d.get("waiting", 0))
        total          = running + waiting
        can_submit     = bool(d.get("can_submit",     total < 2))
        slot_available = bool(d.get("slot_available", running == 0))
        queue_full     = bool(d.get("queue_full",     total >= 2))
        worker_ready   = bool(d.get("worker_ready",   True))
 
        return {
            "url": url, "type": stype, "online": True,
            "worker_ready": worker_ready,
            "can_submit":    can_submit,
            "slot_available": slot_available,
            "queue_full":    queue_full,
            "running": running, "waiting": waiting,
            "checked_at": datetime.utcnow().isoformat(),
        }
    except Exception as e:
        logger.debug(f"Status check failed {url}: {e}")
        return dead


async def _status_loop():
    while True:
        tasks = [
            _check_one(url, stype)
            for stype, urls in ALL_SPACES.items()
            for url in urls
        ]
        results = await asyncio.gather(*tasks, return_exceptions=True)
        for r in results:
            if isinstance(r, dict):
                existing = status_cache.get(r["url"], {})
                r["_reserved"] = existing.get("_reserved", 0)
                status_cache[r["url"]] = r
        await asyncio.sleep(STATUS_POLL_EVERY)

def _status_summary() -> Dict[str, Any]:
    """Enhanced status summary with queue info and separate MFA/Qwen stats"""
    out: Dict[str, Any] = {}
    
    for stype, urls in ALL_SPACES.items():
        spaces = []
        free = busy = 0
        total_slots = 0
        total_queue = 0
        
        for url in urls:
            c = status_cache.get(url, {
                "online": False, 
                "can_submit": False,
                "worker_ready": False,
                "running": 0,
                "waiting": 0,
            })
            
            running = c.get("running", 0)
            waiting = c.get("waiting", 0)
            depth = 2
            available_slots = max(0, depth - (running + waiting))
            queue_available = waiting < 1
            
            spaces.append({
                "url": url,
                "online": c.get("online", False),
                "can_submit": c.get("can_submit", False),
                "worker_ready": c.get("worker_ready", False),
                "running": running,
                "waiting": waiting,
                "available_slots": available_slots,
                "queue_available": queue_available,
            })
            
            if c.get("can_submit"):
                free += 1
                total_slots += available_slots
            else:
                busy += 1
                total_slots += available_slots
            
            total_queue += waiting
        
        out[stype] = {
            "free": free,
            "busy": busy,
            "total": len(urls),
            "all_busy": free == 0,
            "total_slots": total_slots,
            "total_queue": total_queue,
            "spaces": spaces,
        }
    
    mfa_free = out["mfa"]["free"]
    mfa_total = out["mfa"]["total"]
    mfa_slots = out["mfa"]["total_slots"]
    mfa_queue = out["mfa"]["total_queue"]
    
    qwen_free = out["qwen"]["free"]
    qwen_total = out["qwen"]["total"]
    qwen_slots = out["qwen"]["total_slots"]
    qwen_queue = out["qwen"]["total_queue"]
    
    out["mfa_detailed"] = {
        "free": mfa_free,
        "busy": mfa_total - mfa_free,
        "total": mfa_total,
        "all_busy": mfa_free == 0,
        "total_slots": mfa_slots,
        "total_queue": mfa_queue,
    }
    
    out["qwen_detailed"] = {
        "free": qwen_free,
        "busy": qwen_total - qwen_free,
        "total": qwen_total,
        "all_busy": qwen_free == 0,
        "total_slots": qwen_slots,
        "total_queue": qwen_queue,
    }
    
    aligner_free = mfa_free + qwen_free
    aligner_total = mfa_total + qwen_total
    aligner_slots = mfa_slots + qwen_slots
    aligner_queue = mfa_queue + qwen_queue
    
    out["aligners"] = {
        "free": aligner_free,
        "busy": aligner_total - aligner_free,
        "total": aligner_total,
        "all_busy": aligner_free == 0,
        "total_slots": aligner_slots,
        "total_queue": aligner_queue,
    }
    
    return out

# =============================================================================
# SPACE PICKER (keep existing)
# =============================================================================

def _release_reservation(url: str):
    if url and url in status_cache:
        c = status_cache[url]
        c["_reserved"] = max(0, c.get("_reserved", 1) - 1)

async def _pick(stype: str) -> Optional[str]:
    urls      = ALL_SPACES[stype]
    best_url  = None
    best_load = float("inf")
    depth = FFMPEG_QUEUE_DEPTH
 
    for url in urls:
        c        = status_cache.get(url, {})
        if c and not c.get("online", True):
            continue
        running  = c.get("running",   0)
        waiting  = c.get("waiting",   0)
        reserved = c.get("_reserved", 0)
        load     = running + waiting + reserved
        if load >= depth:
            continue
        if load < best_load:
            best_load = load
            best_url  = url
 
    if best_url is None:
        results = await asyncio.gather(*[_check_one(url, stype) for url in urls])
        for r in results:
            if isinstance(r, dict):
                status_cache[r["url"]] = r
 
        for url in urls:
            c        = status_cache.get(url, {})
            if not c.get("online"):
                continue
            running  = c.get("running",   0)
            waiting  = c.get("waiting",   0)
            reserved = c.get("_reserved", 0)
            load     = running + waiting + reserved
            if load >= depth:
                continue
            if load < best_load:
                best_load = load
                best_url  = url
 
    if best_url and best_url in status_cache:
        c = status_cache[best_url]
        c["_reserved"] = c.get("_reserved", 0) + 1
        total = c.get("running", 0) + c.get("waiting", 0) + c["_reserved"]
        c["can_submit"]     = total < depth
        c["queue_full"]     = total >= depth
        c["slot_available"] = c.get("running", 0) == 0
 
    return best_url

async def _pick_aligner() -> Tuple[Optional[str], Optional[str]]:
    for stype in ("mfa", "qwen"):
        url = await _pick(stype)
        if url:
            return url, stype
    return None, None

# =============================================================================
# PIPELINE HELPERS
# =============================================================================

def _new_pipeline(config: PipelineStartRequest) -> Dict[str, Any]:
    pid = uuid.uuid4().hex
    return {
        "pipeline_id": pid,
        "created_at":  datetime.utcnow().isoformat(),
        "last_active": datetime.utcnow().isoformat(),
        "finalized":   False,
        "config": {
            "text":         config.text,
            "voice":        config.voice,
            "rate":         config.rate,
            "language":     config.language,
            "pass_number":  config.pass_number,
            "background":   config.background,
            "duration":     config.duration,
            "aligner_type": "mfa",
        },
        "stages": {
            Stage.TTS:   _blank_stage(),
            Stage.ALIGN: _blank_stage(),
            Stage.VIDEO: _blank_stage(),
        },
        "assets": {
            "audio_url":        None,
            "timestamps_url":   None,
            "video_url":        None,
            "video_download_url": None,
            "video_stream_url":   None,
        },
    }


def _blank_stage() -> Dict[str, Any]:
    return {
        "status":                  StageStatus.IDLE,
        "backend_url":             None,
        "backend_job_id":          None,
        "backend_type":            None,
        "submitted_at":            None,
        "completed_at":            None,
        "error":                   None,
        "progress":                0,
        "chunks_done":             0,
        "chunks_total":            0,
        "elapsed_s":               None,
        "estimated_remaining_s":   None,
        "message":                 "",
        "encode_stats":            None,
    }


def _touch(pid: str) -> Optional[Dict]:
    p = pipelines.get(pid)
    if p:
        p["last_active"] = datetime.utcnow().isoformat()
    return p


def _pipeline_or_404(pid: str) -> Dict:
    p = _touch(pid)
    if not p:
        raise HTTPException(404, {
            "error":  "pipeline_not_found",
            "detail": "Pipeline not found or expired. Start a new one.",
        })
    return p


def _client_id(pid: str) -> str:
    return f"ctrl_{pid[:10]}"

# =============================================================================
# BACKEND JOB POLLER (with enhanced error tracking)
# =============================================================================

async def _poll_backend_stage(p: Dict, stage: str) -> None:
    s = p["stages"][stage]
    if s["status"] != StageStatus.RUNNING:
        return

    url = s["backend_url"]
    jid = s["backend_job_id"]
    pid = p["pipeline_id"]
    analytics = analytics_storage.get(pid)

    try:
        r = await http().get(
            f"{url}/job/{jid}",
            params={"slim": "true"} if stage != Stage.VIDEO else {},
            timeout=HTTP_TIMEOUT,
        )
    except httpx.TimeoutException as e:
        logger.warning(f"Poll timeout {pid}/{stage}: {e}")
        if analytics:
            _record_stage_failure(
                analytics, stage, url, s["backend_type"], jid,
                f"Polling timeout after {HTTP_TIMEOUT}s",
                "poll_timeout",
                http_status=None
            )
        s["status"] = StageStatus.FAILED
        s["error"] = f"Polling timeout: {e}"
        return
    except Exception as e:
        logger.warning(f"Poll error {pid}/{stage}: {e}")
        if analytics:
            _record_stage_failure(
                analytics, stage, url, s["backend_type"], jid,
                str(e), "poll_error"
            )
        return

    if r.status_code == 404:
        s["status"] = StageStatus.FAILED
        s["error"] = "Job expired on backend (5 min TTL). Please re-run this step."
        if analytics:
            _record_stage_failure(
                analytics, stage, url, s["backend_type"], jid,
                "Job expired on backend (5 min TTL)", "job_expired",
                http_status=404
            )
        return

    data = _safe_json(r)
    bk_status = data.get("status", "unknown")

    if bk_status == "completed":
        await _finalise_stage(p, stage, url, jid, data)

    elif bk_status in ("failed", "abandoned"):
        error_msg = data.get("error", bk_status)
        s["status"] = StageStatus.FAILED
        s["error"] = error_msg
        s["completed_at"] = datetime.utcnow().isoformat()
        if analytics:
            _record_stage_failure(
                analytics, stage, url, s["backend_type"], jid,
                error_msg, "backend_job_failed",
                http_status=r.status_code,
                response_body=str(data)[:500]
            )

    elif bk_status in ("running", "queued", "processing"):
        s["progress"] = data.get("progress", s.get("progress", 0))
        s["chunks_done"] = data.get("chunks_done", s.get("chunks_done", 0))
        s["chunks_total"] = data.get("chunks_total", s.get("chunks_total", 0))
        s["elapsed_s"] = data.get("elapsed_s", s.get("elapsed_s"))
        s["estimated_remaining_s"] = data.get("estimated_remaining_s", s.get("estimated_remaining_s"))
        s["message"] = data.get("message", s.get("message", ""))
        if "encode_stats" in data:
            s["encode_stats"] = data["encode_stats"]


async def _finalise_stage(p: Dict, stage: str, url: str, jid: str, slim_data: Dict):
    pid = p["pipeline_id"]
    s   = p["stages"][stage]
    analytics = analytics_storage.get(pid)

    try:
        if stage == Stage.TTS:
            r = await http().get(f"{url}/job/{jid}", params={"slim": "false"}, timeout=30.0)
            full = _safe_json(r)
            audio_b64  = full.get("audio_base64", "")
            timestamps = full.get("word_timestamps", [])

            import base64, json
            wav_bytes = base64.b64decode(audio_b64)
            audio_url = await store().save(pid, "audio.wav", wav_bytes, content_type="audio/wav")

            ts_bytes = json.dumps(timestamps).encode()
            ts_url   = await store().save(pid, "tts_timestamps.json", ts_bytes, content_type="application/json")

            meta = {
                "pipeline_id": pid,
                "created_at":  datetime.utcnow().isoformat() + "Z",
            }
            await store().save(pid, "meta.json", json.dumps(meta).encode(), content_type="application/json")

            p["assets"]["audio_url"]      = audio_url
            p["assets"]["timestamps_url"] = ts_url

            if analytics:
                analytics.tts_completed_at = datetime.utcnow()
                analytics.tts_status = "done"
                analytics.tts_error = None

            logger.info(f"Pipeline {pid[:8]} TTS done → {audio_url}")

        elif stage == Stage.ALIGN:
            r = await http().get(f"{url}/job/{jid}", params={"slim": "false"}, timeout=15.0)
            full = _safe_json(r)
            import json
            timestamps = full.get("word_timestamps", [])
            ts_bytes   = json.dumps(timestamps).encode()
            ts_url     = await store().save(pid, "align_timestamps.json", ts_bytes, content_type="application/json")
            p["assets"]["timestamps_url"] = ts_url

            if analytics:
                analytics.align_completed_at = datetime.utcnow()
                analytics.align_status = "done"
                analytics.align_error = None

            logger.info(f"Pipeline {pid[:8]} Align done → {ts_url}")

        elif stage == Stage.VIDEO:
            raw_download = slim_data.get("download_url", f"/download/{jid}")
            raw_stream   = slim_data.get("stream_url",   f"/stream/{jid}")

            ffmpeg_download_url = (
                raw_download if raw_download.startswith("http")
                else f"{url}{raw_download}"
            )
            ffmpeg_stream_url = (
                raw_stream if raw_stream.startswith("http")
                else f"{url}{raw_stream}"
            )

            dataset_success = False
            video_dataset_url = None
            
            logger.info(f"Pipeline {pid[:8]}: Attempting to upload video to HF dataset...")
            
            try:
                headers = {"X-APP-KEY": APP_KEY} if APP_KEY else {}
                video_response = await http().get(
                    ffmpeg_download_url,
                    headers=headers,
                    timeout=120.0,
                    follow_redirects=True
                )
                video_response.raise_for_status()
                video_bytes = video_response.content
                
                video_dataset_url = await store().save(
                    pid,
                    "video.mp4",
                    video_bytes,
                    content_type="video/mp4"
                )
                
                dataset_success = True
                size_mb = len(video_bytes) / 1024 / 1024
                logger.info(f"Pipeline {pid[:8]} Video uploaded to dataset successfully ({size_mb:.1f}MB)")
                
            except Exception as dataset_err:
                logger.warning(f"Pipeline {pid[:8]}: Dataset upload failed: {dataset_err}. Falling back to FFmpeg URLs.")
                dataset_success = False

            if dataset_success and video_dataset_url:
                p["assets"]["video_url"] = video_dataset_url
                p["assets"]["video_download_url"] = video_dataset_url
                p["assets"]["video_stream_url"] = video_dataset_url
                if analytics:
                    analytics.video_storage_method = "dataset"
            else:
                p["assets"]["video_url"] = None
                p["assets"]["video_download_url"] = ffmpeg_download_url
                p["assets"]["video_stream_url"] = ffmpeg_stream_url
                if analytics:
                    analytics.video_storage_method = "ffmpeg_fallback"
            
            if analytics:
                analytics.video_completed_at = datetime.utcnow()
                analytics.video_status = "done"
                analytics.video_error = None
                analytics.final_status = "success"
                analytics.completed_at = datetime.utcnow()
            
        s["status"] = StageStatus.DONE
        s["completed_at"] = datetime.utcnow().isoformat()

    except httpx.TimeoutException as e:
        logger.exception(f"Finalise timeout {pid}/{stage}")
        s["status"] = StageStatus.FAILED
        s["error"] = f"Timeout during finalization: {e}"
        if analytics:
            _record_stage_failure(
                analytics, stage, url, s["backend_type"], jid,
                str(e), "finalize_timeout",
                http_status=None
            )
    except Exception as e:
        logger.exception(f"Finalise failed {pid}/{stage}")
        s["status"] = StageStatus.FAILED
        s["error"] = f"Failed to save result: {e}"
        
        if analytics:
            _record_stage_failure(
                analytics, stage, url, s["backend_type"], jid,
                str(e), "save_failed"
            )

# =============================================================================
# STAGE SUBMISSION HELPERS (with enhanced error tracking)
# =============================================================================

async def _submit_tts(p: Dict, text: str, voice: str, rate: float) -> Optional[JSONResponse]:
    pid = p["pipeline_id"]
    analytics = analytics_storage.get(pid)

    backend_url = await _pick("tts")
    if not backend_url:
        if analytics:
            _record_stage_failure(
                analytics, "tts", "N/A", "tts", "N/A",
                "All TTS spaces are busy", "all_spaces_busy"
            )
        return JSONResponse(status_code=503, content={
            "error": "all_tts_busy",
            "detail": "All 4 TTS spaces are currently busy. Try again in ~20s.",
            "retry_after": 20,
        })

    cid = _client_id(pid)
    try:
        r = await http().post(
            f"{backend_url}/tts",
            json={"text": text, "voice": voice, "rate": rate, "client_id": cid},
            timeout=HTTP_TIMEOUT,
        )
    except httpx.TimeoutException as e:
        if analytics:
            _record_stage_failure(
                analytics, "tts", backend_url, "tts", "N/A",
                f"Submission timeout: {e}", "submission_timeout"
            )
        raise HTTPException(503, {"error": "backend_timeout", "detail": str(e)})
    except httpx.RequestError as e:
        if analytics:
            _record_stage_failure(
                analytics, "tts", backend_url, "tts", "N/A",
                str(e), "request_error"
            )
        raise HTTPException(503, {"error": "backend_unreachable", "detail": str(e)})

    if r.status_code == 503:
        if analytics:
            _record_stage_failure(
                analytics, "tts", backend_url, "tts", "N/A",
                "Space became busy just before submission", "space_busy",
                http_status=503
            )
        return JSONResponse(status_code=503, content={
            "error": "all_tts_busy",
            "detail": "TTS space became busy just before submission. Retry.",
            "retry_after": 15,
        })
    if r.status_code != 200:
        error_data = _safe_json(r)
        if analytics:
            _record_stage_failure(
                analytics, "tts", backend_url, "tts", "N/A",
                str(error_data), "backend_error",
                http_status=r.status_code,
                response_body=str(error_data)[:500]
            )
        raise HTTPException(r.status_code, error_data)

    data = r.json()
    jid  = data["job_id"]

    s = p["stages"][Stage.TTS]
    s["status"] = StageStatus.RUNNING
    s["backend_url"] = backend_url
    s["backend_job_id"] = jid
    s["backend_type"] = "tts"
    s["submitted_at"] = datetime.utcnow().isoformat()
    s["error"] = None
    
    if analytics:
        analytics.tts_submitted_at = datetime.utcnow()
        analytics.tts_status = "running"
        analytics.tts_backend = backend_url
        analytics.tts_backend_type = "tts"
        analytics.tts_job_id = jid

    return None


async def _submit_align(
    p: Dict,
    language: str,
    pass_number: int,
    aligner_type: str = "mfa"
) -> str:
    pid = p["pipeline_id"]
    analytics = analytics_storage.get(pid)

    audio_url = p["assets"].get("audio_url")
    if not audio_url:
        if analytics:
            _record_stage_failure(
                analytics, "align", "N/A", aligner_type, "N/A",
                "TTS stage not completed", "tts_not_done"
            )
        raise HTTPException(400, {
            "error": "no_audio",
            "detail": "TTS stage has not completed yet. Complete TTS first.",
        })

    try:
        headers = {}
        if HF_TOKEN and "huggingface.co" in audio_url:
            headers["Authorization"] = f"Bearer {HF_TOKEN}"
        r = await http().get(audio_url, timeout=30.0, follow_redirects=True, headers=headers)
        r.raise_for_status()
        import base64
        audio_b64 = base64.b64encode(r.content).decode()
    except HTTPException:
        raise
    except Exception as e:
        if analytics:
            _record_stage_failure(
                analytics, "align", "N/A", aligner_type, "N/A",
                f"Failed to fetch audio: {e}", "audio_fetch_failed"
            )
        raise HTTPException(503, {"error": "audio_fetch_failed", "detail": str(e)})

    backend_url = None
    backend_type = None

    if aligner_type == "qwen":
        backend_url = await _pick("qwen")
        if backend_url:
            backend_type = "qwen"
        else:
            backend_url = await _pick("mfa")
            if backend_url:
                backend_type = "mfa"
                logger.info(f"Pipeline {pid[:8]}: Qwen requested but full, using MFA fallback")
    else:
        backend_url = await _pick("mfa")
        if backend_url:
            backend_type = "mfa"
        else:
            backend_url = await _pick("qwen")
            if backend_url:
                backend_type = "qwen"
                logger.info(f"Pipeline {pid[:8]}: MFA requested but full, using Qwen fallback")

    if not backend_url:
        if analytics:
            _record_stage_failure(
                analytics, "align", "N/A", aligner_type, "N/A",
                "All aligner spaces are busy", "all_spaces_busy"
            )
        raise HTTPException(503, {
            "error": "all_aligners_busy",
            "detail": "All MFA and Qwen spaces are currently busy. Try again in ~30s.",
            "retry_after": 30,
        })

    cid = _client_id(pid)
    try:
        r = await http().post(
            f"{backend_url}/align",
            json={
                "audio_base64": audio_b64,
                "text":         p["config"]["text"],
                "language":     language,
                "pass_number":  pass_number,
                "client_id":    cid,
            },
            timeout=HTTP_TIMEOUT,
        )
    except httpx.TimeoutException as e:
        if analytics:
            _record_stage_failure(
                analytics, "align", backend_url, backend_type, "N/A",
                f"Submission timeout: {e}", "submission_timeout"
            )
        raise HTTPException(503, {"error": "backend_timeout", "detail": str(e)})
    except httpx.RequestError as e:
        if analytics:
            _record_stage_failure(
                analytics, "align", backend_url, backend_type, "N/A",
                str(e), "request_error"
            )
        raise HTTPException(503, {"error": "backend_unreachable", "detail": str(e)})

    if r.status_code == 503:
        if analytics:
            _record_stage_failure(
                analytics, "align", backend_url, backend_type, "N/A",
                "Space became busy just before submission", "space_busy",
                http_status=503
            )
        raise HTTPException(503, {
            "error": "aligner_busy",
            "detail": "Aligner became busy just before submission. Retry.",
            "retry_after": 20,
        })
    if r.status_code != 200:
        error_data = _safe_json(r)
        if analytics:
            _record_stage_failure(
                analytics, "align", backend_url, backend_type, "N/A",
                str(error_data), "backend_error",
                http_status=r.status_code,
                response_body=str(error_data)[:500]
            )
        raise HTTPException(r.status_code, error_data)

    data = r.json()
    jid  = data["job_id"]

    s = p["stages"][Stage.ALIGN]
    s["status"] = StageStatus.RUNNING
    s["backend_url"] = backend_url
    s["backend_job_id"] = jid
    s["backend_type"] = backend_type
    s["submitted_at"] = datetime.utcnow().isoformat()
    s["error"] = None
    
    if analytics:
        analytics.align_submitted_at = datetime.utcnow()
        analytics.align_status = "running"
        analytics.align_backend = backend_url
        analytics.align_backend_type = backend_type
        analytics.align_job_id = jid

    logger.info(f"Pipeline {pid[:8]}: Alignment submitted to {backend_type.upper()} ({backend_url})")
    return backend_type


async def _submit_video(p: Dict, subtitles_ass: str, background: str, duration: Optional[float]) -> Optional[JSONResponse]:
    pid = p["pipeline_id"]
    analytics = analytics_storage.get(pid)

    if not APP_KEY:
        if analytics:
            _record_stage_failure(
                analytics, "video", "N/A", "ffmpeg", "N/A",
                "APP_KEY not configured", "config_error"
            )
        raise HTTPException(500, {
            "error": "controller_misconfigured",
            "detail": "APP_KEY secret not set on controller space.",
        })

    audio_url = p["assets"].get("audio_url")
    if not audio_url:
        if analytics:
            _record_stage_failure(
                analytics, "video", "N/A", "ffmpeg", "N/A",
                "TTS not completed", "tts_not_done"
            )
        raise HTTPException(400, {"error": "no_audio", "detail": "TTS not completed yet."})

    try:
        headers = {}
        if HF_TOKEN and "huggingface.co" in audio_url:
            headers["Authorization"] = f"Bearer {HF_TOKEN}"
        r = await http().get(audio_url, timeout=30.0, follow_redirects=True, headers=headers)
        r.raise_for_status()
        import base64
        audio_b64 = base64.b64encode(r.content).decode()
    except HTTPException:
        raise
    except Exception as e:
        if analytics:
            _record_stage_failure(
                analytics, "video", "N/A", "ffmpeg", "N/A",
                f"Failed to fetch audio: {e}", "audio_fetch_failed"
            )
        raise HTTPException(503, {"error": "audio_fetch_failed", "detail": str(e)})

    backend_url = await _pick("ffmpeg")
    if not backend_url:
        if analytics:
            _record_stage_failure(
                analytics, "video", "N/A", "ffmpeg", "N/A",
                "All video spaces are busy", "all_spaces_busy"
            )
        return JSONResponse(status_code=503, content={
            "error": "all_video_busy",
            "detail": "All video spaces are busy. Try again in ~2 min.",
            "retry_after": 120,
        })

    cid = _client_id(pid)
    try:
        r = await http().post(
            f"{backend_url}/generate",
            json={
                "audio_base64":  audio_b64,
                "subtitles_ass": subtitles_ass,
                "background":    background,
                "duration":      duration,
            },
            headers={"X-APP-KEY": APP_KEY, "X-Client-ID": cid},
            timeout=30.0,
        )
    except httpx.TimeoutException as e:
        if analytics:
            _record_stage_failure(
                analytics, "video", backend_url, "ffmpeg", "N/A",
                f"Submission timeout: {e}", "submission_timeout"
            )
        raise HTTPException(503, {"error": "backend_timeout", "detail": str(e)})
    except httpx.RequestError as e:
        if analytics:
            _record_stage_failure(
                analytics, "video", backend_url, "ffmpeg", "N/A",
                str(e), "request_error"
            )
        raise HTTPException(503, {"error": "backend_unreachable", "detail": str(e)})

    if r.status_code == 503:
        if analytics:
            _record_stage_failure(
                analytics, "video", backend_url, "ffmpeg", "N/A",
                "Space became busy just before submission", "space_busy",
                http_status=503
            )
        return JSONResponse(status_code=503, content={
            "error": "all_video_busy",
            "detail": "Video space became busy just before submission. Retry.",
            "retry_after": 60,
        })
    if r.status_code not in (200, 201):
        error_data = _safe_json(r)
        if analytics:
            _record_stage_failure(
                analytics, "video", backend_url, "ffmpeg", "N/A",
                str(error_data), "backend_error",
                http_status=r.status_code,
                response_body=str(error_data)[:500]
            )
        raise HTTPException(r.status_code, error_data)

    data = r.json()
    jid  = data["job_id"]

    s = p["stages"][Stage.VIDEO]
    s["status"] = StageStatus.RUNNING
    s["backend_url"] = backend_url
    s["backend_job_id"] = jid
    s["backend_type"] = "ffmpeg"
    s["submitted_at"] = datetime.utcnow().isoformat()
    s["error"] = None
    
    if analytics:
        analytics.video_submitted_at = datetime.utcnow()
        analytics.video_status = "running"
        analytics.video_backend = backend_url
        analytics.video_backend_type = "ffmpeg"
        analytics.video_job_id = jid

    return None

# =============================================================================
# PIPELINE VIEW HELPER
# =============================================================================

def _pipeline_view(p: Dict) -> Dict:
    stages = {}
    for stage_name, s in p["stages"].items():
        stage_out = {
            "status":       s["status"],
            "submitted_at": s["submitted_at"],
            "completed_at": s["completed_at"],
            "error":        s["error"],
        }
        if s["status"] == StageStatus.RUNNING:
            stage_out["backend_url"]    = s.get("backend_url")
            stage_out["backend_job_id"] = s.get("backend_job_id")
            stage_out["backend_type"]   = s.get("backend_type")
            stage_out["progress"]              = s.get("progress", 0)
            stage_out["chunks_done"]           = s.get("chunks_done", 0)
            stage_out["chunks_total"]          = s.get("chunks_total", 0)
            stage_out["elapsed_s"]             = s.get("elapsed_s")
            stage_out["estimated_remaining_s"] = s.get("estimated_remaining_s")
            stage_out["message"]               = s.get("message", "")
            if s.get("encode_stats"):
                stage_out["encode_stats"]      = s["encode_stats"]
        stages[stage_name] = stage_out

    return {
        "pipeline_id": p["pipeline_id"],
        "created_at":  p["created_at"],
        "finalized":   p.get("finalized", False),
        "stages":      stages,
        "assets": {
            "audio_url":          p["assets"]["audio_url"],
            "timestamps_url":     p["assets"]["timestamps_url"],
            "video_url":          p["assets"]["video_url"],
            "video_download_url": p["assets"].get("video_download_url"),
            "video_stream_url":   p["assets"].get("video_stream_url"),
        },
        "next_actions": _next_actions(p),
    }


def _next_actions(p: Dict) -> list:
    actions = []
    tts   = p["stages"][Stage.TTS]["status"]
    align = p["stages"][Stage.ALIGN]["status"]
    video = p["stages"][Stage.VIDEO]["status"]

    if tts == StageStatus.DONE:
        actions.append("rerun_tts")
        if align in (StageStatus.IDLE, StageStatus.FAILED):
            actions.append("submit_align")
    if tts == StageStatus.FAILED:
        actions.append("rerun_tts")
    if align == StageStatus.DONE:
        actions.append("rerun_align")
        if video in (StageStatus.IDLE, StageStatus.FAILED):
            actions.append("submit_video")
    if align == StageStatus.FAILED:
        actions.append("rerun_align")
    if video == StageStatus.DONE:
        actions.append("download_video")
    if video == StageStatus.FAILED:
        actions.append("rerun_video")

    return actions

# =============================================================================
# SESSION CLEANUP
# =============================================================================

async def _cleanup_loop():
    while True:
        await asyncio.sleep(120)
        cutoff = datetime.utcnow() - timedelta(seconds=SESSION_TTL)
        expired = [
            pid for pid, p in list(pipelines.items())
            if datetime.fromisoformat(p["last_active"]) < cutoff
        ]
        for pid in expired:
            pipelines.pop(pid, None)
            pipeline_heartbeats.pop(pid, None)
        if expired:
            logger.info(f"Purged {len(expired)} expired pipelines from memory.")

# =============================================================================
# DATASET HEALTH CHECK
# =============================================================================

async def _check_dataset_reachability(repo: str, name: str) -> bool:
    """Check if a dataset repository is reachable and writable."""
    if not repo:
        logger.warning(f"Dataset {name}: not configured (empty repo name)")
        return False
    
    try:
        from huggingface_hub import HfApi
        import io
        
        api = HfApi(token=HF_TOKEN)
        
        try:
            info = api.repo_info(repo_id=repo, repo_type="dataset")
            logger.info(f"Dataset {name} ({repo}): ✓ readable - found {info.id}")
        except Exception as e:
            logger.error(f"Dataset {name} ({repo}): ✗ NOT readable - {e}")
            return False
        
        test_path = "_health_check.txt"
        test_data = b"health check"
        
        try:
            api.upload_file(
                path_or_fileobj=io.BytesIO(test_data),
                path_in_repo=test_path,
                repo_id=repo,
                repo_type="dataset",
                commit_message="Health check (will be deleted)",
            )
            logger.info(f"Dataset {name} ({repo}): ✓ writable - test upload succeeded")
            
            try:
                api.delete_file(
                    path_in_repo=test_path,
                    repo_id=repo,
                    repo_type="dataset",
                    commit_message="Health check cleanup",
                )
                logger.info(f"Dataset {name} ({repo}): ✓ test file cleaned up")
            except Exception as cleanup_err:
                logger.warning(f"Dataset {name} ({repo}): test file cleanup failed - {cleanup_err}")
            
            return True
            
        except Exception as write_err:
            logger.error(f"Dataset {name} ({repo}): ✗ NOT writable - {write_err}")
            return False
            
    except Exception as e:
        logger.error(f"Dataset {name} ({repo}): ✗ health check failed - {e}")
        return False

# =============================================================================
# FRONTEND HEARTBEAT WATCHDOG
# =============================================================================

async def _frontend_heartbeat_watchdog():
    while True:
        await asyncio.sleep(15)
        now = datetime.utcnow()

        for pid, p in list(pipelines.items()):

            if p.get("finalized"):
                continue

            last_hb = pipeline_heartbeats.get(pid)
            if last_hb is None:
                last_hb = datetime.fromisoformat(p["created_at"])

            silence = (now - last_hb).total_seconds()

            if silence >= FRONTEND_HEARTBEAT_GRACE + 200:
                logger.warning(f"Pipeline {pid[:8]} silent {silence:.0f}s — permanent abandon")
                try:
                    await store().delete_pipeline(pid)
                except Exception as e:
                    logger.error(f"Failed to delete dataset assets for {pid[:8]}: {e}")
                pipelines.pop(pid, None)
                pipeline_heartbeats.pop(pid, None)
                continue

            elif silence >= FRONTEND_HEARTBEAT_GRACE:
                running_stage = next(
                    (name for name, s in p["stages"].items() if s["status"] == StageStatus.RUNNING),
                    None
                )
                if not running_stage:
                    continue

                s            = p["stages"][running_stage]
                url          = s.get("backend_url")
                jid          = s.get("backend_job_id")
                backend_type = s.get("backend_type")

                logger.warning(f"Pipeline {pid[:8]} silent {silence:.0f}s — cancelling {running_stage} job {jid}")

                if url and jid:
                    try:
                        if backend_type == "ffmpeg":
                            await http().delete(f"{url}/job/{jid}", headers={"X-APP-KEY": APP_KEY}, timeout=10.0)
                        else:
                            await http().post(f"{url}/cancel/{jid}", json={"client_id": _client_id(pid)}, timeout=10.0)
                        logger.info(f"Cancelled {running_stage} job {jid} on {url}")
                    except Exception as e:
                        logger.warning(f"Cancel request failed for {pid[:8]}: {e}")

                s["status"] = StageStatus.FAILED
                s["error"]  = "Cancelled — client disconnected"
                
                # Update analytics
                analytics = analytics_storage.get(pid)
                if analytics:
                    _record_stage_failure(
                        analytics, running_stage, url or "N/A", backend_type or "unknown", jid or "N/A",
                        "Cancelled — client disconnected", "client_disconnected"
                    )

# =============================================================================
# STARTUP / SHUTDOWN
# =============================================================================

@app.on_event("startup")
async def startup():
    global _http, _store

    if ADMIN_KEY:
        logger.info(f"✓ ADMIN_KEY configured (rate limit bypass active for key holders)")
    else:
        logger.info("ℹ ADMIN_KEY not configured (rate limiting active for all users)")

    logger.info("=" * 80)
    logger.info("DATASET REACHABILITY CHECK (at space build/startup)")
    logger.info("=" * 80)
    
    if HF_TOKEN:
        logger.info(f"✓ HF_TOKEN: configured (length={len(HF_TOKEN)})")
    else:
        logger.error("✗ HF_TOKEN: NOT configured — datasets will not work!")
    
    if HF_DATASET:
        logger.info(f"✓ HF_DATASET (primary) configured: {HF_DATASET}")
        dataset1_ok = await _check_dataset_reachability(HF_DATASET, "PRIMARY")
    else:
        logger.error("✗ HF_DATASET (primary): NOT configured — no primary dataset!")
        dataset1_ok = False
    
    if HF_DATASET_2:
        logger.info(f"✓ HF_DATASET_2 (secondary) configured: {HF_DATASET_2}")
        dataset2_ok = await _check_dataset_reachability(HF_DATASET_2, "SECONDARY")
    else:
        logger.warning("⚠ HF_DATASET_2 (secondary): NOT configured (will run in single-dataset mode)")
        dataset2_ok = False
    
    logger.info("=" * 80)
    logger.info("DATASET STATUS SUMMARY:")
    logger.info("-" * 80)
    logger.info(f"PRIMARY dataset ({HF_DATASET or 'NOT SET'}): {'✓ READY' if dataset1_ok else '✗ UNAVAILABLE'}")
    if HF_DATASET_2:
        logger.info(f"SECONDARY dataset ({HF_DATASET_2}): {'✓ READY' if dataset2_ok else '✗ UNAVAILABLE'}")
        logger.info("-" * 80)
        if dataset1_ok and dataset2_ok:
            logger.info("MODE: ✓ DUAL-DATASET — Both datasets are operational")
        elif dataset1_ok:
            logger.warning("MODE: ⚠ DUAL-DATASET (DEGRADED) — Only primary dataset is operational")
        elif dataset2_ok:
            logger.warning("MODE: ⚠ DUAL-DATASET (DEGRADED) — Only secondary dataset is operational")
        else:
            logger.error("MODE: ✗ DUAL-DATASET (FAILED) — Neither dataset is operational!")
    else:
        logger.info("-" * 80)
        logger.info("MODE: ✓ SINGLE-DATASET — Only primary dataset configured")
    logger.info("=" * 80)
    
    logger.info("Initializing HTTP client and DatasetStore...")
    _http  = httpx.AsyncClient(timeout=HTTP_TIMEOUT)
    _store = DatasetStore(hf_token=HF_TOKEN, dataset_repo=HF_DATASET, dataset_repo_2=HF_DATASET_2)

    init_tasks = [
        _check_one(url, stype)
        for stype, urls in ALL_SPACES.items()
        for url in urls
    ]
    results = await asyncio.gather(*init_tasks, return_exceptions=True)
    for r in results:
        if isinstance(r, dict):
            status_cache[r["url"]] = r

    asyncio.create_task(_status_loop())
    asyncio.create_task(_cleanup_loop())
    asyncio.create_task(_frontend_heartbeat_watchdog())
    asyncio.create_task(_rate_limit_cleanup_loop())
    
    logger.info("=" * 80)
    logger.info(f"RATE LIMITING: {RATE_LIMIT_MAX_PER_HOUR} pipelines per IP per {RATE_LIMIT_WINDOW_HOURS}h")
    if ADMIN_KEY:
        logger.info("ADMIN BYPASS: Active — admin key holders bypass rate limits")
    logger.info("ANALYTICS v1.8: Enhanced tracking with exact backend URLs and failure details")
    logger.info("=" * 80)
    logger.info("ArchNemix Controller v1.8 ready (enhanced debugging + backend failure tracking).")


@app.on_event("shutdown")
async def shutdown():
    if _http:
        await _http.aclose()

# =============================================================================
# ENDPOINTS
# =============================================================================

@app.get("/")
async def root():
    return {
        "name":    "ArchNemix Controller",
        "version": "1.8.0",
        "endpoints": {
            "POST /pipeline/start":            "Start new pipeline (rate limited: 10/hour per IP, admin key bypass available)",
            "GET  /pipeline/{id}":             "Poll pipeline state + per-stage status",
            "POST /pipeline/{id}/rerun/tts":   "Re-run TTS only (new text/voice/rate optional)",
            "POST /pipeline/{id}/align":       "Submit alignment (uses completed TTS audio)",
            "POST /pipeline/{id}/rerun/align": "Re-run alignment only",
            "POST /pipeline/{id}/video":       "Submit video (uses completed TTS audio + subtitles_ass from frontend)",
            "POST /pipeline/{id}/rerun/video": "Re-run video only",
            "POST /pipeline/{id}/finalize":    "Mark pipeline complete — deletes dataset intermediates",
            "GET  /status":                    "Live slot availability for all spaces",
            "GET  /capacity":                  "Current pipeline capacity usage",
            "POST /pipeline/{id}/heartbeat":   "Keep pipeline alive (prevents auto-cancel)",
            "POST /pipeline/{id}/cancel/{stage}": "Cancel a running stage",
            "GET  /debug/dataset-routing/{id}":   "Debug dataset routing logic",
            "GET  /debug/rate-limit-status":      "Check rate limit status for current IP",
            # Admin endpoints (require X-Admin-Key header)
            "GET  /admin/analytics":           "📊 Comprehensive analytics summary with backend stats",
            "GET  /admin/active-jobs":         "🔄 List all currently running jobs with details",
            "GET  /admin/failures":            "❌ Detailed failure breakdown with exact backend URLs",
            "GET  /admin/rate-limit-status":   "⏱️ Rate limit status for all IPs",
            "GET  /admin/pipeline/{id}/analytics": "🔍 Analytics for specific pipeline with failure details",
            "GET  /admin/clear-analytics":     "🗑️ Clear all analytics data",
        },
        "rate_limit": f"{RATE_LIMIT_MAX_PER_HOUR} pipelines per {RATE_LIMIT_WINDOW_HOURS} hour(s) per IP",
        "admin_bypass": bool(ADMIN_KEY),
        "analytics_enabled": True,
        "analytics_version": "1.8",
        "video_storage": "Dataset first (permanent), fallback to FFmpeg /tmp URLs (1-hour TTL) if upload fails",
    }


@app.post("/pipeline/start")
async def start_pipeline(req: PipelineStartRequest, request: Request):
    client_ip = _get_client_ip(request)
    is_admin = _is_admin_request(request)
    anonymized_ip = _anonymize_ip(client_ip)
    
    rate_limited = False
    if not is_admin:
        allowed, current_count, retry_after = _check_rate_limit(client_ip)
        if not allowed:
            rate_limited = True
            logger.warning(f"Rate limit exceeded for IP {anonymized_ip}")
            return JSONResponse(status_code=429, content={
                "error": "rate_limit_exceeded",
                "detail": f"You have reached the limit of {RATE_LIMIT_MAX_PER_HOUR} videos per hour.",
                "retry_after": retry_after,
            })
    
    active_count = sum(
        1 for p in pipelines.values()
        if any(
            p["stages"][s]["status"] == StageStatus.RUNNING
            for s in (Stage.TTS, Stage.ALIGN, Stage.VIDEO)
        )
    )
    if active_count >= 8:
        return JSONResponse(status_code=503, content={
            "error": "at_capacity",
            "detail": "All slots are currently busy. Try again in ~2 minutes.",
            "retry_after": 120,
        })
    
    p = _new_pipeline(req)
    pid = p["pipeline_id"]
    pipelines[pid] = p
    
    analytics = JobAnalytics(
        pipeline_id=pid,
        created_at=datetime.utcnow(),
        user_ip=anonymized_ip,
        is_admin=is_admin,
        rate_limited=rate_limited,
    )
    analytics_storage[pid] = analytics
    
    if not is_admin and not rate_limited:
        _record_request(client_ip)
    
    err = await _submit_tts(p, req.text, req.voice, req.rate)
    if err:
        analytics.tts_status = "failed"
        analytics.tts_error = "All TTS spaces busy at submission"
        analytics.final_status = "failed"
        analytics.completed_at = datetime.utcnow()
        _record_stage_failure(
            analytics, "tts", "N/A", "tts", "N/A",
            "All TTS spaces busy at submission", "all_spaces_busy"
        )
        
        p["stages"][Stage.TTS]["status"] = StageStatus.FAILED
        p["stages"][Stage.TTS]["error"] = "All TTS spaces busy at submission time."
        return JSONResponse(
            status_code=503,
            content={
                "pipeline_id": pid,
                "error": "all_tts_busy",
                "detail": "All TTS spaces busy at submission time.",
                "retry_after": 20,
                "message": f"Pipeline created but TTS could not start. Retry with POST /pipeline/{pid}/rerun/tts",
            },
            headers={"X-Pipeline-ID": pid},
        )
    
    logger.info(
        f"Pipeline {pid[:8]} started — TTS job {p['stages'][Stage.TTS]['backend_job_id']} "
        f"(user: {'admin' if is_admin else 'normal'}, ip: {anonymized_ip})"
    )
    
    return JSONResponse(
        {
            "pipeline_id": pid,
            "status": "tts_running",
            "poll_url": f"/pipeline/{pid}",
            "message": "TTS job submitted. Poll /pipeline/{id} every 2s.",
        },
        headers={"X-Pipeline-ID": pid},
    )


@app.get("/pipeline/{pipeline_id}")
async def get_pipeline(pipeline_id: str):
    p = _pipeline_or_404(pipeline_id)
    for stage in (Stage.TTS, Stage.ALIGN, Stage.VIDEO):
        await _poll_backend_stage(p, stage)
    return _pipeline_view(p)


@app.post("/pipeline/{pipeline_id}/rerun/tts")
async def rerun_tts(pipeline_id: str, req: RerunTTSRequest):
    p = _pipeline_or_404(pipeline_id)

    if p["stages"][Stage.TTS]["status"] == StageStatus.RUNNING:
        raise HTTPException(400, {
            "error": "tts_already_running",
            "detail": "TTS is already running. Wait for it to complete or fail first.",
        })

    if req.text is not None: p["config"]["text"] = req.text
    if req.voice is not None: p["config"]["voice"] = req.voice
    if req.rate is not None: p["config"]["rate"] = req.rate

    p["stages"][Stage.ALIGN] = _blank_stage()
    p["stages"][Stage.VIDEO] = _blank_stage()
    p["assets"]["timestamps_url"] = None
    p["assets"]["video_url"] = None
    p["assets"]["video_download_url"] = None
    p["assets"]["video_stream_url"] = None

    err = await _submit_tts(p, p["config"]["text"], p["config"]["voice"], p["config"]["rate"])
    if err:
        return err

    return JSONResponse({
        "pipeline_id": pipeline_id,
        "status": "tts_running",
        "message": "TTS re-submitted. Poll /pipeline/{id} every 2s.",
    })


@app.post("/pipeline/{pipeline_id}/align", response_model=None)
async def submit_align(pipeline_id: str, req: AlignSubmitRequest):
    p = _pipeline_or_404(pipeline_id)

    if p["stages"][Stage.TTS]["status"] != StageStatus.DONE:
        raise HTTPException(400, {
            "error": "tts_not_done",
            "detail": "TTS must complete successfully before alignment.",
        })
    if p["stages"][Stage.ALIGN]["status"] == StageStatus.RUNNING:
        raise HTTPException(400, {
            "error": "align_already_running",
            "detail": "Alignment is already running.",
        })

    language = req.language or p["config"]["language"]
    pass_number = req.pass_number or p["config"]["pass_number"]
    aligner_type = req.aligner_type or p["config"].get("aligner_type", "mfa")

    p["config"]["aligner_type"] = aligner_type

    backend_type = await _submit_align(p, language, pass_number, aligner_type)

    return JSONResponse({
        "pipeline_id": pipeline_id,
        "status": "align_running",
        "aligner_used": backend_type,
        "message": f"{backend_type.upper()} alignment submitted. Poll /pipeline/{{id}} every 2s.",
    })


@app.post("/pipeline/{pipeline_id}/rerun/align", response_model=None)
async def rerun_align(pipeline_id: str, req: AlignSubmitRequest):
    p = _pipeline_or_404(pipeline_id)

    if p["stages"][Stage.TTS]["status"] != StageStatus.DONE:
        raise HTTPException(400, {"error": "tts_not_done", "detail": "TTS must be done first."})
    if p["stages"][Stage.ALIGN]["status"] == StageStatus.RUNNING:
        raise HTTPException(400, {"error": "align_already_running", "detail": "Alignment is already running."})

    if req.language is not None: p["config"]["language"] = req.language
    if req.pass_number is not None: p["config"]["pass_number"] = req.pass_number
    if req.aligner_type is not None: p["config"]["aligner_type"] = req.aligner_type

    p["stages"][Stage.VIDEO] = _blank_stage()
    p["assets"]["video_url"] = None
    p["assets"]["video_download_url"] = None
    p["assets"]["video_stream_url"] = None

    aligner_type = p["config"].get("aligner_type", "mfa")
    backend_type = await _submit_align(p, p["config"]["language"], p["config"]["pass_number"], aligner_type)

    return JSONResponse({
        "pipeline_id": pipeline_id,
        "status": "align_running",
        "aligner_used": backend_type,
        "message": f"{backend_type.upper()} alignment re-submitted. Poll /pipeline/{{id}} every 2s.",
    })


@app.post("/pipeline/{pipeline_id}/video")
async def submit_video(pipeline_id: str, req: VideoSubmitRequest):
    p = _pipeline_or_404(pipeline_id)

    if p["stages"][Stage.TTS]["status"] != StageStatus.DONE:
        raise HTTPException(400, {"error": "tts_not_done", "detail": "TTS must be done first."})
    if p["stages"][Stage.VIDEO]["status"] == StageStatus.RUNNING:
        raise HTTPException(400, {"error": "video_already_running", "detail": "Video is already running."})

    background = req.background or p["config"]["background"]
    duration = req.duration or p["config"]["duration"]

    err = await _submit_video(p, req.subtitles_ass, background, duration)
    if err:
        return err

    return JSONResponse({
        "pipeline_id": pipeline_id,
        "status": "video_running",
        "message": "Video job submitted. Poll /pipeline/{id} every 5s.",
    })


@app.post("/pipeline/{pipeline_id}/rerun/video")
async def rerun_video(pipeline_id: str, req: VideoSubmitRequest):
    p = _pipeline_or_404(pipeline_id)

    if p["stages"][Stage.TTS]["status"] != StageStatus.DONE:
        raise HTTPException(400, {"error": "tts_not_done", "detail": "TTS must be done first."})
    if p["stages"][Stage.VIDEO]["status"] == StageStatus.RUNNING:
        raise HTTPException(400, {"error": "video_already_running", "detail": "Video is already running."})

    if req.background is not None: p["config"]["background"] = req.background
    if req.duration is not None: p["config"]["duration"] = req.duration

    p["assets"]["video_url"] = None
    p["assets"]["video_download_url"] = None
    p["assets"]["video_stream_url"] = None

    err = await _submit_video(p, req.subtitles_ass, p["config"]["background"], p["config"]["duration"])
    if err:
        return err

    return JSONResponse({
        "pipeline_id": pipeline_id,
        "status": "video_running",
        "message": "Video re-submitted. Poll /pipeline/{id} every 5s.",
    })


@app.post("/pipeline/{pipeline_id}/finalize")
async def finalize_pipeline(pipeline_id: str):
    p = pipelines.get(pipeline_id)
    if not p:
        return {"ok": True, "pipeline_id": pipeline_id, "note": "pipeline_not_in_memory"}

    if p.get("finalized"):
        return {"ok": True, "pipeline_id": pipeline_id, "note": "already_finalized"}

    if p["stages"][Stage.VIDEO]["status"] != StageStatus.DONE:
        raise HTTPException(400, {
            "error": "video_not_done",
            "detail": "Cannot finalize a pipeline whose video stage has not completed.",
        })

    p["finalized"] = True
    pipeline_heartbeats.pop(pipeline_id, None)

    asyncio.create_task(_run_delete_intermediates(pipeline_id))

    logger.info(f"Pipeline {pipeline_id[:8]} finalized (video kept in dataset).")

    return {
        "ok": True,
        "pipeline_id": pipeline_id,
        "video_url": p["assets"].get("video_url"),
        "video_download_url": p["assets"].get("video_download_url"),
        "video_stream_url": p["assets"].get("video_stream_url"),
    }


async def _run_delete_intermediates(pipeline_id: str):
    try:
        await store().delete_intermediates(pipeline_id)
    except Exception as e:
        logger.error(f"delete_intermediates failed for {pipeline_id[:8]}: {e}")


@app.get("/status")
async def get_status():
    summary = _status_summary()
    
    return {
        "tts": {
            **summary["tts"],
            "description": "Text-to-Speech spaces (2 slots each = 8 total)",
        },
        "mfa": {
            **summary["mfa"],
            "description": "Montreal Forced Aligner (fine-tune, precise English)",
        },
        "qwen": {
            **summary["qwen"],
            "description": "Qwen Neural Aligner (fast, 2-pass refinement)",
        },
        "aligners": {
            **summary["aligners"],
            "description": "Combined aligners (MFA + Qwen)",
        },
        "ffmpeg": {
            **summary["ffmpeg"],
            "description": "Video encoding spaces (2 slots each = 4 total)",
        },
    }


@app.post("/pipeline/{pipeline_id}/heartbeat")
async def pipeline_heartbeat(pipeline_id: str):
    p = _touch(pipeline_id)
    if not p:
        raise HTTPException(404, {"error": "pipeline_not_found"})

    pipeline_heartbeats[pipeline_id] = datetime.utcnow()

    stages = {name: s["status"] for name, s in p["stages"].items()}
    return {"pipeline_id": pipeline_id, "acknowledged": True, "stages": stages}


@app.get("/debug/dataset-routing/{pipeline_id}")
async def debug_dataset_routing(pipeline_id: str):
    """Test which dataset a pipeline ID would route to"""
    if not _store:
        return {"error": "DatasetStore not initialized"}
    
    first_hex = pipeline_id[0]
    hex_value = int(first_hex, 16)
    is_odd = hex_value % 2 == 1
    
    repo_1 = _store.repo_1
    repo_2 = _store.repo_2
    is_dual = _store._dual
    
    if is_dual:
        chosen_repo = repo_2 if is_odd else repo_1
        mode = "DUAL-DATASET"
    else:
        chosen_repo = repo_1
        mode = "SINGLE-DATASET"
    
    return {
        "pipeline_id": pipeline_id,
        "mode": mode,
        "first_char": first_hex,
        "hex_value": hex_value,
        "is_odd": is_odd,
        "repo_1": repo_1,
        "repo_2": repo_2 if repo_2 else "NOT CONFIGURED",
        "chosen_repo": chosen_repo,
        "routing": "SECONDARY (repo_2)" if (is_dual and is_odd) else "PRIMARY (repo_1)"
    }


@app.get("/capacity")
async def get_capacity():
    active_pipelines = [
        {
            "pipeline_id": p["pipeline_id"],
            "stage": next(
                (s for s in (Stage.TTS, Stage.ALIGN, Stage.VIDEO)
                 if p["stages"][s]["status"] == StageStatus.RUNNING),
                "idle"
            ),
            "created_at": p["created_at"],
        }
        for p in pipelines.values()
        if any(
            p["stages"][s]["status"] == StageStatus.RUNNING
            for s in (Stage.TTS, Stage.ALIGN, Stage.VIDEO)
        )
    ]

    waiting = [
        p for p in pipelines.values()
        if all(
            p["stages"][s]["status"] != StageStatus.RUNNING
            for s in (Stage.TTS, Stage.ALIGN, Stage.VIDEO)
        )
        and any(
            p["stages"][s]["status"] == StageStatus.IDLE
            for s in (Stage.ALIGN, Stage.VIDEO)
        )
        and p["stages"][Stage.TTS]["status"] == StageStatus.DONE
    ]

    return {
        "active": len(active_pipelines),
        "cap": 8,
        "slots_free": max(0, 8 - len(active_pipelines)),
        "at_capacity": len(active_pipelines) >= 8,
        "pipelines": active_pipelines,
        "waiting_count": len(waiting),
        "total_in_memory": len(pipelines),
    }


@app.get("/debug/rate-limit-status")
async def debug_rate_limit_status(request: Request):
    """Debug endpoint to check rate limit status for requesting IP"""
    client_ip = _get_client_ip(request)
    is_admin = _is_admin_request(request)
    allowed, current_count, retry_after = _check_rate_limit(client_ip)
    
    timestamps = rate_limit_storage.get(client_ip, [])
    
    return {
        "ip": client_ip if not is_admin else "admin",
        "is_admin": is_admin,
        "allowed": allowed,
        "current_usage": current_count,
        "limit": RATE_LIMIT_MAX_PER_HOUR,
        "window_hours": RATE_LIMIT_WINDOW_HOURS,
        "retry_after_seconds": retry_after if not allowed else 0,
        "recent_requests": [ts.isoformat() for ts in sorted(timestamps, reverse=True)],
        "total_ips_tracked": len(rate_limit_storage),
    }


@app.post("/pipeline/{pipeline_id}/cancel/{stage}")
async def cancel_stage(pipeline_id: str, stage: str, request: Request):
    if stage not in (Stage.TTS, Stage.ALIGN, Stage.VIDEO):
        raise HTTPException(400, {
            "error": "invalid_stage",
            "detail": f"Stage must be one of: tts, align, video",
        })

    p = _pipeline_or_404(pipeline_id)
    s = p["stages"][stage]
    analytics = analytics_storage.get(pipeline_id)

    if s["status"] != StageStatus.RUNNING:
        raise HTTPException(400, {
            "error": "stage_not_running",
            "detail": f"Stage '{stage}' is not currently running (status: {s['status']}). Nothing to cancel.",
        })

    url = s.get("backend_url")
    jid = s.get("backend_job_id")
    btype = s.get("backend_type")

    if url and jid:
        try:
            if btype == "ffmpeg":
                await http().delete(
                    f"{url}/job/{jid}",
                    headers={"X-APP-KEY": APP_KEY},
                    timeout=10.0,
                )
            else:
                await http().post(
                    f"{url}/cancel/{jid}",
                    json={"client_id": _client_id(pipeline_id)},
                    timeout=10.0,
                )
            logger.info(f"Pipeline {pipeline_id[:8]}: user cancelled {stage} job {jid} on {url}")
        except Exception as e:
            logger.warning(f"Pipeline {pipeline_id[:8]}: cancel request to backend failed ({e}) — marking failed anyway")

    s["status"] = StageStatus.FAILED
    s["error"] = "Cancelled by user"
    
    if analytics:
        _record_stage_failure(
            analytics, stage, url or "N/A", btype or "unknown", jid or "N/A",
            "Cancelled by user", "user_cancelled"
        )

    return {
        "ok": True,
        "pipeline_id": pipeline_id,
        "stage": stage,
        "job_id": jid,
        "backend_url": url,
    }

# =============================================================================
# ENHANCED ADMIN ANALYTICS ENDPOINTS
# =============================================================================

@app.get("/admin/analytics")
async def admin_analytics(request: Request):
    """Get comprehensive analytics summary with backend stats"""
    if not _is_admin_request(request):
        raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
    
    return _get_analytics_summary()

@app.get("/admin/active-jobs")
async def admin_active_jobs(request: Request):
    """Get all currently running jobs with details"""
    if not _is_admin_request(request):
        raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
    
    active_jobs = _get_active_jobs()
    return {
        "active_jobs": active_jobs,
        "total_active": len(active_jobs),
        "capacity": 8,
        "slots_available": max(0, 8 - len(active_jobs)),
    }

@app.get("/admin/pipeline/{pipeline_id}/analytics")
async def admin_pipeline_analytics(pipeline_id: str, request: Request):
    """Get detailed analytics for a specific pipeline with failure details"""
    if not _is_admin_request(request):
        raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
    
    analytics = analytics_storage.get(pipeline_id)
    if not analytics:
        raise HTTPException(404, {"error": "pipeline_not_found", "detail": "Pipeline not found in analytics"})
    
    return analytics.to_dict()

@app.get("/admin/failures")
async def admin_failures(request: Request):
    """Get detailed failure breakdown with exact backend URLs"""
    if not _is_admin_request(request):
        raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
    
    failures = []
    for pid, analytics in analytics_storage.items():
        if analytics.final_status == "failed":
            # Determine which stage failed and get its failure detail
            failed_stage = None
            failure_detail = None
            
            if analytics.tts_status == "failed":
                failed_stage = "tts"
                failure_detail = analytics.tts_failure_detail
            elif analytics.align_status == "failed":
                failed_stage = "align"
                failure_detail = analytics.align_failure_detail
            elif analytics.video_status == "failed":
                failed_stage = "video"
                failure_detail = analytics.video_failure_detail
            
            failures.append({
                "pipeline_id": pid,
                "created_at": analytics.created_at.isoformat(),
                "user_ip": analytics.user_ip,
                "is_admin": analytics.is_admin,
                "failed_stage": failed_stage,
                "failure": {
                    "backend_url": failure_detail.backend_url if failure_detail else None,
                    "backend_type": failure_detail.backend_type if failure_detail else None,
                    "job_id": failure_detail.job_id if failure_detail else None,
                    "error_message": failure_detail.error_message if failure_detail else None,
                    "error_type": failure_detail.error_type if failure_detail else None,
                    "failed_at": failure_detail.failed_at.isoformat() if failure_detail else None,
                    "http_status": failure_detail.http_status if failure_detail else None,
                },
                "stage_errors": {
                    "tts_error": analytics.tts_error,
                    "align_error": analytics.align_error,
                    "video_error": analytics.video_error,
                }
            })
    
    return {
        "total_failures": len(failures),
        "failures": failures,
        "failure_stats_by_stage": dict(stage_failure_stats),
        "error_type_breakdown": {
            stage: dict(errors) for stage, errors in stage_failure_stats.items()
        }
    }

@app.get("/admin/rate-limit-status")
async def admin_rate_limit_status(request: Request):
    """Get rate limit status for all IPs"""
    if not _is_admin_request(request):
        raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
    
    ip_status = []
    for ip, timestamps in rate_limit_storage.items():
        allowed, current_count, retry_after = _check_rate_limit(ip)
        ip_status.append({
            "ip": _anonymize_ip(ip),
            "current_usage": current_count,
            "limit": RATE_LIMIT_MAX_PER_HOUR,
            "allowed": allowed,
            "retry_after_seconds": retry_after if not allowed else 0,
            "recent_requests": len(timestamps),
        })
    
    return {
        "total_ips_tracked": len(rate_limit_storage),
        "ips": ip_status,
        "global_limit": RATE_LIMIT_MAX_PER_HOUR,
        "window_hours": RATE_LIMIT_WINDOW_HOURS,
    }

@app.get("/admin/clear-analytics")
async def admin_clear_analytics(request: Request):
    """Clear all analytics data"""
    if not _is_admin_request(request):
        raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
    
    global analytics_storage, stage_failure_stats
    count = len(analytics_storage)
    analytics_storage.clear()
    stage_failure_stats.clear()
    
    return {
        "cleared": count,
        "message": f"Cleared {count} analytics records"
    }


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860, timeout_keep_alive=180)