File size: 113,941 Bytes
04684e6
 
 
 
 
 
 
 
 
 
 
f9e6788
eb4ae44
2678e3b
04684e6
 
 
f8a6bfe
04684e6
 
 
 
 
 
 
f8a6bfe
 
 
 
 
 
 
 
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3993434
 
 
 
 
 
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2678e3b
 
 
04684e6
 
 
 
 
 
 
 
 
2678e3b
 
 
 
 
 
 
 
 
ef3cc8a
2678e3b
 
04684e6
ef3cc8a
04684e6
 
 
 
 
 
 
 
 
9496b0b
b732ab0
04684e6
3993434
04684e6
 
 
 
 
 
 
 
 
 
9496b0b
 
b732ab0
 
04684e6
 
3993434
 
 
 
 
 
 
 
04684e6
 
 
 
3993434
04684e6
 
 
 
 
3993434
 
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4135ca
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3993434
 
 
 
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e3b725
 
04684e6
2678e3b
 
 
 
 
 
 
 
 
 
 
 
ef3cc8a
2678e3b
 
 
 
 
 
 
 
 
 
 
 
 
04684e6
 
 
 
f9e6788
04684e6
 
f9e6788
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2678e3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c36551
 
 
 
 
 
 
 
3993434
9496b0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
687f9bf
9496b0b
687f9bf
9496b0b
ef3cc8a
9496b0b
 
 
2c36551
 
 
 
 
 
 
3993434
2c36551
 
 
 
 
 
 
 
 
 
 
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9e6788
04684e6
 
 
 
 
 
 
 
f9e6788
04684e6
 
 
 
 
 
 
 
 
 
 
 
f9e6788
ef3cc8a
04684e6
f9e6788
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9e6788
04684e6
 
 
 
 
f9e6788
04684e6
 
 
 
 
f9e6788
ef3cc8a
04684e6
f9e6788
 
4a3d42c
 
 
 
 
 
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
7dc7029
 
 
 
04684e6
1325c64
 
 
04684e6
1325c64
 
a497b09
 
 
 
 
 
4a3d42c
 
 
1325c64
 
 
04684e6
 
cd5aaf7
 
04684e6
 
 
 
 
 
cd5aaf7
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
f9e6788
1325c64
 
 
 
 
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd5aaf7
04684e6
a497b09
 
 
 
ef3cc8a
a497b09
ef3cc8a
a497b09
4a3d42c
 
 
 
 
04684e6
cd5aaf7
04684e6
 
ef3cc8a
cd5aaf7
 
 
 
 
 
 
 
 
 
04684e6
 
2f73c0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f73c0e
04684e6
 
2f73c0e
04684e6
ef3cc8a
04684e6
 
 
3993434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04684e6
3993434
 
4fb0550
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef3cc8a
4fb0550
3993434
 
 
 
 
 
 
 
 
04684e6
 
2678e3b
 
 
2c36551
3993434
 
 
 
 
2c36551
 
e784831
3993434
 
 
e784831
 
04684e6
3993434
 
 
 
04684e6
3993434
2c36551
3993434
65b8f9a
3993434
 
 
 
04684e6
 
 
 
 
 
 
 
276d1c3
04684e6
 
 
 
687f9bf
 
 
04684e6
 
 
 
 
 
 
 
 
 
687f9bf
04684e6
687f9bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04684e6
 
 
687f9bf
 
 
 
04684e6
687f9bf
 
04684e6
 
 
 
 
687f9bf
04684e6
687f9bf
04684e6
 
 
687f9bf
04684e6
 
 
 
 
 
 
 
 
 
 
 
687f9bf
04684e6
 
 
687f9bf
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276d1c3
 
 
 
 
 
 
 
 
 
 
 
 
04684e6
 
687f9bf
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
687f9bf
04684e6
 
 
 
 
 
 
 
 
 
 
3993434
 
04684e6
 
 
 
3993434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276d1c3
 
3993434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef3cc8a
3993434
 
 
bb8d56d
 
8ef2cd2
bb8d56d
 
 
 
 
 
 
 
 
 
 
 
 
 
8ef2cd2
bb8d56d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef3cc8a
bb8d56d
 
 
 
 
 
ef3cc8a
bb8d56d
 
 
3993434
 
 
04684e6
 
 
 
3993434
04684e6
ec0c85f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fb0550
 
 
 
 
 
 
ec0c85f
 
 
3993434
 
ec0c85f
4fb0550
 
 
ec0c85f
 
 
 
 
 
 
 
 
 
ef3cc8a
ec0c85f
 
 
 
 
 
3993434
ec0c85f
3993434
 
ec0c85f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69d3d07
ec0c85f
 
 
 
 
 
 
 
 
 
69d3d07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec0c85f
ef3cc8a
ec0c85f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e33c1f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec0c85f
 
 
 
 
 
 
e33c1f9
 
 
 
 
 
 
ec0c85f
 
 
e33c1f9
 
 
 
 
 
 
 
 
 
 
 
 
b732ab0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3993434
fb3984d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3993434
 
 
 
b732ab0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3984d
 
 
 
 
 
 
3993434
fb3984d
 
 
 
 
 
 
 
 
b8de33e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3993434
fb3984d
 
 
 
 
 
 
3993434
fb3984d
 
 
 
 
 
 
 
85d0497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01864c7
 
 
 
 
8ef2cd2
 
 
 
3993434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276d1c3
 
 
 
 
 
 
 
 
 
 
3993434
 
 
 
 
 
 
 
 
 
 
 
ec0c85f
 
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9e6788
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef3cc8a
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8fe1a2
 
687f9bf
c8fe1a2
 
 
 
687f9bf
 
b732ab0
687f9bf
 
 
 
 
 
 
 
 
 
c8fe1a2
 
04684e6
 
3993434
b732ab0
 
 
04684e6
3993434
 
04684e6
 
 
3993434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec0c85f
3993434
 
 
 
 
 
 
 
 
 
04684e6
 
07f9ba9
 
 
 
 
 
4fb0550
 
 
 
 
07f9ba9
 
 
 
e33c1f9
07f9ba9
 
e33c1f9
 
 
 
 
 
 
 
07f9ba9
 
 
 
 
 
 
3993434
07f9ba9
 
 
 
ef3cc8a
07f9ba9
 
 
 
 
 
4fb0550
 
3993434
07f9ba9
3993434
07f9ba9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e33c1f9
 
07f9ba9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef3cc8a
07f9ba9
 
 
 
 
 
 
 
 
3993434
 
07f9ba9
 
 
 
 
 
 
 
 
 
 
 
1e3b725
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0bf932b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04684e6
 
 
 
 
 
e33c1f9
 
 
 
 
 
 
 
04684e6
 
 
 
 
 
3993434
 
0bf932b
 
 
3993434
 
0bf932b
3993434
04684e6
 
0bf932b
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb4ae44
 
 
 
 
 
1325c64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef3cc8a
1325c64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb4ae44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef3cc8a
eb4ae44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d21dfe
 
65b8f9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d21dfe
 
 
 
 
 
 
 
 
 
 
 
 
04684e6
 
 
 
eb4ae44
04684e6
 
 
1325c64
3993434
04684e6
3993434
 
eb4ae44
 
 
 
65b8f9a
 
 
 
 
 
 
 
 
 
 
 
 
 
04684e6
eb4ae44
 
 
 
 
 
 
ef3cc8a
04684e6
 
 
 
eb4ae44
04684e6
 
 
 
 
 
 
7dc7029
 
04684e6
 
7dc7029
 
04684e6
7dc7029
 
 
 
 
 
 
 
 
 
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c36551
 
3993434
 
 
04684e6
 
 
 
 
 
 
 
 
 
 
3993434
 
 
 
 
 
 
 
04684e6
6d21dfe
 
 
 
04684e6
 
 
 
 
 
 
 
 
2c36551
 
3993434
2c36551
04684e6
65b8f9a
 
6d21dfe
 
 
 
04684e6
1325c64
3993434
 
 
 
 
 
 
ef3cc8a
3993434
04684e6
 
01864c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04684e6
 
ec0c85f
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3993434
04684e6
 
 
 
 
3993434
 
 
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb4ae44
04684e6
751c735
 
 
 
 
 
 
 
a4135ca
eb4ae44
 
 
 
 
 
04684e6
b732ab0
 
 
 
3993434
 
 
 
 
 
 
 
 
 
ec0c85f
85d0497
 
 
 
 
3993434
 
 
01864c7
 
 
 
 
3993434
 
 
 
 
 
 
 
 
 
 
 
04684e6
 
 
 
 
 
 
 
 
2c36551
 
 
 
04684e6
 
 
 
 
 
 
 
 
7dc7029
 
 
04684e6
 
 
 
 
3993434
04684e6
 
3993434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04684e6
 
 
 
 
f9e6788
 
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9e6788
04684e6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
"""
Main application entry point for Hugging Face Space
Author: Maaldeens
License: MIT
"""

import asyncio
import hashlib
import hmac
import io
import json
import os
import threading
import time
import uuid
import argparse
import logging
import warnings
from concurrent.futures import ThreadPoolExecutor
from typing import Optional
import uvicorn
from fastapi import FastAPI, Request, UploadFile, File, Form, HTTPException
from fastapi.responses import JSONResponse, Response
from fastapi.middleware.cors import CORSMiddleware

# pyannote.audio calls torchaudio.set_audio_backend() which is a no-op in
# torchaudio 2.x (dispatcher always enabled). Suppress the UserWarning it emits.
warnings.filterwarnings(
    "ignore",
    message="torchaudio._backend.set_audio_backend has been deprecated",
    category=UserWarning,
)

try:
    import requests as _requests
    _requests_available = True
except ImportError:
    _requests_available = False

# ZeroGPU support — only activate on ZeroGPU Spaces.
# SPACES_ZERO_GPU=1 is set exclusively by HF's ZeroGPU infrastructure.
# SPACE_ID is present on ALL HF Spaces (including T4/A10G paid tiers) and
# is therefore NOT a reliable gate; use SPACES_ZERO_GPU instead.
try:
    import spaces as _spaces
    _HF_ZERO_GPU = os.getenv("SPACES_ZERO_GPU") == "1"
except ImportError:
    _spaces = None
    _HF_ZERO_GPU = False

_executor = ThreadPoolExecutor(max_workers=2)

# All compute and job routes require a verified Firebase user. Integrations
# must obtain their own service account's Firebase ID token; shared keys do
# not grant user impersonation or bypass billing.
_MAX_AUDIO_SECONDS = 2 * 60 * 60
_MAX_UPLOAD_BYTES = 256 * 1024 * 1024
_WORK_SLOTS = threading.BoundedSemaphore(8)

# ── Supabase persistent job storage ──────────────────────────────────────────
_SUPABASE_URL = os.getenv("SUPABASE_URL", "")
_SUPABASE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY", "")


def _sb_headers() -> dict:
    return {
        "apikey": _SUPABASE_KEY,
        "Authorization": f"Bearer {_SUPABASE_KEY}",
        "Content-Type": "application/json",
        "Prefer": "return=representation",
    }


def _supabase_request(method: str, path: str, payload=None, params=None) -> Optional[dict]:
    """Make a request to Supabase REST API using requests library."""
    if not _requests_available:
        return None
    if not _SUPABASE_URL or not _SUPABASE_KEY:
        return None

    url = f"{_SUPABASE_URL}{path}"
    headers = _sb_headers()
    if method in ("POST", "PUT", "PATCH") and payload is not None:
        headers["Prefer"] = "return=representation,resolution=merge-duplicates"

    try:
        resp = _requests.request(
            method,
            url,
            params=params,
            json=payload,
            headers=headers,
            timeout=10,
        )
        if resp.status_code >= 400:
            logger.warning(f"Supabase {method} {path} HTTP {resp.status_code}")
            return None
        return resp.json() if resp.text else {}
    except Exception as e:
        logger.warning(f"Supabase {method} {path} failed: {type(e).__name__}")
    return None


def _upsert_job(
    job_id: str,
    status: str,
    result: Optional[dict] = None,
    progress: Optional[dict] = None,
    detail: Optional[str] = None,
    submitted_at: Optional[float] = None,
    firebase_uid: Optional[str] = None,
):
    """Update an existing owner-bound job. Storage failures are explicit."""
    payload = {
        "job_id": job_id,
        "status": status,
    }
    if result is not None:
        payload["result"] = result
    if progress is not None:
        payload["progress"] = progress
    if detail is not None:
        payload["detail"] = detail
    if submitted_at is not None:
        payload["submitted_at"] = submitted_at
    if firebase_uid:
        payload["firebase_uid"] = firebase_uid

    if not _SUPABASE_URL or not _SUPABASE_KEY:
        raise RuntimeError("Job storage is not configured")
    # Creation happens insert-only in reserve_processing; progress cannot
    # accidentally create jobs or replace their owners.
    payload.pop("job_id", None)
    resp = _supabase_request("PATCH", "/rest/v1/transcription_jobs", payload=payload,
                             params={"job_id": f"eq.{job_id}"})
    if not resp:
        raise RuntimeError("Job storage unavailable")



def _get_job(job_id: str) -> Optional[dict]:
    """Read authoritative job state and ownership from Supabase."""
    rows = _supabase_request(
        "GET",
        "/rest/v1/transcription_jobs",
        params={"job_id": f"eq.{job_id}", "limit": "1"},
    )
    if rows is None:
        raise HTTPException(status_code=503, detail="Job storage unavailable")
    if rows and isinstance(rows, list) and len(rows) > 0:
        row = rows[0]
        return row
    return None


def _delete_job(job_id: str):
    """Remove job from local cache and Supabase."""
    _supabase_request(
        "DELETE",
        "/rest/v1/transcription_jobs",
        params={"job_id": f"eq.{job_id}"},
    )

try:
    import anthropic as _anthropic
    _anthropic_available = True
except ImportError:
    _anthropic_available = False

# Languages where smaller Whisper models perform poorly.
# medium has almost no Yoruba/Igbo/Hausa training data — large-v3 is
# the minimum model where these languages plus English code-switching
# produce usable results.
_UPGRADE_LANGUAGES = {"yo", "ig", "ha"}
_UPGRADE_TARGET = "whisper-large-v3"

# Short generic language hints for code-switching audio.
# We deliberately avoid full sentences — Whisper can hallucinate them
# when uncertain, causing cascading repetition loops across chunks.
_LANGUAGE_PROMPTS = {
    "yo": "Yoruba and English, proper tone marks.",
    "ig": "Igbo and English, proper diacritics.",
    "ha": "Hausa and English, proper tone marks.",
}

from src.transcription.engine import TranscriptionEngine, NATIVE_MODELS, native_asr_enabled
from src.output.formatter import OutputFormatter

# Setup logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Initialize FastAPI app
app = FastAPI(
    title="Modular ASR System",
    description="Upgradable speech-to-text transcription system",
    version="1.0.0"
)

from src.security import RequestAdmission
app.add_middleware(RequestAdmission, authorize=lambda request: _require_uid(request),
                   max_upload_bytes=_MAX_UPLOAD_BYTES)

# Add CORS middleware — origins configurable via env var
# Default allows all origins WITHOUT credentials (browser-safe default).
# For production, set CORS_ORIGINS=https://yourdomain.com,https://app.yourdomain.com
_cors_origins = [o.strip() for o in os.getenv("CORS_ORIGINS", "*").split(",")]
_allow_credentials = os.getenv("CORS_ALLOW_CREDENTIALS", "false").lower() == "true"
app.add_middleware(
    CORSMiddleware,
    allow_origins=_cors_origins,
    allow_credentials=_allow_credentials,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize transcription engine
engine = None

@app.on_event("startup")
async def startup_event():
    global engine
    config_path = os.getenv("CONFIG_PATH", "config/settings.yaml")
    engine = TranscriptionEngine(config_path)
    logger.info(f"Transcription engine initialized with model: {engine.current_model_key}")
    # Google Play refunds take their credits back (every 6 hours; idempotent).
    asyncio.create_task(_google_voided_loop())

    # Diarization availability diagnostic — visible in HF Space logs
    hf_token_set = bool(os.getenv("HF_TOKEN"))
    if engine.diarization.is_available():
        logger.info("Speaker diarization: AVAILABLE (pyannote importable + HF_TOKEN set)")
        # Pre-load the pyannote pipeline in the background so the first
        # transcription request doesn't stall waiting for the ~1 GB model download.
        async def _preload_pyannote():
            try:
                logger.info("Pre-loading pyannote diarization pipeline in background…")
                await asyncio.to_thread(engine.diarization._load_pipeline)
                logger.info("Pyannote diarization pipeline pre-loaded successfully.")
            except Exception as exc:
                logger.warning(f"Pyannote pipeline pre-load failed (will retry on first use): {type(exc).__name__}")
        asyncio.create_task(_preload_pyannote())
    else:
        try:
            from src.diarization.engine import _PYANNOTE_AVAILABLE as _pyannote_ok
        except Exception:
            _pyannote_ok = False
        logger.warning(
            "Speaker diarization: UNAVAILABLE — "
            f"pyannote_importable={_pyannote_ok}, hf_token_set={hf_token_set}. "
            "Set HF_TOKEN in Space secrets and ensure pyannote/speaker-diarization-3.1 "
            "is accessible on HuggingFace."
        )

    # Verify Supabase connectivity on startup
    if _SUPABASE_URL and _SUPABASE_KEY:
        test_resp = _supabase_request(
            "GET", "/rest/v1/transcription_jobs", params={"limit": "1"}
        )
        if test_resp is not None:
            logger.info(f"Supabase connection OK: {_SUPABASE_URL}")
        else:
            logger.warning(f"Supabase connection FAILED: {_SUPABASE_URL}")
    else:
        logger.warning("Supabase not configured — job results will NOT persist across restarts")

@app.get("/")
async def root():
    return {
        "name": "Modular ASR System",
        "version": "1.0.0",
        "owner": "Maaldeens",
        "license": "MIT",
        "status": "operational",
        "available_models": list(engine.get_available_models().keys()) if engine else [],
        "current_model": engine.current_model_key if engine else None
    }

@app.get("/models")
async def list_models():
    if not engine:
        raise HTTPException(status_code=503, detail="Engine not initialized")
    return {
        "available_models": engine.get_available_models(),
        "current_model": engine.current_model_key
    }

@app.get("/diarization-status")
async def diarization_status_endpoint():
    """Diagnostic endpoint — shows why diarization is or isn't available."""
    # Run the import directly to capture the real exception (not a cached flag)
    pyannote_importable = False
    pyannote_error = ""
    try:
        import pyannote.audio as _pa  # noqa: F401
        pyannote_importable = True
    except Exception as e:
        pyannote_error = f"{type(e).__name__}: {e}"
    hf_token_set = bool(os.getenv("HF_TOKEN"))
    available = engine.diarization.is_available() if engine else False
    reason = None
    if not available:
        if not pyannote_importable:
            reason = pyannote_error or "pyannote.audio failed to import"
        elif not hf_token_set:
            reason = "HF_TOKEN is not set — add it to HuggingFace Space secrets"
        else:
            reason = "unknown"
    return {
        "available": available,
        "pyannote_importable": pyannote_importable,
        "hf_token_set": hf_token_set,
        "reason": reason,
    }


# ── Cancellation ──────────────────────────────────────────────────────────────
# A user can cancel a job from the app. The flag lives in Supabase (status
# "cancelled") because on Modal the cancel request can land on a different
# container than the one running the job; _CANCELLED is the same-container
# fast path. The running job checks between 5-minute blocks.
_CANCELLED: set = set()



# Job rows hold finished transcripts so the app can collect them; they are
# not kept beyond JOB_RETENTION_DAYS (stated in the privacy policy).
JOB_RETENTION_DAYS = 7
_last_purge = 0.0


def _purge_old_jobs() -> None:
    global _last_purge
    now = time.time()
    if now - _last_purge < 3600:
        return
    _last_purge = now
    cutoff = now - JOB_RETENTION_DAYS * 86400
    def run():
        if _SUPABASE_URL and _SUPABASE_KEY and _requests_available:
            try:
                for when in (f"lt.{cutoff}", "is.null"):  # null: rows from before timestamps were stored
                    response = _requests.delete(f"{_SUPABASE_URL}/rest/v1/transcription_jobs",
                                     params={"submitted_at": when}, headers=_sb_headers(), timeout=15)
                    response.raise_for_status()
            except Exception as e:
                logger.warning(f"Job purge failed: {type(e).__name__}")
    threading.Thread(target=run, daemon=True).start()


class _JobCancelled(Exception):
    pass


def _is_cancelled(job_id: str) -> bool:
    if job_id in _CANCELLED:
        return True
    # Cancellation is shared by all workers/containers through Supabase.
    rows = _supabase_request(
        "GET",
        "/rest/v1/transcription_jobs",
        params={"job_id": f"eq.{job_id}", "select": "status", "limit": "1"},
    )
    if rows and isinstance(rows, list) and rows and rows[0].get("status") == "cancelled":
        _CANCELLED.add(job_id)
        return True
    return False


_HALLUCINATION_PATTERNS = [
    "thank you for watching",
    "thanks for watching",
    "see you in the next video",
    "don't forget to subscribe",
    "like and subscribe",
    "see you next time",
    "thanks for listening",
    "please subscribe",
]

def _is_likely_hallucination(text: str) -> bool:
    lower = text.lower()
    return any(p in lower for p in _HALLUCINATION_PATTERNS)

def _is_repetition_loop(text: str) -> bool:
    t = text.strip()
    if len(t) < 20:
        return False
    # 1) Single-character dominance (e.g. "GGGGG" or "-------")
    most_common_count = max(t.count(c) for c in set(t))
    if most_common_count / len(t) > 0.70:
        return True
    # 2) Short-phrase repetition (e.g. "thanks for watching" repeated)
    probe = t[:15]
    if t.count(probe) > max(5, len(t) // 50):
        return True
    # 3) Alternating short-token repetition (e.g. "G-G-G-G" or "I'm I'm I'm")
    tokens = t.split()
    if len(tokens) >= 8:
        for window in (2, 3, 4):
            pattern = tuple(tokens[:window])
            repeats = 0
            for i in range(0, len(tokens) - window + 1, window):
                if tuple(tokens[i:i + window]) == pattern:
                    repeats += window
            if repeats / len(tokens) > 0.60:
                return True
    # 4) Sentence-level repetition — Whisper often hallucinates the same
    #    stock sentences (e.g. Yoruba/English phrases, "thanks for watching")
    #    repeatedly on music or noisy audio.
    import re
    sentences = [s.strip() for s in re.split(r"[.!?]+", t) if len(s.strip()) > 8]
    if len(sentences) >= 6:
        from collections import Counter
        counts = Counter(sentences)
        most_common_count = counts.most_common(1)[0][1]
        if most_common_count >= 4:
            return True
        unique_ratio = len(counts) / len(sentences)
        if unique_ratio < 0.35:
            return True
    # 5) Single-character stutter with separators: "Z, Z, Z, Z" or "G-G-G-G"
    #    Extract alphabetic chars and check for dominance of one letter.
    alpha_only = re.sub(r"[^a-zA-Z]", "", t)
    if len(alpha_only) > 20:
        from collections import Counter
        c = Counter(alpha_only.lower())
        if c.most_common(1)[0][1] / len(alpha_only) > 0.60:
            return True
    return False


_BATCH_SIZE = 30


def _generate_minutes_with_claude(
    segments: list, speaker_names: dict, session_name: str
) -> dict:
    """Summarise a transcript into structured meeting minutes using Claude."""
    api_key = os.getenv("ANTHROPIC_API_KEY")
    if not api_key or not _anthropic_available:
        return {"summary": "", "topics": [], "decisions": [], "action_items": []}

    lines = []
    for seg in segments:
        spk = seg.get("speaker")
        name = speaker_names.get(spk, spk) if spk else "Speaker"
        text = seg.get("text", "").strip()
        if text:
            lines.append(f"{name}: {text}")
    transcript_text = "\n".join(lines)
    if not transcript_text:
        return {"summary": "", "topics": [], "decisions": [], "action_items": []}

    client = _anthropic.Anthropic(api_key=api_key)
    system = (
        "You are a professional meeting minutes writer. "
        "Given a meeting transcript, return ONLY valid JSON with exactly these keys:\n"
        "summary (string, 2-3 sentence overview), "
        "topics (array of strings, key discussion points, max 8), "
        "decisions (array of strings, decisions made, empty if none), "
        "action_items (array of strings, format 'Owner: task' where owner is known, empty if none). "
        "Be concise and factual. Only include what was explicitly discussed. No markdown fences."
    )
    try:
        msg = client.messages.create(
            model="claude-haiku-4-5-20251001",
            max_tokens=1024,
            system=system,
            messages=[{
                "role": "user",
                "content": f"Meeting: {session_name}\n\nTranscript:\n{transcript_text[:40000]}",
            }],
        )
        response_text = msg.content[0].text.strip()
        # Strip markdown fences if model adds them despite instructions
        if response_text.startswith("```"):
            parts = response_text.split("```")
            response_text = parts[1].lstrip("json").strip() if len(parts) > 1 else response_text
        parsed = json.loads(response_text)
        return {
            "summary": parsed.get("summary", ""),
            "topics": parsed.get("topics", []),
            "decisions": parsed.get("decisions", []),
            "action_items": parsed.get("action_items", []),
        }
    except Exception as e:
        logger.warning(f"Minutes generation failed: {type(e).__name__}")
        return {"summary": "", "topics": [], "decisions": [], "action_items": []}


def _get_speaker_sentiments(segments: list, speaker_names: dict) -> dict:
    """Return per-speaker tone label using one Claude call."""
    api_key = os.getenv("ANTHROPIC_API_KEY")
    if not api_key or not _anthropic_available:
        return {}

    speaker_texts: dict[str, list[str]] = {}
    for seg in segments:
        spk = seg.get("speaker")
        if not spk:
            continue
        text = seg.get("text", "").strip()
        if text:
            speaker_texts.setdefault(spk, []).append(text)
    if not speaker_texts:
        return {}

    client = _anthropic.Anthropic(api_key=api_key)
    summaries = []
    for spk_id, texts in speaker_texts.items():
        name = speaker_names.get(spk_id, spk_id)
        combined = " ".join(texts[:60])[:2000]
        summaries.append(f"{spk_id} ({name}): {combined}")

    system = (
        "Analyse the overall tone of each speaker in this meeting excerpt. "
        "For each speaker ID return exactly one label from: calm, neutral, tense, enthusiastic, concerned. "
        "Return ONLY valid JSON: {\"SPEAKER_00\": \"calm\", ...}. No markdown fences."
    )
    try:
        msg = client.messages.create(
            model="claude-haiku-4-5-20251001",
            max_tokens=256,
            system=system,
            messages=[{"role": "user", "content": "\n\n".join(summaries)}],
        )
        response_text = msg.content[0].text.strip()
        if response_text.startswith("```"):
            parts = response_text.split("```")
            response_text = parts[1].lstrip("json").strip() if len(parts) > 1 else response_text
        return json.loads(response_text)
    except Exception as e:
        logger.warning(f"Sentiment analysis failed: {type(e).__name__}")
        return {}


def _adds_words(original: str, corrected: str) -> bool:
    """True when a correction is clearly longer than the line it corrects."""
    before, after = len(original.split()), len(corrected.split())
    return after > before + max(3, before // 4)


def _enhance_segments_with_claude(segments: list, language: str) -> list:
    segments = [s for s in segments if not _is_likely_hallucination(s.get("text", ""))]

    api_key = os.getenv("ANTHROPIC_API_KEY")
    if not api_key or not _anthropic_available:
        return segments

    client = _anthropic.Anthropic(api_key=api_key)
    lang_desc = {
        "yo": "Yoruba-English code-switching",
        "ig": "Igbo-English code-switching",
        "ha": "Hausa-English code-switching",
    }.get(language, language or "en")
    if language and "," in language:
        # A meeting that switches language: each segment stays in its own.
        lang_desc = ("a meeting that switches between " + ", ".join(language.split(","))
                     + "; keep every segment in the language it was spoken in")

    # Only changed segments come back: echoing every unchanged line made
    # output tokens (5x the price of input on Haiku) the largest per-minute
    # cost of a transcription. Segments left out keep their original text.
    system = (
        "You are a transcription corrector. Given numbered segments, fix ASR "
        "errors (misheard words, wrong names, broken punctuation). "
        "Mark a segment HALLUCINATED (exactly) only if it is a stock phrase Whisper "
        "invents on silence or noise: video outros and subtitle credits such as "
        "'Thank you for watching', 'See you in the next video', 'Don't forget to "
        "subscribe', 'Subtitles by ...'. Never mark a segment HALLUCINATED because "
        "it is unusual, off-topic, technical, full of unfamiliar names, or in a "
        "different language from the rest: meetings switch topic and language. "
        "Never translate. Never add new sentences. Each segment is its own stretch "
        "of time: never move words from one segment into another, even to finish a "
        "sentence that continues on the next line. Preserve code-switching exactly. "
        "Output ONLY the segments you changed or marked, one per line, format: "
        "[N] corrected text (or [N] HALLUCINATED). If nothing needs changing, "
        "output exactly: NONE"
    )

    def _process(batch: list) -> list:
        out: list = []
        numbered = "\n".join(
            f"[{i}] {seg.get('text', '').strip()}"
            for i, seg in enumerate(batch)
            if seg.get("text", "").strip()
        )
        if not numbered:
            return out

        try:
            msg = client.messages.create(
                model="claude-haiku-4-5-20251001",
                max_tokens=4096,
                system=system,
                messages=[{
                    "role": "user",
                    "content": (
                        f"Language: {lang_desc}\n\n"
                        f"Segments:\n{numbered}"
                    ),
                }],
            )
            try:
                logger.info(f"Claude cleanup batch: {len(batch)} segments, "
                            f"in={msg.usage.input_tokens} out={msg.usage.output_tokens}")
            except Exception:
                pass
            response_text = msg.content[0].text.strip()

            result_map: dict[int, str] = {}
            for line in response_text.splitlines():
                line = line.strip()
                if not line:
                    continue
                if line.startswith("[") and "]" in line:
                    try:
                        idx_str, rest = line[1:].split("]", 1)
                        result_map[int(idx_str.strip())] = rest.strip()
                    except ValueError:
                        pass

            for i, seg in enumerate(batch):
                corrected = result_map.get(i)
                if corrected is None:
                    out.append(seg)
                elif corrected == "HALLUCINATED":
                    text = seg.get("text", "")
                    # Only drop what looks like Whisper filler. A long, real
                    # sentence is kept even if the model thought it out of place.
                    if len(text.split()) <= 12 or _is_likely_hallucination(text) or _is_repetition_loop(text):
                        logger.info("Stripped hallucinated segment (Claude)")
                    else:
                        logger.info("Kept segment flagged by Claude")
                        out.append(seg)
                elif _adds_words(seg.get("text", ""), corrected):
                    # A "correction" that grows the line has pulled in words from
                    # its neighbours, which then appear twice in the transcript.
                    logger.info("Kept original: correction added words")
                    out.append(seg)
                else:
                    out.append({**seg, "text": corrected})

        except Exception as e:
            logger.warning(f"Claude batch enhancement failed: {type(e).__name__} — keeping originals")
            out.extend(batch)
        return out

    # Batches are independent, so send them concurrently: an hour-long
    # meeting is ~30 batches, which took several minutes one after another.
    from concurrent.futures import ThreadPoolExecutor as _Pool
    batches = [segments[i:i + _BATCH_SIZE] for i in range(0, len(segments), _BATCH_SIZE)]
    with _Pool(max_workers=min(6, max(1, len(batches)))) as pool:
        results = list(pool.map(_process, batches))
    return [seg for part in results for seg in part]


def _base_letters(text: str) -> str:
    """Text without tone marks, accents, case or punctuation."""
    import unicodedata
    plain = "".join(ch for ch in unicodedata.normalize("NFD", text) if unicodedata.category(ch) != "Mn")
    return " ".join("".join(ch.lower() if ch.isalnum() else " " for ch in plain).split())


def _is_same_text_with_marks(original: str, corrected: str, min_ratio: float = 0.8) -> bool:
    """Adding tone marks keeps the letters; anything else (a refusal, an
    explanation, a translation) changes them, so it is rejected."""
    import difflib
    a, b = _base_letters(original), _base_letters(corrected)
    if not a or not b:
        return False
    return difflib.SequenceMatcher(None, a, b, autojunk=False).ratio() >= min_ratio


def _add_diacritics_with_claude(text: str, language: str) -> str:
    """Post-process transcription to add proper tone marks/diacritics."""
    if not text or not text.strip():
        return text
    if language not in ("yo", "ig", "ha"):
        return text

    api_key = os.getenv("ANTHROPIC_API_KEY")
    if not api_key or not _anthropic_available:
        return text

    client = _anthropic.Anthropic(api_key=api_key)
    lang_name = {"yo": "Yoruba", "ig": "Igbo", "ha": "Hausa"}.get(language, language)

    # Build language-specific system prompt
    if language == "yo":
        from src.yoruba_knowledge import build_yoruba_prompt_context
        system = build_yoruba_prompt_context()
    else:
        system = (
            f"You are a {lang_name} language expert. Your ONLY job is to add the "
            f"correct tone marks and diacritics to {lang_name} words. "
            "Do NOT change English words. Do NOT translate. Do NOT add or remove "
            "words. Do NOT change the meaning. Only add missing tone marks. "
            "Return ONLY the corrected text, nothing else."
        )

    try:
        msg = client.messages.create(
            model="claude-haiku-4-5-20251001",
            max_tokens=4096,
            system=system,
            messages=[{
                "role": "user",
                "content": f"Add proper {lang_name} tone marks to this text:\n\n{text}",
            }],
        )
        corrected = msg.content[0].text.strip()

        # Claude sometimes adds explanations despite instructions.
        # Strip parenthetical notes, markdown, and "(No Yoruba words...)" lines.
        import re
        # Remove lines that look like explanations
        lines = corrected.splitlines()
        cleaned_lines = []
        for line in lines:
            stripped = line.strip()
            if stripped.startswith("(") and stripped.endswith(")"):
                continue
            if stripped.startswith("[") and stripped.endswith("]"):
                continue
            if "No Yoruba" in stripped or "no Yoruba" in stripped:
                continue
            if "entirely in English" in stripped:
                continue
            cleaned_lines.append(line)
        corrected = "\n".join(cleaned_lines).strip()

        if corrected and _is_same_text_with_marks(text, corrected):
            logger.info(f"Added {lang_name} diacritics via Claude")
            return corrected
        logger.info(f"Claude {lang_name} diacritics rejected: the letters changed, keeping original")
    except Exception as e:
        logger.warning(f"Claude diacritics failed: {type(e).__name__} — keeping original")
    return text


def _require_uid(request: Request) -> str:
    cached = getattr(request.state, "verified_uid", None)
    if cached:
        return cached
    uid = _verified_uid(request)
    if not uid:
        raise HTTPException(status_code=401, detail="Sign in to continue.")
    profile = _billing_profile(uid)
    if profile is None:
        raise HTTPException(status_code=403, detail="Account profile required.")
    if profile.get("disabled_at"):
        raise HTTPException(status_code=403, detail="Account suspended.")
    return uid


def _owned_job(job_id: str, request: Request) -> dict:
    uid = _require_uid(request)
    try:
        uuid.UUID(job_id)
    except ValueError:
        raise HTTPException(status_code=404, detail="Job not found")
    row = _get_job(job_id)
    if not row or row.get("firebase_uid") != uid:
        raise HTTPException(status_code=404, detail="Job not found")
    return _reap_if_orphaned(job_id, row)


# A job left "processing" by a server that restarted never finishes. On the
# HF Space (one process; SPACE_ID is set by Hugging Face) a processing job this
# process didn't start was orphaned by a restart. Anywhere, nothing runs for
# 3 hours. Either way fail it and refund the reserved credits so the app stops
# polling and the user can retry.
_ORPHAN_MAX_AGE = 3 * 3600


def _reap_if_orphaned(job_id: str, row: dict) -> dict:
    if row.get("status") != "processing":
        return row
    try:
        age = time.time() - float(row.get("submitted_at") or 0)
    except (TypeError, ValueError):
        age = 0
    single_process = bool(os.getenv("SPACE_ID"))
    lost = single_process and job_id not in _JOB_SUBMIT_TIMES and age > 30
    if not (lost or (row.get("submitted_at") and age > _ORPHAN_MAX_AGE)):
        return row
    logger.warning(f"Job {job_id} orphaned (age {age:.0f}s); failing and refunding")
    _upsert_job(job_id, status="error", detail="The server restarted. Please try again.")
    try:
        _finish_work(job_id, False)
    except Exception:
        logger.error("Orphaned job refund needs reconciliation: %s", job_id)
    return dict(row, status="error")


@app.get("/progress/{job_id}")
async def get_progress(job_id: str, request: Request):
    row = await asyncio.to_thread(_owned_job, job_id, request)
    p = row.get("progress") or {}
    total, current = p.get("total", 0), p.get("current", 0)
    return {"current": current, "total": total,
            "percent": round(current / total * 100) if total > 0 else 0}


_JOB_SUBMIT_TIMES: dict = {}


@app.post("/cancel/{job_id}")
async def cancel_job(job_id: str, request: Request):
    row = await asyncio.to_thread(_owned_job, job_id, request)
    if row.get("status") == "processing":
        await asyncio.to_thread(_upsert_job, job_id, status="cancelled", detail="Cancelled by user")
    return {"status": "cancelled" if row.get("status") == "processing" else row.get("status")}


@app.get("/status/{job_id}")
async def get_status(job_id: str, request: Request):
    row = await asyncio.to_thread(_owned_job, job_id, request)
    return {"status": row.get("status", "processing")}


@app.get("/result/{job_id}")
async def get_result(job_id: str, request: Request):
    row = await asyncio.to_thread(_owned_job, job_id, request)
    status = row.get("status")
    if status == "processing":
        return JSONResponse(status_code=202, content={"status": "processing"})
    if status == "cancelled":
        raise HTTPException(status_code=410, detail="Transcription cancelled.")
    if status == "error":
        raise HTTPException(status_code=422, detail=_user_detail(row.get("detail")) or "Transcription failed. Please try again.")
    if status == "done" and row.get("result"):
        # GET never consumes a result. Retention cleanup removes expired jobs.
        return JSONResponse(content=row["result"])
    raise HTTPException(status_code=503, detail="Result temporarily unavailable")


def _generate_docx_bytes(
    ai_minutes: dict,
    session_name: str,
    segments: list,
    speaker_names: dict,
    prepared_by: str = "",
    speaker_sentiment: Optional[dict] = None,
) -> bytes:
    """Build a Word document from AI minutes + full transcript."""
    try:
        from docx import Document
        from docx.shared import Pt, RGBColor, Inches
        from docx.oxml import OxmlElement
        from docx.oxml.ns import qn
        from docx.enum.text import WD_ALIGN_PARAGRAPH
    except ImportError:
        raise RuntimeError("python-docx not installed")

    import datetime

    doc = Document()

    # ── Styles ──────────────────────────────────────────────────────────────
    style = doc.styles["Normal"]
    style.font.name = "Inter"
    style.font.size = Pt(11)
    style.font.color.rgb = RGBColor.from_string("111111")
    style.paragraph_format.line_spacing = 1.35
    style.paragraph_format.space_after = Pt(8)
    section = doc.sections[0]
    section.top_margin = section.bottom_margin = Inches(0.65)
    section.left_margin = section.right_margin = Inches(0.72)
    for name, size in (("Title", 28), ("Heading 1", 16), ("Heading 2", 11)):
        heading = doc.styles[name]
        heading.font.name = "Inter"
        heading.font.size = Pt(size)
        heading.font.color.rgb = RGBColor.from_string("111111")
        heading.paragraph_format.space_before = Pt(20)
        heading.paragraph_format.space_after = Pt(8)
        heading.paragraph_format.keep_with_next = True
        borders = OxmlElement("w:pBdr")
        bottom = OxmlElement("w:bottom")
        bottom.set(qn("w:val"), "nil")
        borders.append(bottom)
        heading.element.get_or_add_pPr().append(borders)
    brand = doc.add_paragraph()
    brand.paragraph_format.space_after = Pt(20)
    from pathlib import Path
    logo_path = Path(__file__).resolve().parent / "src" / "output" / "assets" / "narratifai-logo.png"
    brand.add_run().add_picture(str(logo_path), width=Inches(0.42))
    brand_run = brand.add_run("  NarratifAI")
    brand_run.bold = True
    brand_run.font.size = Pt(14)
    footer = section.footer.paragraphs[0]
    footer.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    footer_run = footer.add_run("NarratifAI  /  Meeting report     ·     ")
    footer_run.font.size = Pt(8)
    footer_run.font.color.rgb = RGBColor.from_string("5F5F5F")
    field = OxmlElement("w:fldSimple")
    field.set(qn("w:instr"), "PAGE")
    footer._p.append(field)

    # ── Cover ────────────────────────────────────────────────────────────────
    title_para = doc.add_heading("", level=0)
    run = title_para.add_run(session_name)
    run.font.size = Pt(28)
    run.font.color.rgb = RGBColor.from_string("111111")
    title_para.alignment = WD_ALIGN_PARAGRAPH.LEFT

    sub = doc.add_paragraph("Minutes of meeting")
    sub.alignment = WD_ALIGN_PARAGRAPH.LEFT
    sub.runs[0].font.size = Pt(13)
    sub.runs[0].font.bold = True

    date_str = datetime.datetime.now().strftime("%-d %B %Y")
    meta = doc.add_paragraph(f"Date: {date_str}")
    meta.alignment = WD_ALIGN_PARAGRAPH.LEFT
    meta.runs[0].font.size = Pt(11)
    meta.runs[0].font.color.rgb = RGBColor.from_string("5F5F5F")

    if prepared_by:
        prep = doc.add_paragraph(f"Prepared by: {prepared_by}")
        prep.alignment = WD_ALIGN_PARAGRAPH.LEFT
        prep.runs[0].font.size = Pt(11)

    doc.add_paragraph("")

    # ── AI Summary ───────────────────────────────────────────────────────────
    summary = ai_minutes.get("summary", "")
    topics = ai_minutes.get("topics") or []
    decisions = ai_minutes.get("decisions") or []
    action_items = ai_minutes.get("action_items") or []

    if summary or topics or decisions or action_items:
        h = doc.add_heading("AI Summary", level=1)
        h.runs[0].font.color.rgb = RGBColor.from_string("111111")

        if summary:
            p = doc.add_paragraph(summary)
            p.paragraph_format.space_after = Pt(14)

        if topics:
            doc.add_heading("Key Topics", level=2)
            for t in topics:
                doc.add_paragraph(t, style="List Bullet")

        if decisions:
            doc.add_heading("Decisions Made", level=2)
            for d in decisions:
                doc.add_paragraph(d, style="List Bullet")

        if action_items:
            doc.add_heading("Action Items", level=2)
            for a in action_items:
                doc.add_paragraph(a, style="List Bullet")

        doc.add_paragraph("")

    # ── Participants, with each speaker's overall tone when known ────────────
    speaker_ids = list(dict.fromkeys(s.get("speaker") for s in segments if s.get("speaker")))
    if speaker_ids:
        doc.add_heading("Participants", level=1)
        for spk_id in speaker_ids:
            p = doc.add_paragraph(style="List Bullet")
            p.add_run(str(speaker_names.get(spk_id, spk_id))).bold = True
            tone = (speaker_sentiment or {}).get(spk_id)
            if tone:
                tone_run = p.add_run(f"  ·  {tone.capitalize()}")
                tone_run.font.color.rgb = RGBColor.from_string("5F5F5F")
        doc.add_paragraph("")

    # ── Full Transcript ──────────────────────────────────────────────────────
    h2 = doc.add_heading("Full Transcript", level=1)
    h2.runs[0].font.color.rgb = RGBColor.from_string("111111")

    def _ts(s: float) -> str:
        h = int(s // 3600)
        m = int((s % 3600) // 60)
        sec = int(s % 60)
        return f"{h:02}:{m:02}:{sec:02}"

    for seg in segments:
        spk_id = seg.get("speaker")
        name = speaker_names.get(spk_id, spk_id) if spk_id else None
        text = seg.get("text", "").strip()
        start = seg.get("start", 0)
        if not text:
            continue
        p = doc.add_paragraph()
        ts_run = p.add_run(f"[{_ts(start)}]  ")
        ts_run.font.size = Pt(9)
        ts_run.font.color.rgb = RGBColor.from_string("5F5F5F")
        if name:
            spk_run = p.add_run(f"{name}: ")
            spk_run.font.bold = True
            spk_run.font.size = Pt(11)
        p.add_run(text).font.size = Pt(11)

    buf = io.BytesIO()
    doc.save(buf)
    return buf.getvalue()


async def _generate_minutes(request: Request, docx: bool = False):
    uid = await asyncio.to_thread(_require_uid, request)
    try:
        body = await request.json()
    except Exception:
        raise HTTPException(status_code=400, detail="Invalid JSON body")
    _minutes_input(request, body)
    if not _WORK_SLOTS.acquire(blocking=False):
        raise HTTPException(status_code=429, detail="Server busy. Try again later.")
    reference = str(uuid.uuid4())
    reserved = False
    settled = False
    try:
        canonical = {"segments": body["segments"], "speakers": body.get("speaker_names", {}),
                     "session": body.get("session_name", "Meeting")[:200]}
        cache_key = hashlib.sha256(json.dumps(canonical, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
        reservation = await asyncio.to_thread(_reserve_work, uid, reference, MINUTES_DOC_CREDITS, "minutes", cache_key)
        result = reservation.get("cached")
        reserved = result is None
        if reserved:
            result = await asyncio.to_thread(_generate_minutes_with_claude, body["segments"],
                                            body.get("speaker_names", {}), body.get("session_name", "Meeting")[:200])
        if not isinstance(result, dict) or not any(result.get(k) for k in ("summary", "topics", "decisions", "action_items")):
            raise HTTPException(status_code=503, detail="Minutes generation temporarily unavailable")
        if docx:
            payload = await asyncio.to_thread(_generate_docx_bytes, result,
                body.get("session_name", "Meeting")[:200], body["segments"],
                body.get("speaker_names", {}), str(body.get("prepared_by", ""))[:200],
                _speaker_sentiment_input(body.get("speaker_sentiment")))
        if reserved:
            completed = await asyncio.to_thread(_supabase_request, "POST", "/rest/v1/rpc/complete_minutes",
                                                {"p_reference": reference, "p_result": result})
            if not isinstance(completed, dict) or completed.get("error"):
                raise HTTPException(status_code=503, detail="Could not save minutes. Please retry.")
        settled = True
        if docx:
            return Response(content=payload, media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                            headers={"Content-Disposition": 'attachment; filename="meeting-minutes.docx"'})
        return JSONResponse(content=result)
    finally:
        if reserved and not settled:
            try:
                await asyncio.to_thread(_finish_work, reference, False)
            except Exception:
                logger.error("Minutes reservation needs reconciliation: %s", reference)
        _WORK_SLOTS.release()


@app.post("/translate")
async def translate_transcript_endpoint(request: Request):
    from src.translation import validate_translation, translate_texts, translation_credits
    uid = await asyncio.to_thread(_require_uid, request)
    try:
        target, texts = validate_translation(await request.json())
    except (ValueError, TypeError):
        raise HTTPException(status_code=400, detail="Choose a supported language and a transcript of up to 500 segments and 50,000 characters.")
    if not _WORK_SLOTS.acquire(blocking=False):
        raise HTTPException(status_code=429, detail="Server busy. Try again later.")
    reference = str(uuid.uuid4())
    reserved = settled = False
    try:
        # Translation shares the existing five-credit AI document reservation
        # and owner-bound cache. Namespace prevents collisions with minutes.
        canonical = {"task": "translation-v1", "target": target, "texts": texts}
        cache_key = hashlib.sha256(json.dumps(canonical, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
        reservation = await asyncio.to_thread(_reserve_work, uid, reference, translation_credits(texts), "minutes", cache_key)
        result = reservation.get("cached")
        reserved = result is None
        if reserved:
            key = os.getenv("ANTHROPIC_API_KEY")
            if not key or not _anthropic_available:
                raise RuntimeError("Translation service unavailable")
            def generate():
                with _anthropic.Anthropic(api_key=key, max_retries=0) as client:
                    return translate_texts(client, target, texts)
            translated = await asyncio.to_thread(generate)
            result = {"target_language": target, "texts": translated}
            completed = await asyncio.to_thread(_supabase_request, "POST", "/rest/v1/rpc/complete_minutes",
                                                {"p_reference": reference, "p_result": result})
            if not isinstance(completed, dict) or completed.get("error") or completed.get("state") != "settled":
                raise RuntimeError("Could not save translation")
        if not isinstance(result, dict) or result.get("target_language") != target or not isinstance(result.get("texts"), list) or len(result["texts"]) != len(texts):
            raise RuntimeError("Invalid cached translation")
        settled = True
        return {**result, "credits_charged": reservation.get("reserved", 0) if reserved else 0}
    except HTTPException:
        raise
    except Exception:
        logger.error("Translation failed for reservation %s", reference)
        raise HTTPException(status_code=503, detail="Translation unavailable. Please try again.")
    finally:
        if reserved and not settled:
            try:
                await asyncio.to_thread(_finish_work, reference, False)
            except Exception:
                logger.error("Translation reservation needs reconciliation: %s", reference)
        _WORK_SLOTS.release()


@app.post("/minutes")
async def generate_minutes_endpoint(request: Request):
    return await _generate_minutes(request)


@app.post("/minutes/docx")
async def generate_minutes_docx_endpoint(request: Request):
    return await _generate_minutes(request, docx=True)


# ── Credits (pay-as-you-go) ───────────────────────────────────────────────────
# Server-side source of truth for packs and prices; the apps only display
# what /credits/packs returns. 1 credit = 1 audio minute (2 on the largest
# model); speaker identification is included; an AI minutes document is 5.
# Balances change only through the apply_credits() SQL function, which is
# idempotent per (kind, reference) so retries never double-count.
CREDIT_PACKS = [
    {"id": "starter",  "name": "Starter",  "credits": 100,  "price_ngn": 1500},
    {"id": "standard", "name": "Standard", "credits": 350,  "price_ngn": 4500},
    {"id": "pro",      "name": "Pro",      "credits": 1000, "price_ngn": 12000},
    {"id": "business", "name": "Business", "credits": 3000, "price_ngn": 33000},
]
CREDITS_PER_MINUTE = {
    "whisper-tiny": 1, "whisper-small": 1, "whisper-medium": 1, "whisper-large-v3": 2,
}
MINUTES_DOC_CREDITS = 5
_FIREBASE_PROJECT = os.getenv("FIREBASE_PROJECT_ID", "clarifai-11cb7")
_JOB_BILLING: dict = {}


def _credits_for_minutes(minutes: float, model_key: str) -> int:
    import math
    rate = CREDITS_PER_MINUTE.get(model_key, 1)
    return max(1, math.ceil(max(minutes, 0.0) - 1e-9)) * rate


# ConsulMeet's live notetaker has no Firebase user. With the shared secret it
# acts as this service account, which needs a complimentary user_profiles row
# (created by the VAPT migration) so it is never charged.
_NOTETAKER_SHARED_SECRET = os.getenv("NOTETAKER_SHARED_SECRET", "")
NOTETAKER_UID = "consulmeet-notetaker"


def _verified_uid(request: Request) -> Optional[str]:
    """Firebase uid from a verified 'Authorization: Bearer <ID token>', or None.

    Missing tokens are rejected by _require_uid. Body user IDs never
    establish identity.
    """
    key = request.headers.get("x-notetaker-key", "")
    if _NOTETAKER_SHARED_SECRET and key and hmac.compare_digest(key, _NOTETAKER_SHARED_SECRET):
        return NOTETAKER_UID
    auth = request.headers.get("authorization", "")
    if not auth.lower().startswith("bearer "):
        return None
    token = auth.split(" ", 1)[1].strip()
    try:
        from google.oauth2 import id_token as _gid
        from google.auth.transport import requests as _gareq
        claims = _gid.verify_firebase_token(token, _gareq.Request(), audience=_FIREBASE_PROJECT)
        return (claims or {}).get("user_id") or (claims or {}).get("sub")
    except Exception as e:
        logger.warning(f"Firebase token rejected: {type(e).__name__}")
        raise HTTPException(status_code=401, detail="Your session has expired. Please sign in again.")


def _billing_profile(uid: str) -> Optional[dict]:
    rows = _supabase_request(
        "GET", "/rest/v1/user_profiles",
        params={"firebase_uid": f"eq.{uid}", "select": "credits,plan,plan_expires_at,disabled_at", "limit": "1"},
    )
    if rows is None:
        raise HTTPException(status_code=503, detail="Billing temporarily unavailable")
    return rows[0] if rows and isinstance(rows, list) else None


def _is_unlimited(profile: Optional[dict]) -> bool:
    """Complimentary accounts, and anyone still inside a paid subscription
    period from before credits launched, are never charged."""
    if not profile:
        return False
    plan = (profile.get("plan") or "free").lower()
    expires = profile.get("plan_expires_at")
    if plan == "complimentary" and not expires:
        return True
    if plan in ("complimentary", "pro", "team") and expires:
        from datetime import datetime, timezone
        try:
            return datetime.fromisoformat(expires.replace("Z", "+00:00")) > datetime.now(timezone.utc)
        except ValueError:
            return False
    return False


def _apply_credits(uid: str, delta: int, kind: str, reference: Optional[str], note: str = "") -> Optional[int]:
    res = _supabase_request(
        "POST", "/rest/v1/rpc/apply_credits",
        payload={"p_uid": uid, "p_delta": int(delta), "p_kind": kind,
                 "p_reference": reference, "p_note": note or None},
    )
    if res is None:
        logger.error(f"Credit {kind} of {delta} for {uid} ({reference}) FAILED")
        return None
    return res if isinstance(res, int) else None


def _probe_duration_sec(content: bytes, filename: str) -> Optional[float]:
    """Audio length via ffprobe, to check the balance before starting."""
    import re, subprocess, tempfile
    suffix = os.path.splitext(filename or "")[1] or ".bin"
    try:
        with tempfile.NamedTemporaryFile(suffix=suffix) as f:
            f.write(content)
            f.flush()
            out = subprocess.run(
                ["ffprobe", "-v", "error", "-show_entries", "format=duration",
                 "-of", "default=nw=1:nk=1", f.name],
                capture_output=True, text=True, timeout=30,
            )
            try:
                return float(out.stdout.strip())
            except ValueError:
                pass
            # Browser recordings (MediaRecorder WebM) carry no duration in the
            # header, so ffprobe says "N/A". Decode the audio and read the time
            # ffmpeg reached instead.
            out = subprocess.run(
                ["ffmpeg", "-hide_banner", "-nostdin", "-i", f.name,
                 "-map", "0:a:0", "-f", "null", "-"],
                capture_output=True, text=True, timeout=120,
            )
            times = re.findall(r"time=(\d+):(\d+):(\d+(?:\.\d+)?)", out.stderr)
            if not times:
                return None
            h, m, s = times[-1]
            return int(h) * 3600 + int(m) * 60 + float(s)
    except Exception as e:
        logger.warning("Could not probe audio duration")
        return None


def _not_enough_credits(needed: int, balance: int) -> HTTPException:
    return HTTPException(
        status_code=402,
        detail={
            "code": "insufficient_credits",
            "message": f"This needs about {needed} credits and you have {balance}. Buy more credits to continue.",
            "needed": needed,
            "balance": balance,
        },
    )


# Custom amounts: the buyer types any naira amount. The smallest pack's rate
# applies, and each bigger pack's rate kicks in once the amount reaches that
# pack's size, so a custom amount is never worse than the packs (and buying
# exactly a pack's price gives exactly that pack's credits).
CUSTOM_MIN_NGN = 500
CUSTOM_MAX_NGN = 500_000
# iPhone can't take a free amount (Apple sells fixed-price products only), so
# it gets these presets; the four pack prices are the existing pack products.
APPLE_PRESET_NGN = [1000, 1500, 2500, 4500, 7500, 12000, 20000, 33000]


def credits_for_naira(naira: int) -> int:
    tiers = sorted(CREDIT_PACKS, key=lambda p: p["credits"])
    best = (naira * tiers[0]["credits"]) // tiers[0]["price_ngn"]
    for t in tiers[1:]:
        c = (naira * t["credits"]) // t["price_ngn"]
        if c >= t["credits"]:
            best = max(best, c)
    return best


@app.get("/credits/packs")
async def credit_packs():
    return {
        "packs": CREDIT_PACKS,
        "credits_per_minute": CREDITS_PER_MINUTE,
        "minutes_doc_credits": MINUTES_DOC_CREDITS,
        "currency": "NGN",
        "custom": {
            "min_ngn": CUSTOM_MIN_NGN,
            "max_ngn": CUSTOM_MAX_NGN,
            "tiers": [{"credits": p["credits"], "price_ngn": p["price_ngn"]} for p in sorted(CREDIT_PACKS, key=lambda p: p["credits"])],
            "apple_presets": [{"price_ngn": n, "credits": credits_for_naira(n),
                               "product_id": f"com.consulaw.narratifai.credits.{_apple_preset_suffix(n)}"} for n in APPLE_PRESET_NGN],
        },
    }


def _apple_preset_suffix(naira: int) -> str:
    """Pack prices reuse the original pack products; other presets are ngn<amount>."""
    pack = next((p for p in CREDIT_PACKS if p["price_ngn"] == naira), None)
    return pack["id"] if pack else f"ngn{naira}"


@app.get("/credits/quote")
async def credit_quote(amount_ngn: int):
    if amount_ngn < CUSTOM_MIN_NGN or amount_ngn > CUSTOM_MAX_NGN:
        raise HTTPException(status_code=400, detail=f"Choose an amount between NGN {CUSTOM_MIN_NGN:,} and NGN {CUSTOM_MAX_NGN:,}.")
    return {"amount_ngn": amount_ngn, "credits": credits_for_naira(amount_ngn)}


_SETTINGS_CACHE: dict = {"at": 0.0, "values": {}}


def _platform_setting(key: str, default=True):
    """A system_settings value (switches set in the admin portal), cached 30 s.
    If Supabase can't be read, the default wins so an outage never blocks users."""
    if time.time() - _SETTINGS_CACHE["at"] > 30:
        rows = _supabase_request("GET", "/rest/v1/system_settings", params={"select": "key,value"})
        if isinstance(rows, list):
            _SETTINGS_CACHE["values"] = {r.get("key"): r.get("value") for r in rows}
            _SETTINGS_CACHE["at"] = time.time()
    value = _SETTINGS_CACHE["values"].get(key, default)
    if isinstance(value, str) and value.lower() in ("true", "false"):
        return value.lower() == "true"
    return value


def _paused(key: str, what: str) -> Optional[HTTPException]:
    if _platform_setting(key, True) is False:
        note = _platform_setting("maintenance_message", "") or ""
        return HTTPException(status_code=503, detail=(note.strip() or f"{what} is paused for maintenance. Please try again soon."))
    return None


def _require_staff(request: Request, permission: str) -> str:
    """Email of an active admin_staff member, from a verified Firebase token."""
    auth = request.headers.get("authorization", "")
    if not auth.lower().startswith("bearer "):
        raise HTTPException(status_code=401, detail="Sign in as staff.")
    try:
        from google.oauth2 import id_token as _gid
        from google.auth.transport import requests as _gareq
        claims = _gid.verify_firebase_token(auth.split(" ", 1)[1].strip(), _gareq.Request(),
                                            audience=_FIREBASE_PROJECT) or {}
    except Exception:
        raise HTTPException(status_code=401, detail="Your session has expired. Please sign in again.")
    email = (claims.get("email") or "").lower()
    rows = _supabase_request("GET", "/rest/v1/admin_staff",
                             params={"email": f"eq.{email}", "select": "role,active", "limit": "1"}) if email else None
    if not rows or rows[0].get("active") is False:
        raise HTTPException(status_code=403, detail="Staff only.")
    allowed = {"super_admin": {"credits:write", "payments:read"},
               "ops_admin": {"credits:write", "payments:read"}}
    if permission not in allowed.get(rows[0].get("role"), set()):
        raise HTTPException(status_code=403, detail="Permission denied")
    # The portal's 2FA session (issued by the admin-2fa function after a
    # server-checked TOTP code). Only its SHA-256 is stored.
    session = request.headers.get("x-admin-session", "")
    sessions = _supabase_request("GET", "/rest/v1/admin_sessions", params={
        "token_hash": f"eq.{hashlib.sha256(session.encode()).hexdigest()}",
        "select": "email,expires_at", "limit": "1",
    }) if session else None
    if not sessions or (sessions[0].get("email") or "").lower() != email:
        raise HTTPException(status_code=401, detail="Confirm your 2FA code again.")
    from datetime import datetime, timezone
    try:
        expires = datetime.fromisoformat(str(sessions[0]["expires_at"]).replace("Z", "+00:00"))
    except Exception:
        expires = None
    if not expires or expires < datetime.now(timezone.utc):
        raise HTTPException(status_code=401, detail="Confirm your 2FA code again.")
    return email


@app.post("/credits/admin-grant")
async def credits_admin_grant(request: Request):
    """Staff adjust a user's balance (support refunds, testers, promotions).
    A negative amount removes credits (never below zero)."""
    staff = await asyncio.to_thread(_require_staff, request, "credits:write")
    body = await request.json()
    target = (body.get("firebase_uid") or "").strip()
    try:
        amount = int(body.get("amount"))
    except (TypeError, ValueError):
        raise HTTPException(status_code=400, detail="amount must be a whole number")
    if not target or amount == 0 or abs(amount) > 100000:
        raise HTTPException(status_code=400, detail="firebase_uid and a non-zero amount (max 100,000) are required")
    note = (body.get("note") or "").strip()[:200]
    payload = {"p_email": staff, "p_uid": target, "p_delta": amount, "p_note": note,
               "p_reference": f"admin:{uuid.uuid4()}"}

    def call():
        # Not _supabase_request: the database's reason is needed to tell staff
        # what went wrong (it only says "failed").
        r = _requests.post(f"{_SUPABASE_URL}/rest/v1/rpc/admin_adjust_credits", json=payload,
                           headers=_sb_headers(), timeout=15)
        try:
            data = r.json() if r.text else {}
        except ValueError:
            data = {}
        return r.status_code, data

    try:
        status, result = await asyncio.to_thread(call)
    except Exception as e:
        logger.warning(f"Admin credit change failed: {type(e).__name__}")
        raise HTTPException(status_code=503, detail="The database could not be reached. Try again in a minute.")
    if status >= 400 or not isinstance(result, dict) or "balance" not in result:
        reason = (result.get("message") or result.get("hint") or "") if isinstance(result, dict) else ""
        logger.warning(f"Admin credit change for {target} refused: HTTP {status} {reason[:120]}")
        known = {
            "permission_denied": "Your staff role can't change credits (super admin or ops admin only).",
            "profile_not_found": "This user has no NarratifAI profile yet. Ask them to open the app once, then try again.",
            "invalid_delta": "Use a whole number between -100,000 and 100,000.",
            "reference_owner_mismatch": "This change clashed with another one. Try again.",
            "account_deleted": "This account is being deleted, so its balance can't change.",
        }
        detail = next((v for k, v in known.items() if k in reason), None)
        if not detail and "deleted" in reason.lower():
            detail = known["account_deleted"]
        raise HTTPException(status_code=409 if detail else 503,
                            detail=detail or f"Could not update the balance ({reason[:120] or f'HTTP {status}'}).")
    balance = result["balance"]
    logger.info(f"Staff {staff} changed {target} by {amount} credits (balance {balance})")
    return {"balance": balance}


@app.get("/credits/admin-ledger/{firebase_uid}")
async def credits_admin_ledger(firebase_uid: str, request: Request):
    """Staff view of a user's last 50 credit movements."""
    await asyncio.to_thread(_require_staff, request, "payments:read")
    rows = await asyncio.to_thread(
        _supabase_request, "GET", "/rest/v1/credit_ledger",
        None, {"firebase_uid": f"eq.{firebase_uid}", "order": "created_at.desc", "limit": "50",
               "select": "delta,balance_after,kind,note,created_at"},
    )
    return {"entries": rows or []}


_WORK_LABEL = {"transcription": "Transcription", "minutes": "Meeting minutes", "translation": "Translation"}


def _credit_history(uid: str) -> list:
    rows = _supabase_request(
        "GET", "/rest/v1/credit_ledger", None,
        {"firebase_uid": f"eq.{uid}", "order": "created_at.desc", "limit": "100",
         "select": "delta,balance_after,kind,note,reference,created_at"},
    ) or []
    refs = sorted({(r.get("reference") or "").removeprefix("settlement:") for r in rows
                   if r.get("kind") in ("charge", "refund") and r.get("reference")})
    kinds = {}
    for i in range(0, len(refs), 40):
        chunk = [x for x in refs[i:i + 40] if x and all(c.isalnum() or c in "-_:." for c in x)]
        if not chunk:
            continue
        found = _supabase_request("GET", "/rest/v1/processing_reservations", None,
                                  {"reference": f"in.({','.join(chunk)})", "select": "reference,kind"}) or []
        kinds.update({f["reference"]: f.get("kind") for f in found})
    out = []
    for r in rows:
        kind, note, ref, delta = r.get("kind"), r.get("note") or "", r.get("reference") or "", r.get("delta") or 0
        settlement = ref.startswith("settlement:")
        work = _WORK_LABEL.get(kinds.get(ref.removeprefix("settlement:")) or "", "")
        detail = ""
        if kind == "signup_bonus":
            label = "Welcome credits"
        elif kind == "purchase":
            label = "Credits bought"
        elif kind == "admin_grant":
            label = "Added by NarratifAI" if delta > 0 else "Adjusted by NarratifAI"
            detail = note
        elif kind == "refund" and (ref.startswith("apple-refund:") or ref.startswith("google-refund:")):
            label = "Store refund"
        elif kind == "refund":
            label = "Returned"
            detail = f"{work or 'Processing'} failed or came out shorter" if settlement else note
        elif note in ("Transfer to team wallet", "Closed team wallet returned to owner"):
            label = "Team wallet"
            detail = note
        else:
            label = work or "Used"
            detail = "Adjusted to the final length" if settlement else ""
        out.append({"label": label, "detail": detail, "delta": delta,
                    "balance_after": r.get("balance_after"), "created_at": r.get("created_at")})
    return out


@app.get("/credits/history")
async def credits_history(request: Request):
    """The signed-in user's last 100 credit movements, in plain words."""
    uid = await asyncio.to_thread(_require_uid, request)
    return {"entries": await asyncio.to_thread(_credit_history, uid)}


def _reserve_work(uid: str, reference: str, cost: int, kind: str, cache_key: Optional[str] = None, companion_id: Optional[str] = None) -> dict:
    if companion_id:
        result = _supabase_request("POST", "/rest/v1/rpc/reserve_companion_processing", payload={
            "p_uid": uid, "p_id": companion_id, "p_cost": cost})
    elif cache_key:
        payload = {"p_uid": uid, "p_reference": reference, "p_cache_key": cache_key}
        if cost != 5:  # minutes keep the SQL default; translation is priced by length
            payload["p_cost"] = cost
        result = _supabase_request("POST", "/rest/v1/rpc/reserve_minutes", payload=payload)
    else:
        result = _supabase_request("POST", "/rest/v1/rpc/reserve_processing", payload={
            "p_uid": uid, "p_reference": reference, "p_cost": cost, "p_kind": kind})
    if not isinstance(result, dict):
        raise HTTPException(status_code=503, detail="Billing temporarily unavailable")
    if result.get("error") == "insufficient_credits":
        raise _not_enough_credits(cost, result.get("balance", 0))
    if result.get("error") == "rate_limited":
        raise HTTPException(status_code=429, detail="Too many jobs. Try again later.")
    if result.get("error"):
        raise HTTPException(status_code=403, detail="Account is unavailable for processing")
    return result


def _finish_work(reference: str, success: bool, cost: int = 0):
    result = _supabase_request("POST", "/rest/v1/rpc/finish_processing", payload={
        "p_reference": reference, "p_success": success, "p_cost": cost})
    if not isinstance(result, dict) or result.get("error"):
        raise RuntimeError("Could not settle processing reservation")
    return result


SENTIMENT_LABELS = ("calm", "neutral", "tense", "enthusiastic", "concerned")


def _speaker_sentiment_input(raw) -> dict:
    """Optional per-speaker tone sent with a minutes request; only known labels are kept."""
    if not isinstance(raw, dict):
        return {}
    return {str(k)[:64]: v for k, v in list(raw.items())[:50]
            if isinstance(v, str) and v in SENTIMENT_LABELS}


def _minutes_input(request: Request, body: dict):
    uid = _require_uid(request)
    if not isinstance(body, dict) or not isinstance(body.get("segments"), list):
        raise HTTPException(status_code=400, detail="Transcript segments required")
    segments = body["segments"]
    if not segments or len(segments) > 5000 or any(not isinstance(s, dict) or not isinstance(s.get("text"), str) for s in segments):
        raise HTTPException(status_code=400, detail="Invalid transcript segments")
    if sum(len(s["text"]) for s in segments) > 100000:
        raise HTTPException(status_code=413, detail="Transcript is too long")
    if not isinstance(body.get("speaker_names", {}), dict) or not isinstance(body.get("session_name", "Meeting"), str):
        raise HTTPException(status_code=400, detail="Invalid meeting metadata")
    return uid


# ── Paystack / Supabase helpers ───────────────────────────────────────────────

def _supabase_update_plan(firebase_uid: str, plan: str, expires_iso: Optional[str], data: dict):
    """Write plan change to Supabase using the service-role key (bypasses RLS)."""
    url = os.getenv("SUPABASE_URL", "")
    key = os.getenv("SUPABASE_SERVICE_ROLE_KEY", "")
    if not url or not key or not _requests_available:
        logger.warning("Supabase service-role key or URL not set — skipping plan update")
        return
    headers = {
        "apikey": key,
        "Authorization": f"Bearer {key}",
        "Content-Type": "application/json",
        "Prefer": "return=minimal",
    }
    payload = {"plan": plan, "plan_expires_at": expires_iso}
    sub_code = data.get("subscription_code") or data.get("subscription", {}).get("subscription_code")
    if sub_code:
        payload["paystack_subscription_code"] = sub_code
    customer = data.get("customer", {})
    customer_code = customer.get("customer_code") if isinstance(customer, dict) else None
    if customer_code:
        payload["paystack_customer_code"] = customer_code
    _requests.patch(
        f"{url}/rest/v1/user_profiles?firebase_uid=eq.{firebase_uid}",
        json=payload,
        headers=headers,
        timeout=10,
    )


def _supabase_increment_audio_minutes(firebase_uid: str, audio_duration_sec: float):
    """Increment audio_minutes_used for a user atomically after a successful transcription."""
    url = os.getenv("SUPABASE_URL", "")
    key = os.getenv("SUPABASE_SERVICE_ROLE_KEY", "")
    if not url or not key or not _requests_available or not firebase_uid:
        return
    minutes_used = max(1, round(audio_duration_sec / 60))
    headers = {
        "apikey": key,
        "Authorization": f"Bearer {key}",
        "Content-Type": "application/json",
        "Prefer": "return=minimal",
    }
    # Atomic increment via Postgres RPC function
    try:
        _requests.post(
            f"{url}/rest/v1/rpc/increment_audio_minutes",
            json={"p_firebase_uid": firebase_uid, "p_minutes": minutes_used},
            headers=headers,
            timeout=10,
        )
    except Exception as exc:
        logger.warning(f"Could not increment audio_minutes_used: {type(exc).__name__}")


def _paystack_plan_expires(data: dict) -> Optional[str]:
    """Extract subscription end date from a Paystack charge.success/subscription.create payload."""
    # subscription object may be nested
    sub = data.get("subscription") or data
    next_date = sub.get("next_payment_date") or sub.get("paid_at")
    if not next_date:
        return None
    # Add 31 days as a safe buffer when exact next-billing isn't present
    from datetime import datetime, timezone, timedelta
    try:
        dt = datetime.fromisoformat(next_date.replace("Z", "+00:00"))
    except ValueError:
        return None
    return (dt + timedelta(days=31)).isoformat()


@app.post("/account/delete")
async def delete_account(request: Request):
    """Delegate identity + database deletion to the durable verified Edge workflow."""
    uid = _verified_uid(request)
    if not uid:
        raise HTTPException(status_code=401, detail="Sign in again to delete your account.")
    if not _SUPABASE_URL or not _SUPABASE_KEY:
        raise HTTPException(status_code=503, detail="Account service unavailable")
    token = request.headers.get("authorization", "").split(" ", 1)[-1]
    try:
        resp = await asyncio.to_thread(_requests.post,
            f"{_SUPABASE_URL}/functions/v1/account-delete",
            headers={"apikey": _SUPABASE_KEY, "x-firebase-token": token},
            json={"confirm": "DELETE"}, timeout=60)
        data = resp.json()
    except Exception:
        raise HTTPException(status_code=503, detail="Deletion service unavailable. Please retry.")
    if resp.status_code not in (200, 202):
        raise HTTPException(status_code=resp.status_code, detail=data.get("error", "Could not delete account"))
    return JSONResponse(data, status_code=resp.status_code)


@app.post("/paystack/init")
async def paystack_init(request: Request):
    uid = await asyncio.to_thread(_require_uid, request)
    paused = _paused("allow_payments", "Buying credits")
    if paused:
        raise paused
    secret = os.getenv("PAYSTACK_SECRET_KEY", "")
    if not secret or not _requests_available:
        raise HTTPException(status_code=503, detail="Payments temporarily unavailable")
    try:
        body = await request.json()
    except Exception:
        raise HTTPException(status_code=400, detail="Invalid JSON")
    if not isinstance(body, dict):
        raise HTTPException(status_code=400, detail="Invalid payment request")
    profiles = await asyncio.to_thread(_supabase_request, "GET", "/rest/v1/user_profiles", None,
                                      {"firebase_uid": f"eq.{uid}", "select": "email", "limit": "1"})
    email = profiles[0].get("email") if profiles else None
    if not email:
        raise HTTPException(status_code=503, detail="Billing email unavailable")
    pack = next((p for p in CREDIT_PACKS if p["id"] == body.get("pack_id")), None)
    if pack:
        naira, credits = pack["price_ngn"], pack["credits"]
    else:
        naira = body.get("amount_ngn")
        if isinstance(naira, bool) or not isinstance(naira, int) or not CUSTOM_MIN_NGN <= naira <= CUSTOM_MAX_NGN:
            raise HTTPException(status_code=400, detail="Choose a valid credit pack or whole-naira amount")
        credits = credits_for_naira(naira)
    reference = "narratifai-" + uuid.uuid4().hex
    order = await asyncio.to_thread(_supabase_request, "POST", "/rest/v1/payment_orders", {
        "reference": reference, "firebase_uid": uid, "email": email,
        "amount": naira * 100, "currency": "NGN", "credits": credits,
    })
    if not order:
        raise HTTPException(status_code=503, detail="Could not create payment order")
    callback = body.get("callback_url") or "narratifai://paystack-callback"
    if callback not in ("narratifai://paystack-callback", "https://narratifai.com/pricing?paid=1",
                         "https://www.narratifai.com/pricing?paid=1"):
        raise HTTPException(status_code=400, detail="Invalid payment callback")
    try:
        response = await asyncio.to_thread(_requests.post,
            "https://api.paystack.co/transaction/initialize",
            json={"email": email, "amount": naira * 100, "currency": "NGN",
                  "reference": reference, "callback_url": callback,
                  "metadata": {"firebase_uid": uid}},
            headers={"Authorization": f"Bearer {secret}"}, timeout=20)
        data = response.json().get("data", {})
        if response.status_code != 200 or data.get("reference") != reference or not data.get("authorization_url"):
            raise ValueError("Payment initialization failed")
    except Exception:
        raise HTTPException(status_code=502, detail="Could not start payment. Please try again.")
    return {"authorization_url": data["authorization_url"], "reference": reference, "credits": credits}


# ── Apple in-app purchase (iOS) ───────────────────────────────────────────────
# Credit packs are consumable IAPs with product ids
# com.consulaw.narratifai.credits.<pack id>. The app sends the StoreKit 2
# signed transaction here; it is verified against Apple's certificate chain
# (src/apple_iap.py), so no App Store API key is needed.
APPLE_BUNDLE_ID = "com.consulaw.narratifai"
# Sandbox purchases (TestFlight, App Review) are free, so they only fund
# accounts we choose: the App Review demo account plus any Firebase uids in
# APPLE_SANDBOX_UIDS (comma separated). Everyone else is refused.
APPLE_SANDBOX_UIDS = {"IcN3wZSLoaac1wXAKoCsLKzKsX02"} | {
    u.strip() for u in os.environ.get("APPLE_SANDBOX_UIDS", "").split(",") if u.strip()}
APPLE_PRODUCT_PREFIX = "com.consulaw.narratifai.credits."


def _apple_pack(product_id: str) -> Optional[dict]:
    """The pack (or preset amount) an App Store product id stands for."""
    if not product_id.startswith(APPLE_PRODUCT_PREFIX):
        return None
    suffix = product_id[len(APPLE_PRODUCT_PREFIX):]
    pack = next((p for p in CREDIT_PACKS if p["id"] == suffix), None)
    if pack:
        return pack
    if suffix.startswith("ngn") and suffix[3:].isdigit() and int(suffix[3:]) in APPLE_PRESET_NGN:
        naira = int(suffix[3:])
        return {"id": suffix, "name": "Custom amount", "credits": credits_for_naira(naira), "price_ngn": naira}
    return None


@app.post("/credits/apple")
async def credits_apple(request: Request):
    """Credit a verified App Store purchase. Safe to call more than once for
    the same transaction: it is only ever credited once."""
    from src.apple_iap import verify_jws, AppleJWSError, account_token
    uid = await asyncio.to_thread(_require_uid, request)
    body = await request.json()
    try:
        tx = verify_jws(str(body.get("signed_transaction") or ""))
    except AppleJWSError as e:
        logger.warning(f"Apple purchase rejected for {uid}: {type(e).__name__}")
        raise HTTPException(status_code=400, detail="We couldn't verify this purchase with Apple.")
    pack = _apple_pack(tx.get("productId") or "")
    if tx.get("bundleId") != APPLE_BUNDLE_ID or not pack or tx.get("type") not in (None, "Consumable"):
        raise HTTPException(status_code=400, detail="This purchase isn't a NarratifAI credit pack.")
    if tx.get("revocationDate"):
        raise HTTPException(status_code=400, detail="Apple has refunded this purchase.")
    env = tx.get("environment")
    if env != "Production" and not (env == "Sandbox" and uid in APPLE_SANDBOX_UIDS):
        raise HTTPException(status_code=403, detail="Test purchases cannot fund production credits.")
    token = tx.get("appAccountToken")
    if token != account_token(uid):
        logger.warning(f"Apple transaction {tx.get('transactionId')} belongs to another account (caller {uid})")
        raise HTTPException(status_code=403, detail="This purchase was made from a different NarratifAI account.")
    tx_id = str(tx.get("transactionId") or "")
    if not tx_id:
        raise HTTPException(status_code=400, detail="We couldn't verify this purchase with Apple.")
    reference = f"apple:{tx_id}"
    prior = await asyncio.to_thread(_supabase_request, "GET", "/rest/v1/credit_ledger",
                                    None, {"kind": "eq.purchase", "reference": f"eq.{reference}", "select": "firebase_uid", "limit": "1"})
    if prior:
        if prior[0].get("firebase_uid") != uid:
            raise HTTPException(status_code=403, detail="This purchase was already added to a different account.")
        profile = await asyncio.to_thread(_billing_profile, uid)
        return {"balance": int((profile or {}).get("credits") or 0), "credits_added": 0, "already_credited": True}
    qty = max(1, int(tx.get("quantity") or 1))
    credits = pack["credits"] * qty
    sandbox = tx.get("environment") == "Sandbox"
    # Sandbox purchases (TestFlight, App Review) cost nothing: record NGN 0 so
    # they never show up as revenue.
    note = (f"{pack['name']} pack, NGN 0 (Apple sandbox test)" if sandbox
            else (f"Custom amount, NGN {pack['price_ngn'] * qty:,} (Apple)" if pack["id"].startswith("ngn")
                  else f"{pack['name']} pack, NGN {pack['price_ngn'] * qty:,} (Apple)"))
    balance = await asyncio.to_thread(_apply_credits, uid, credits, "purchase", reference, note)
    if balance is None:
        raise HTTPException(status_code=500, detail="Your payment went through but the credits didn't save. Reopen the app to retry.")
    logger.info(f"Apple purchase {tx_id}: +{credits} credits for {uid} ({'sandbox' if sandbox else 'production'})")
    return {"balance": balance, "credits_added": credits, "already_credited": False}


@app.post("/apple/notifications")
async def apple_notifications(request: Request):
    """App Store Server Notifications V2. A refunded or revoked credit pack
    takes its credits back (never below zero)."""
    from src.apple_iap import verify_jws, AppleJWSError
    body = await request.json()
    try:
        note = verify_jws(str(body.get("signedPayload") or ""))
    except AppleJWSError as e:
        logger.warning(f"Apple notification rejected: {type(e).__name__}")
        raise HTTPException(status_code=400, detail="invalid signature")
    kind = note.get("notificationType")
    data = note.get("data") or {}
    if data.get("bundleId") != APPLE_BUNDLE_ID or kind not in ("REFUND", "REVOKE"):
        return {"ok": True}
    try:
        tx = verify_jws(str(data.get("signedTransactionInfo") or ""))
    except AppleJWSError:
        return {"ok": True}
    if tx.get("environment") != "Production" or tx.get("bundleId") != APPLE_BUNDLE_ID:
        return {"ok": True}
    tx_id = str(tx.get("transactionId") or "")
    rows = await asyncio.to_thread(_supabase_request, "GET", "/rest/v1/credit_ledger",
                                   None, {"kind": "eq.purchase", "reference": f"eq.apple:{tx_id}", "select": "firebase_uid,delta", "limit": "1"})
    if not rows:
        logger.warning(f"Apple {kind} for unknown transaction {tx_id}")
        return {"ok": True}
    uid, delta = rows[0]["firebase_uid"], int(rows[0]["delta"])
    await asyncio.to_thread(_apply_credits, uid, -delta, "refund", f"apple-refund:{tx_id}", f"Apple {kind.lower()}: purchase {tx_id} reversed")
    logger.info(f"Apple {kind} {tx_id}: -{delta} credits for {uid}")
    return {"ok": True}


# ── Google Play Billing (Android) ────────────────────────────────────────────
# Same product ids and packs as the App Store. The app sends the purchase
# token; src/google_play.py asks Google what it really is, then the pack is
# credited once (reference google:<orderId>) and consumed so it can be bought
# again. Test purchases by license testers cost nothing, so like Apple sandbox
# they only fund the accounts in APPLE_SANDBOX_UIDS.


@app.post("/credits/google")
async def credits_google(request: Request):
    """Credit a verified Google Play purchase. Safe to call more than once for
    the same purchase: it is only ever credited once."""
    from src import google_play
    from src.apple_iap import account_token
    uid = await asyncio.to_thread(_require_uid, request)
    body = await request.json()
    product_id = str(body.get("product_id") or "")
    purchase_token = str(body.get("purchase_token") or "")
    pack = _apple_pack(product_id)
    if not pack or not purchase_token:
        raise HTTPException(status_code=400, detail="This purchase isn't a NarratifAI credit pack.")
    try:
        purchase = await asyncio.to_thread(google_play.get_purchase, product_id, purchase_token)
    except google_play.GooglePlayError as e:
        logger.warning(f"Google Play purchase check failed for {uid}: {e}")
        raise HTTPException(status_code=503 if e.retryable else 400,
                            detail="We couldn't verify this purchase with Google Play." if not e.retryable
                            else "Google Play is not reachable right now. Your purchase is safe and will be added shortly.")
    state = purchase.get("purchaseState")
    if state == 2:
        raise HTTPException(status_code=409, detail="Google Play is still processing this payment.")
    if state != 0:
        raise HTTPException(status_code=400, detail="This purchase was cancelled or refunded.")
    if purchase.get("obfuscatedExternalAccountId") != account_token(uid):
        logger.warning(f"Google purchase {purchase.get('orderId')} belongs to another account (caller {uid})")
        raise HTTPException(status_code=403, detail="This purchase was made from a different NarratifAI account.")
    test = purchase.get("purchaseType") == 0
    if test and uid not in APPLE_SANDBOX_UIDS:
        raise HTTPException(status_code=403, detail="Test purchases cannot fund production credits.")
    order_id = str(purchase.get("orderId") or "")
    if not order_id:
        raise HTTPException(status_code=400, detail="We couldn't verify this purchase with Google Play.")
    reference = f"google:{order_id}"
    prior = await asyncio.to_thread(_supabase_request, "GET", "/rest/v1/credit_ledger",
                                    None, {"kind": "eq.purchase", "reference": f"eq.{reference}", "select": "firebase_uid", "limit": "1"})
    if prior:
        if prior[0].get("firebase_uid") != uid:
            raise HTTPException(status_code=403, detail="This purchase was already added to a different account.")
        if purchase.get("consumptionState") != 1:
            await asyncio.to_thread(google_play.consume, product_id, purchase_token)
        profile = await asyncio.to_thread(_billing_profile, uid)
        return {"balance": int((profile or {}).get("credits") or 0), "credits_added": 0, "already_credited": True}
    qty = max(1, int(purchase.get("quantity") or 1))
    credits = pack["credits"] * qty
    note = (f"{pack['name']} pack, NGN 0 (Google Play test)" if test
            else (f"Custom amount, NGN {pack['price_ngn'] * qty:,} (Google Play, {purchase.get('regionCode') or 'unknown region'})" if pack["id"].startswith("ngn")
                  else f"{pack['name']} pack, NGN {pack['price_ngn'] * qty:,} (Google Play, {purchase.get('regionCode') or 'unknown region'})"))
    balance = await asyncio.to_thread(_apply_credits, uid, credits, "purchase", reference, note)
    if balance is None:
        raise HTTPException(status_code=500, detail="Your payment went through but the credits didn't save. Reopen the app to retry.")
    if not await asyncio.to_thread(google_play.consume, product_id, purchase_token):
        logger.warning(f"Google purchase {order_id} credited but not consumed yet; the next check retries")
    logger.info(f"Google purchase {order_id}: +{credits} credits for {uid} ({'test' if test else 'production'})")
    return {"balance": balance, "credits_added": credits, "already_credited": False}


def _google_voided_sync() -> int:
    """Take back credits for Google Play purchases refunded or charged back in
    the last 30 days. Each reversal is recorded once (google-refund:<orderId>)."""
    from src import google_play
    if not google_play.configured():
        return 0
    since = int((time.time() - 30 * 86400) * 1000)
    reversed_count = 0
    for v in google_play.voided_purchases(since):
        order_id = str(v.get("orderId") or "")
        if not order_id:
            continue
        rows = _supabase_request("GET", "/rest/v1/credit_ledger", None,
                                 {"kind": "eq.purchase", "reference": f"eq.google:{order_id}", "select": "firebase_uid,delta", "limit": "1"})
        if not rows:
            continue
        uid, delta = rows[0]["firebase_uid"], int(rows[0]["delta"])
        if _apply_credits(uid, -delta, "refund", f"google-refund:{order_id}", f"Google Play refund: order {order_id} reversed") is not None:
            reversed_count += 1
    return reversed_count


async def _google_voided_loop():
    while True:
        try:
            n = await asyncio.to_thread(_google_voided_sync)
            if n:
                logger.info(f"Google Play refunds checked: {n} purchase(s) reversed or already reversed")
        except Exception as exc:
            logger.warning(f"Google Play refund check failed: {type(exc).__name__}")
        await asyncio.sleep(6 * 3600)


def _fulfill_paystack_charge(data):
    from src.payments import charge_payload, fulfillment_succeeded
    try:
        payload = charge_payload(data)
    except ValueError:
        raise HTTPException(status_code=400, detail="Invalid payment event")
    result = _supabase_request("POST", "/rest/v1/rpc/fulfill_payment_order", payload)
    if not fulfillment_succeeded(result):
        logger.error("Paystack fulfillment not completed for reference %s", payload["p_reference"])
        raise HTTPException(status_code=503, detail="Payment not credited yet; retry required")
    return result


@app.post("/paystack/verify")
async def paystack_verify(request: Request):
    uid = await asyncio.to_thread(_require_uid, request)
    try:
        body = await request.json()
    except Exception:
        raise HTTPException(status_code=400, detail="Invalid JSON")
    reference = body.get("reference") if isinstance(body, dict) else None
    if not isinstance(reference, str) or not reference or len(reference) > 200:
        raise HTTPException(status_code=400, detail="Payment reference required")
    orders = await asyncio.to_thread(_supabase_request, "GET", "/rest/v1/payment_orders", None,
        {"reference": f"eq.{reference}", "firebase_uid": f"eq.{uid}",
         "select": "reference,credits,fulfilled_at", "limit": "1"})
    if orders is None:
        raise HTTPException(status_code=503, detail="Payment status unavailable")
    if not orders:
        raise HTTPException(status_code=404, detail="Payment order not found")
    order = orders[0]
    if order.get("fulfilled_at"):
        return {"credited": True, "credits": order["credits"], "reference": reference}
    secret = os.getenv("PAYSTACK_SECRET_KEY", "")
    if not secret:
        raise HTTPException(status_code=503, detail="Payment verification unavailable")
    from src.payments import verified_charge
    try:
        data = await asyncio.to_thread(verified_charge, reference, secret)
    except Exception:
        raise HTTPException(status_code=503, detail="Could not verify payment; retry shortly")
    if data.get("domain") != "live" or data.get("status") != "success":
        return {"credited": False, "status": data.get("status", "pending"), "reference": reference}
    await asyncio.to_thread(_fulfill_paystack_charge, data)
    return {"credited": True, "credits": order["credits"], "reference": reference}


@app.post("/paystack/webhook")
async def paystack_webhook(request: Request):
    """Receive and verify Paystack webhook events; update Supabase on subscription changes."""
    secret = os.getenv("PAYSTACK_SECRET_KEY", "")
    body = await request.body()
    sig = request.headers.get("x-paystack-signature", "")
    if not secret:
        # Without the secret the signature can't be checked; never trust an
        # unsigned "payment succeeded".
        logger.error("Paystack webhook received but PAYSTACK_SECRET_KEY is not set")
        raise HTTPException(status_code=503, detail="Payments not configured")
    expected = hmac.new(secret.encode(), body, hashlib.sha512).hexdigest()
    if not hmac.compare_digest(sig, expected):
        raise HTTPException(status_code=403, detail="Invalid signature")

    try:
        event = json.loads(body)
    except Exception:
        raise HTTPException(status_code=400, detail="Invalid JSON")

    if not isinstance(event, dict) or event.get("event") != "charge.success":
        return {"ok": True}
    data = event.get("data")
    if not isinstance(data, dict):
        raise HTTPException(status_code=400, detail="Invalid payment event")
    if data.get("domain") != "live" or data.get("status") != "success":
        return {"ok": True}
    await asyncio.to_thread(_fulfill_paystack_charge, data)
    return {"ok": True}



# ---------------------------------------------------------------------------
# GPU-aware transcription shim
# On HuggingFace Spaces with ZeroGPU this acquires a shared A100 for the
# duration of the call then releases it back to the pool.  Everywhere else
# (Modal, local) it is a plain function call.
# ---------------------------------------------------------------------------
if _HF_ZERO_GPU:
    @_spaces.GPU(duration=300)
    def _transcribe_with_engine(content: bytes, filename: str, **kwargs):
        return engine.transcribe_bytes(content, filename=filename, **kwargs)
else:
    def _transcribe_with_engine(content: bytes, filename: str, **kwargs):
        return engine.transcribe_bytes(content, filename=filename, **kwargs)


# The engine holds one "current model" shared by every job. Switching it at
# submit time (as this used to) let a second upload swap the model out from
# under a job that was still running. Each job now selects its own model and
# runs inside this lock, so concurrent uploads queue instead of colliding.
_ENGINE_LOCK = threading.Lock()

# ── Keep-alive while jobs run ─────────────────────────────────────────────────
# Both hosts sleep/scale down after a period with no *incoming requests*,
# regardless of work in progress. That used to force long idle windows
# (HF 1 h, Modal 1 h) so a job didn't die when the phone stopped polling,
# and the idle GPU became the biggest serving cost. Instead, while any job
# is running the server requests its own public URL every few minutes,
# which counts as traffic on both hosts, so the idle window can be short.
_ACTIVE_JOBS = 0
_ACTIVE_LOCK = threading.Lock()


def _self_url() -> str:
    explicit = os.getenv("SELF_URL", "").rstrip("/")
    if explicit:
        return explicit
    host = os.getenv("SPACE_HOST", "")  # set by Hugging Face Spaces
    return f"https://{host}" if host else ""


def _keepalive_loop() -> None:
    while True:
        time.sleep(240)
        url = _self_url()
        if _ACTIVE_JOBS > 0 and url and _requests_available:
            try:
                _requests.get(f"{url}/health", timeout=15)
            except Exception as e:
                logger.warning(f"Keep-alive ping failed: {type(e).__name__}")


threading.Thread(target=_keepalive_loop, name="keepalive", daemon=True).start()


def _job_started() -> None:
    global _ACTIVE_JOBS
    with _ACTIVE_LOCK:
        _ACTIVE_JOBS += 1


def _job_finished() -> None:
    global _ACTIVE_JOBS
    with _ACTIVE_LOCK:
        _ACTIVE_JOBS = max(0, _ACTIVE_JOBS - 1)


def _default_model_key() -> str:
    return engine.config.get("models", {}).get("default") or engine.current_model_key


def _drop_repetition_segments(segments: list) -> list:
    """Remove hallucinated loops segment by segment instead of failing the job.

    Long meetings legitimately repeat phrases ("all in favour", the agenda
    title), so judging the whole transcript at once rejected real 30-60 min
    recordings after all the work was done. Here only segments that are
    themselves loops, or the 4th+ consecutive copy of the same text, go.
    """
    cleaned = []
    run_text, run_len = None, 0
    for seg in segments:
        text = (seg.get("text") or "").strip()
        if not text:
            continue
        key = text.lower()
        run_len = run_len + 1 if key == run_text else 1
        run_text = key
        if run_len > 3 or _is_repetition_loop(text):
            logger.info("Dropped repeated/looping segment")
            continue
        cleaned.append(seg)
    return cleaned


_SENTENCE_SPLIT = __import__("re").compile(r"(?<=[.!?])\s+")


def _collapse_repeated_sentences(segments: list) -> list:
    """Drop a sentence that exactly repeats one of the 3 sentences before it.

    Whisper sometimes loops inside a 30 s window ("X. Y. X. X.") without the
    whole segment looking like a loop. A person repeating a full 5+ word
    sentence verbatim within a few sentences is rare, so the copy is
    removed; short replies ("Yes. Yes.") are left alone.
    """
    import re
    norm = lambda t: " ".join(re.sub(r"[^a-z0-9' ]", " ", t.lower()).split())
    recent: list = []
    out = []
    for seg in segments:
        kept = []
        for sentence in _SENTENCE_SPLIT.split((seg.get("text") or "").strip()):
            key = norm(sentence)
            if key and key in recent and len(key.split()) >= 5:
                continue
            if key:
                recent = (recent + [key])[-3:]
            kept.append(sentence)
        text = " ".join(kept).strip()
        if text:
            out.append({**seg, "text": text})
    return out


LONG_RECORDING_SEC = 600   # recordings this long also get an email when ready

# A failed job's detail is what the user is told, then, after this marker,
# what staff need to diagnose it. /result only ever returns the first part.
_STAFF_DETAIL = " | staff: "
_UNREADABLE_AUDIO = ("invalid data", "could not decode", "ffmpeg", "libsndfile", "soundfile",
                     "unsupported format", "audio file could not be read", "no audio stream")


def _failure_detail(e: BaseException) -> str:
    """Plain reason for the user plus the technical one for staff."""
    name, text = type(e).__name__, str(e)
    low = f"{name} {text}".lower()
    if "out of memory" in low or name == "OutOfMemoryError":
        user = "The transcription server was too busy for this recording. Please try again in a few minutes."
    elif any(k in low for k in _UNREADABLE_AUDIO):
        user = "We couldn't read this audio file. Try exporting it as MP3, M4A or WAV and uploading it again."
    elif "timeout" in low or "timed out" in low:
        user = "This recording took too long to process. Please try again, or split it into shorter parts."
    else:
        user = "Something went wrong on our side while transcribing. Please try again."
    return f"{user}{_STAFF_DETAIL}{name}: {text[:300]}"


def _user_detail(detail: Optional[str]) -> str:
    return (detail or "").split(_STAFF_DETAIL)[0].strip()


def _worth_retrying(e: BaseException) -> bool:
    """A second attempt helps with server-side hiccups, not with a bad file."""
    low = f"{type(e).__name__} {e}".lower()
    return not any(k in low for k in _UNREADABLE_AUDIO)


def _notify(uid: str, kind: str, title: str, body: str, data: dict) -> None:
    """In-app notification; the database hands it on for email and push
    (notify-dispatch). Never fails the job."""
    if not uid or uid == NOTETAKER_UID:
        return
    try:
        _supabase_request("POST", "/rest/v1/notifications", payload={
            "firebase_uid": uid, "kind": kind, "title": title[:120], "body": body[:400], "data": data})
    except Exception as e:
        logger.warning(f"Notification not saved: {type(e).__name__}")


def _run_transcription_sync(
    jid: str,
    content: bytes,
    filename: str,
    model_key: Optional[str],
    **kwargs,
):
    """Sync worker running in ThreadPoolExecutor — returns immediately so 202 is sent."""
    _job_started()
    settled = False
    try:
        if _is_cancelled(jid):
            raise _JobCancelled()
        with _ENGINE_LOCK:
            target_model = model_key or _default_model_key()
            if target_model != engine.current_model_key:
                engine.set_model(target_model)
            # One automatic retry for unexpected server errors, so a passing
            # problem (a model that failed to load, a GPU hiccup) never
            # reaches the user. Nothing is charged until the job settles.
            for attempt in (1, 2):
                try:
                    result = _transcribe_with_engine(content, filename, **kwargs)
                    break
                except _JobCancelled:
                    raise
                except Exception as e:
                    if attempt == 2 or not _worth_retrying(e) or _is_cancelled(jid):
                        raise
                    logger.warning(f"Job {jid} attempt 1 failed ({type(e).__name__}: {e}); retrying once",
                                   exc_info=True)

        if result.segments:
            result.segments = _collapse_repeated_sentences(
                _drop_repetition_segments(result.segments)
            )
            result.text = " ".join((seg.get("text") or "").strip() for seg in result.segments)
        loop_only = not result.segments and _is_repetition_loop(result.text or "")
        if loop_only or not (result.text or "").strip():
            logger.warning("No usable speech after loop cleanup")
            _upsert_job(
                jid,
                status="error",
                detail=(
                    "Transcription failed: no clear speech was recognised. "
                    "Try selecting the correct language manually or a larger model."
                ),
            )
            return

        if result.segments:
            result.segments = _enhance_segments_with_claude(
                result.segments,
                ",".join(result.languages) if getattr(result, "languages", None) else (result.language or "en"),
            )

        # Add tone marks / diacritics for Nigerian languages. A meeting that
        # switched language only gets them on the Yoruba/Igbo/Hausa parts.
        lang_for_diacritics = kwargs.get("language") or result.language
        if getattr(result, "languages", None):
            touched = False
            for seg in result.segments or []:
                seg_lang = seg.get("language")
                if seg_lang in ("yo", "ig", "ha") and seg.get("text"):
                    seg["text"] = _add_diacritics_with_claude(seg["text"], seg_lang)
                    touched = True
            if touched:
                result.text = " ".join(s.get("text", "") for s in result.segments if s.get("text")).strip()
        elif lang_for_diacritics in ("yo", "ig", "ha") and result.text:
            result.text = _add_diacritics_with_claude(result.text, lang_for_diacritics)
            for seg in result.segments or []:
                original = seg.get("text", "")
                if original:
                    seg["text"] = _add_diacritics_with_claude(original, lang_for_diacritics)

        formatted_output = OutputFormatter.format(result.to_dict(), "json")
        payload = json.loads(formatted_output)

        speakers = None
        diarization_status = "skipped"
        diarize = kwargs.get("diarization", False)
        if result.segments:
            found = sorted({
                seg.get("speaker")
                for seg in result.segments
                if seg.get("speaker")
            })
            speakers = found if found else None
            if diarize:
                if not engine.diarization.is_available():
                    diarization_status = "unavailable"
                elif speakers:
                    diarization_status = "success"
                else:
                    diarization_status = "failed"

        speaker_sentiment = _get_speaker_sentiments(result.segments or [], {})

        if _is_cancelled(jid):
            raise _JobCancelled()
        billing = _JOB_BILLING[jid]
        cost = _credits_for_minutes(result.audio_duration / 60, billing["model"])
        result_payload = {
                "success": True,
                "filename": filename,
                "model_used": result.model_used,
                "processing_time": result.processing_time,
                "audio_duration": result.audio_duration,
                "language": result.language,
                "output_format": "json",
                "speakers": speakers,
                "diarization_status": diarization_status,
                "speaker_sentiment": speaker_sentiment,
                "result": payload,
            }
        completion = _supabase_request("POST", "/rest/v1/rpc/complete_transcription", payload={
            "p_reference": jid, "p_cost": cost, "p_result": result_payload})
        if not isinstance(completion, dict) or completion.get("error"):
            raise RuntimeError("Could not publish and settle transcription")
        if completion.get("cancelled"):
            raise _JobCancelled()
        settled = True
        logger.info(f"Job {jid} completed successfully.")
        name = os.path.splitext(os.path.basename(filename or ""))[0][:80] or "Your recording"
        _notify(kwargs.get("firebase_uid") or "", "transcript_ready", "Transcript ready",
                f"{name} has been transcribed. Tap to read it.",
                {"route": "/history", "job_id": jid, "long": bool(result.audio_duration and result.audio_duration >= LONG_RECORDING_SEC)})

        # Track usage: increment audio_minutes_used in Supabase
        firebase_uid = kwargs.get("firebase_uid") or ""
        if firebase_uid and result.audio_duration:
            try:
                _supabase_increment_audio_minutes(firebase_uid, result.audio_duration)
            except Exception:
                pass

    except _JobCancelled:
        logger.info(f"Job {jid} cancelled — stopped and discarded.")
        _upsert_job(jid, status="cancelled", detail="Cancelled by user")
        _CANCELLED.discard(jid)
    except Exception as e:
        logger.error(f"Background transcription job {jid} failed: {type(e).__name__}: {e}", exc_info=True)
        _upsert_job(jid, status="error", detail=_failure_detail(e))
        name = os.path.splitext(os.path.basename(filename or ""))[0][:80] or "Your recording"
        _notify(kwargs.get("firebase_uid") or "", "transcript_failed", "Transcription failed",
                f"We couldn't transcribe {name}. Any credits it used have been returned. Please try again.",
                {"route": "/history", "job_id": jid})
    finally:
        _job_finished()
        _CANCELLED.discard(jid)
        _JOB_BILLING.pop(jid, None)
        _JOB_SUBMIT_TIMES.pop(jid, None)
        if not settled:
            try:
                _finish_work(jid, False)
            except Exception:
                logger.error("Reservation needs reconciliation: %s", jid)
        _WORK_SLOTS.release()


@app.post("/companion/transcribe")
async def transcribe_companion(request: Request):
    from src.companion import load_upload, assemble_upload
    import io
    uid = await asyncio.to_thread(_require_uid, request)
    body = await request.json()
    if not isinstance(body, dict):
        raise HTTPException(400, "Invalid request")
    upload = await asyncio.to_thread(load_upload, uid, body.get("id"), _supabase_request)
    if upload.get("job_id"):
        return JSONResponse(status_code=202, content={"job_id": upload["job_id"], "duplicate": True})
    # Bound simultaneous assembly independently of GPU admission.
    if not _COMPANION_SLOTS.acquire(blocking=False):
        raise HTTPException(429, "Another upload is being prepared. Retry shortly.")
    try:
        content = await asyncio.to_thread(assemble_upload, upload, _supabase_request)
        request.state.companion_upload_id = upload["id"]
        suffix = ".mp4" if upload["mime_type"] == "audio/mp4" else ".ogg" if "ogg" in upload["mime_type"] else ".webm"
        return await transcribe(request, UploadFile(filename="meeting" + suffix, file=io.BytesIO(content)),
            language=None, task="transcribe", return_timestamps=True, output_format="json",
            model="whisper-small", diarization=True, num_speakers=None, job_id=None, firebase_uid=uid)
    finally:
        _COMPANION_SLOTS.release()


_COMPANION_SLOTS = threading.BoundedSemaphore(1)


@app.post("/transcribe")
async def transcribe(
    request: Request,
    file: UploadFile = File(...),
    language: Optional[str] = Form(None),
    task: str = Form("transcribe"),
    return_timestamps: bool = Form(True),
    output_format: str = Form("json"),
    model: Optional[str] = Form(None),
    diarization: bool = Form(False),
    num_speakers: Optional[int] = Form(None),
    job_id: Optional[str] = Form(None),
    firebase_uid: Optional[str] = Form(None),
):
    """
    Submit an audio file for transcription.
    Returns 202 immediately with a job_id.
    Poll GET /result/{job_id} for the completed transcript.
    Poll GET /progress/{job_id} for chunk-level progress.
    """
    uid = await asyncio.to_thread(_require_uid, request)
    if not engine:
        raise HTTPException(status_code=503, detail="Engine not initialized")
    if not file.filename:
        raise HTTPException(status_code=400, detail="No file provided")

    content = await file.read(_MAX_UPLOAD_BYTES + 1)
    if len(content) > _MAX_UPLOAD_BYTES:
        raise HTTPException(status_code=413, detail="Audio upload is too large")

    # Support comma-separated multi-language hints: "yo,en" or "ig,en"
    lang_list = [l.strip().lower() for l in (language or "").split(",") if l.strip() and l.strip() != "auto"]
    primary_lang = lang_list[0] if lang_list else None

    # Upgrade model if ANY requested language is a Nigerian language
    needs_upgrade = any(l in _UPGRADE_LANGUAGES for l in lang_list)
    effective_model = model
    if needs_upgrade:
        # Only upgrade to large-v3 when GPU is available. On CPU, large-v3
        # is impractically slow and may OOM on resource-constrained hosts.
        try:
            import torch
            has_gpu = torch.cuda.is_available()
        except Exception:
            has_gpu = False

        if has_gpu:
            if not effective_model or effective_model != _UPGRADE_TARGET:
                logger.info(f"Languages {lang_list} — GPU detected, auto-upgrading model to {_UPGRADE_TARGET}")
                effective_model = _UPGRADE_TARGET
        else:
            logger.info(f"Languages {lang_list} — CPU-only, staying with default model for speed")
            effective_model = effective_model or _default_model_key()

    # One Nigerian language, alone or with English: use its dedicated model
    # (falls back to large-v3 inside the engine if it can't load), at the
    # same price either way.
    natives = [l for l in lang_list if l in NATIVE_MODELS]
    if len(natives) == 1 and all(l in NATIVE_MODELS or l == "en" for l in lang_list) and native_asr_enabled() \
            and NATIVE_MODELS[natives[0]] in engine.registry.list_available_models():
        effective_model = NATIVE_MODELS[natives[0]]
        logger.info(f"Languages {lang_list}: using {effective_model}")

    # Validate only; the worker switches models under _ENGINE_LOCK.
    if effective_model and effective_model not in engine.registry.list_available_models():
        raise HTTPException(
            status_code=400,
            detail=f"Model '{effective_model}' not available. Options: {list(engine.registry.list_available_models().keys())}",
        )

    paused = _paused("allow_transcription_api", "Transcription")
    if paused:
        raise paused

    seconds = await asyncio.to_thread(_probe_duration_sec, content, file.filename)
    import math
    if seconds is None or not math.isfinite(seconds) or seconds <= 0:
        raise HTTPException(status_code=400, detail="Could not determine audio duration")
    if seconds > _MAX_AUDIO_SECONDS:
        raise HTTPException(status_code=413, detail="Audio must be at most two hours")
    if not _WORK_SLOTS.acquire(blocking=False):
        raise HTTPException(status_code=429, detail="Server busy. Try again later.")
    # Ignore legacy client IDs; they never select a persistent job key.
    jid = str(uuid.uuid4())
    billing_model = effective_model or _default_model_key()
    # A model chosen for the user (Nigerian languages need a bigger one) never
    # costs more than the option they picked.
    chosen = model or _default_model_key()
    if CREDITS_PER_MINUTE.get(chosen, 1) < CREDITS_PER_MINUTE.get(billing_model, 1):
        billing_model = chosen
    cost = _credits_for_minutes(seconds / 60, billing_model)
    reserved = False
    try:
        reservation = await asyncio.to_thread(_reserve_work, uid, jid, cost, "transcription", companion_id=getattr(request.state, "companion_upload_id", None))
        if reservation.get("duplicate"):
            _WORK_SLOTS.release()
            return JSONResponse(status_code=202, content={"job_id": reservation["job_id"], "status": "processing", "duplicate": True})
        jid = reservation.get("job_id", jid)
        reserved = True
        _JOB_BILLING[jid] = {"uid": uid, "model": billing_model, "reserved": cost}
        now = time.time()
        _JOB_SUBMIT_TIMES[jid] = now
        # SQL creates the owner-bound job insert-only in the reservation transaction.
        _purge_old_jobs()
    except Exception:
        if reserved:
            await asyncio.to_thread(_finish_work, jid, False)
        _JOB_BILLING.pop(jid, None)
        _WORK_SLOTS.release()
        raise

    # For Nigerian languages we pass the primary language code explicitly
    # (e.g. "yo") so Whisper uses its Yoruba decoder and produces proper
    # tone marks. When multiple languages are requested, we still pass the
    # primary one — Whisper handles occasional English words within a
    # predominantly Yoruba stream better than pure auto-detection.
    effective_lang = primary_lang

    def _progress_cb(current: int, total: int) -> None:
        if _is_cancelled(jid):
            raise _JobCancelled()
        percent = round(current / total * 100) if total > 0 else 0
        progress = {"current": current, "total": total, "percent": percent}
        _upsert_job(jid, status="processing", progress=progress)

    # We deliberately do NOT pass a static initial_prompt for Nigerian
    # languages. Whisper's HuggingFace implementation treats the prompt as
    # prefix text and regurgitates it when uncertain, causing cascading
    # hallucinations across chunks. Rely on whisper-large-v3's training
    # data for Yoruba/Igbo/Hausa diacritics instead.
    transcription_kwargs = {
        "language": effective_lang,
        # Every requested language: a meeting may switch between them (or
        # into English); the engine finds where each one is spoken.
        "languages": lang_list,
        "task": task,
        "return_timestamps": return_timestamps,
        "diarization": diarization,
        "num_speakers": num_speakers,
        "progress_callback": _progress_cb,
        "firebase_uid": uid,
    }

    try:
        _executor.submit(
            _run_transcription_sync,
            jid,
            content,
            file.filename or "audio",
            effective_model,
            **transcription_kwargs,
        )
    except Exception:
        try:
            await asyncio.to_thread(_finish_work, jid, False)
            await asyncio.to_thread(_upsert_job, jid, status="error", detail="Queue unavailable")
        finally:
            _JOB_BILLING.pop(jid, None)
            _WORK_SLOTS.release()
        raise HTTPException(status_code=503, detail="Queue unavailable. Try again later.")


    logger.info(f"Job {jid} accepted — transcription running in background.")
    return JSONResponse(
        status_code=202,
        content={"job_id": jid, "status": "processing"},
    )


@app.get("/health")
async def health_check():
    return {
        "status": "healthy",
        "engine_initialized": engine is not None
    }

def main():
    parser = argparse.ArgumentParser(description="Modular ASR Transcription System")
    parser.add_argument("--api", action="store_true", help="Run as API server")
    parser.add_argument("--host", default="0.0.0.0", help="API host")
    parser.add_argument("--port", type=int, default=7860, help="API port")
    parser.add_argument("--config", "-c", help="Config file path")

    args = parser.parse_args()

    if args.config:
        os.environ["CONFIG_PATH"] = args.config

    if args.api:
        uvicorn.run(app, host=args.host, port=args.port)
        return

if __name__ == "__main__":
    main()