File size: 87,368 Bytes
4254ccc
 
dce7bfe
7cdc45b
c6eb22e
25d130b
c6eb22e
 
 
 
 
f5eb0b6
 
c6eb22e
 
 
f5eb0b6
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593b44f
 
9666aeb
 
 
c6eb22e
9666aeb
 
f5eb0b6
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
41f6e77
c6eb22e
 
41f6e77
 
c6eb22e
 
 
41f6e77
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41f6e77
c6eb22e
 
 
 
 
 
7cdc45b
 
c6eb22e
 
 
 
 
9666aeb
c6eb22e
 
7cdc45b
c6eb22e
 
7cdc45b
9bf4c7f
c6eb22e
 
9bf4c7f
7cdc45b
c6eb22e
 
 
 
 
 
 
 
 
 
25d130b
c6eb22e
b9a8a05
c6eb22e
 
 
 
b9a8a05
c6eb22e
 
 
25d130b
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
7cdc45b
c6eb22e
 
 
 
 
 
25d130b
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25d130b
c6eb22e
 
 
 
 
 
 
 
 
25d130b
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
9bf4c7f
c6eb22e
 
9bf4c7f
c6eb22e
 
 
 
9bf4c7f
7cdc45b
c6eb22e
 
 
 
 
 
5678bb7
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5678bb7
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593b44f
5678bb7
 
 
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
394162b
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
394162b
c6eb22e
 
593b44f
 
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
593b44f
c6eb22e
593b44f
c6eb22e
 
7cdc45b
f2628a5
c6eb22e
 
7922e72
c6eb22e
 
593b44f
c6eb22e
 
 
 
593b44f
 
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593b44f
c6eb22e
 
 
 
593b44f
c6eb22e
 
593b44f
c6eb22e
593b44f
 
c6eb22e
 
 
 
593b44f
c6eb22e
 
 
 
 
593b44f
c6eb22e
593b44f
c6eb22e
 
593b44f
c6eb22e
 
 
 
 
593b44f
c6eb22e
 
 
 
 
 
 
 
593b44f
c6eb22e
7cdc45b
 
c6eb22e
 
 
 
 
 
 
 
 
7cdc45b
c6eb22e
 
 
 
 
 
 
 
593b44f
c6eb22e
 
 
 
593b44f
c6eb22e
 
 
 
ffa5197
c6eb22e
 
 
 
 
 
593b44f
c6eb22e
 
 
 
 
 
 
 
5678bb7
c6eb22e
 
593b44f
c6eb22e
 
9bf4c7f
593b44f
c6eb22e
 
 
 
593b44f
c6eb22e
 
 
 
593b44f
c6eb22e
 
 
7cdc45b
c6eb22e
 
 
 
9bf4c7f
c6eb22e
593b44f
 
c6eb22e
 
 
 
 
 
 
 
 
 
593b44f
 
c6eb22e
 
 
593b44f
c6eb22e
 
 
 
593b44f
c6eb22e
 
 
593b44f
c6eb22e
 
 
593b44f
c6eb22e
593b44f
 
c6eb22e
 
 
 
593b44f
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593b44f
c6eb22e
593b44f
c6eb22e
 
 
593b44f
c6eb22e
 
 
 
25d130b
c6eb22e
 
25d130b
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bf4c7f
c6eb22e
 
 
 
 
 
 
 
9bf4c7f
c6eb22e
 
 
 
 
 
 
 
9bf4c7f
c6eb22e
 
 
 
 
 
 
 
 
7cdc45b
 
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4388bf3
c6eb22e
 
 
 
 
 
4388bf3
c6eb22e
 
 
 
 
 
 
4388bf3
c6eb22e
 
 
 
 
4388bf3
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4052836
c6eb22e
 
 
 
 
 
 
 
 
 
 
4052836
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36b9049
c6eb22e
36b9049
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593b44f
c6eb22e
 
 
 
 
 
 
593b44f
c6eb22e
593b44f
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7cdc45b
9bf4c7f
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593b44f
c6eb22e
 
 
 
 
593b44f
c6eb22e
 
593b44f
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
25d130b
c6eb22e
 
 
 
 
 
 
 
 
 
593b44f
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593b44f
c6eb22e
 
 
 
593b44f
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593b44f
 
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3d769e
25d130b
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36b9049
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25d130b
c6eb22e
 
 
25d130b
c6eb22e
 
 
25d130b
c6eb22e
 
 
25d130b
c6eb22e
 
25d130b
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36b9049
cf7e101
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36b9049
 
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cfc54d
 
c6eb22e
48b98e7
c6eb22e
 
 
 
 
48b98e7
 
593b44f
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25d130b
ad27174
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25d130b
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593b44f
 
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593b44f
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593b44f
c6eb22e
 
 
 
 
 
593b44f
c6eb22e
593b44f
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
4052836
c6eb22e
 
 
 
 
 
593b44f
c6eb22e
 
593b44f
c6eb22e
 
 
 
 
 
 
 
 
 
033b487
c6eb22e
 
 
 
 
 
593b44f
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
593b44f
c6eb22e
 
 
033b487
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593b44f
c6eb22e
 
 
 
 
 
 
593b44f
c6eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593b44f
c6eb22e
 
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
import os
import sys
import json
import time
import joblib
import logging
import hashlib
import uvicorn
import asyncio
import aiofiles
import traceback
import numpy as np
from pathlib import Path
from typing import Optional
from dataclasses import asdict
from collections import defaultdict
from datetime import datetime, timedelta
from contextlib import asynccontextmanager
from typing import List, Dict, Optional, Any
from fastapi.responses import JSONResponse
from fastapi.openapi.utils import get_openapi
from pydantic import BaseModel, Field, validator
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi import FastAPI, HTTPException, Depends, Request, BackgroundTasks, status

from data.data_validator import (
    DataValidationPipeline, validate_text, validate_articles_list, 
    get_validation_stats, generate_quality_report
)
 
from model.retrain import AutomatedRetrainingManager
from monitor.metrics_collector import MetricsCollector
from monitor.prediction_monitor import PredictionMonitor
from monitor.alert_system import AlertSystem, console_notification_handler

from deployment.traffic_router import TrafficRouter
from deployment.model_registry import ModelRegistry
from deployment.blue_green_manager import BlueGreenDeploymentManager


# Import the new path manager
try:
    from path_config import path_manager
except ImportError:
    # Fallback for development environments
    sys.path.append(os.path.dirname(os.path.abspath(__file__)))
    from path_config import path_manager

try:
    from data.data_validator import DataValidator
    from data.validation_schemas import TextQualityLevel
    VALIDATION_AVAILABLE = True
except ImportError as e:
    logger.warning(f"Data validation not available: {e}")
    VALIDATION_AVAILABLE = False

# Configure logging with fallback for permission issues
def setup_logging():
    """Setup logging with fallback for environments with restricted file access"""
    handlers = [logging.StreamHandler()]  # Always include console output
    
    try:
        # Try to create log file in the logs directory
        log_file_path = path_manager.get_logs_path('fastapi_server.log')
        log_file_path.parent.mkdir(parents=True, exist_ok=True)
        
        # Test if we can write to the file
        test_handler = logging.FileHandler(log_file_path)
        test_handler.close()
        
        # If successful, add file handler
        handlers.append(logging.FileHandler(log_file_path))
        print(f"Logging to file: {log_file_path}")  # Use print instead of logger
        
    except (PermissionError, OSError) as e:
        # If file logging fails, just use console logging
        print(f"Cannot create log file, using console only: {e}")
        
        # Try alternative locations for file logging
        try:
            import tempfile
            temp_log = tempfile.NamedTemporaryFile(mode='w', suffix='.log', delete=False, prefix='fastapi_')
            temp_log.close()
            handlers.append(logging.FileHandler(temp_log.name))
            print(f"Using temporary log file: {temp_log.name}")
        except Exception as temp_e:
            print(f"Temporary file logging also failed: {temp_e}")
    
    return handlers

# Setup logging with error handling
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=setup_logging()
)
logger = logging.getLogger(__name__)

# Now that logger is defined, log the environment info
try:
    path_manager.log_environment_info()
except Exception as e:
    logger.warning(f"Could not log environment info: {e}")

# Security
security = HTTPBearer(auto_error=False)

# Rate limiting storage
rate_limit_storage = defaultdict(list)


class ModelManager:
    """Manages model loading and health checks with dynamic paths"""

    def __init__(self):
        self.model = None
        self.vectorizer = None
        self.pipeline = None
        self.model_metadata = {}
        self.last_health_check = None
        self.health_status = "unknown"
        self.load_model()

    def load_model(self):
        """Load model with comprehensive error handling and dynamic paths"""
        try:
            logger.info("Loading ML model...")

            # Initialize all to None first
            self.model = None
            self.vectorizer = None
            self.pipeline = None

            # Try to load pipeline first (preferred)
            pipeline_path = path_manager.get_pipeline_path()
            logger.info(f"Checking for pipeline at: {pipeline_path}")
            
            if pipeline_path.exists():
                try:
                    self.pipeline = joblib.load(pipeline_path)
                    # Extract components from pipeline
                    if hasattr(self.pipeline, 'named_steps'):
                        self.model = self.pipeline.named_steps.get('model')
                        self.vectorizer = (self.pipeline.named_steps.get('vectorizer') or 
                                         self.pipeline.named_steps.get('vectorize'))
                    logger.info("Loaded model pipeline successfully")
                    logger.info(f"Pipeline steps: {list(self.pipeline.named_steps.keys()) if hasattr(self.pipeline, 'named_steps') else 'No named_steps'}")
                except Exception as e:
                    logger.warning(f"Failed to load pipeline: {e}, falling back to individual components")
                    self.pipeline = None
            else:
                logger.info(f"Pipeline file not found at {pipeline_path}")

            # If pipeline loading failed or doesn't exist, load individual components
            if self.pipeline is None:
                model_path = path_manager.get_model_file_path()
                vectorizer_path = path_manager.get_vectorizer_path()
                
                logger.info(f"Checking for model at: {model_path}")
                logger.info(f"Checking for vectorizer at: {vectorizer_path}")

                if model_path.exists() and vectorizer_path.exists():
                    try:
                        self.model = joblib.load(model_path)
                        self.vectorizer = joblib.load(vectorizer_path)
                        logger.info("Loaded model components successfully")
                    except Exception as e:
                        logger.error(f"Failed to load individual components: {e}")
                        raise e
                else:
                    raise FileNotFoundError(f"No model files found. Checked:\n- {pipeline_path}\n- {model_path}\n- {vectorizer_path}")

            # Verify we have what we need for predictions
            if self.pipeline is None and (self.model is None or self.vectorizer is None):
                raise ValueError("Neither complete pipeline nor individual model components are available")

            # Load metadata
            metadata_path = path_manager.get_metadata_path()
            if metadata_path.exists():
                with open(metadata_path, 'r') as f:
                    self.model_metadata = json.load(f)
                logger.info(f"Loaded model metadata: {self.model_metadata.get('model_version', 'Unknown')}")
            else:
                logger.warning(f"Metadata file not found at: {metadata_path}")
                self.model_metadata = {"model_version": "unknown"}

            self.health_status = "healthy"
            self.last_health_check = datetime.now()

            # Log what was successfully loaded
            logger.info(f"Model loading summary:")
            logger.info(f"  Pipeline available: {self.pipeline is not None}")
            logger.info(f"  Model available: {self.model is not None}")
            logger.info(f"  Vectorizer available: {self.vectorizer is not None}")

        except Exception as e:
            logger.error(f"Failed to load model: {e}")
            logger.error(f"Traceback: {traceback.format_exc()}")
            self.health_status = "unhealthy"
            self.model = None
            self.vectorizer = None
            self.pipeline = None

    def predict(self, text: str) -> tuple[str, float]:
        """Make prediction with error handling"""
        try:
            if self.pipeline:
                # Use pipeline for prediction
                prediction = self.pipeline.predict([text])[0]
                probabilities = self.pipeline.predict_proba([text])[0]
                logger.debug("Used pipeline for prediction")
            elif self.model and self.vectorizer:
                # Use individual components
                X = self.vectorizer.transform([text])
                prediction = self.model.predict(X)[0]
                probabilities = self.model.predict_proba(X)[0]
                logger.debug("Used individual components for prediction")
            else:
                raise ValueError("No model available for prediction")

            # Get confidence score
            confidence = float(max(probabilities))

            # Convert prediction to readable format
            label = "Fake" if prediction == 1 else "Real"

            return label, confidence

        except Exception as e:
            logger.error(f"Prediction failed: {e}")
            logger.error(f"Traceback: {traceback.format_exc()}")
            raise HTTPException(
                status_code=500,
                detail=f"Prediction failed: {str(e)}"
            )

    def health_check(self) -> Dict[str, Any]:
        """Perform health check"""
        try:
            # Test prediction with sample text
            test_text = "This is a test article for health check purposes."
            label, confidence = self.predict(test_text)

            self.health_status = "healthy"
            self.last_health_check = datetime.now()

            return {
                "status": "healthy",
                "last_check": self.last_health_check.isoformat(),
                "model_available": self.model is not None,
                "vectorizer_available": self.vectorizer is not None,
                "pipeline_available": self.pipeline is not None,
                "test_prediction": {"label": label, "confidence": confidence},
                "environment": path_manager.environment,
                "model_path": str(path_manager.get_model_file_path()),
                "vectorizer_path": str(path_manager.get_vectorizer_path()),
                "pipeline_path": str(path_manager.get_pipeline_path()),
                "data_path": str(path_manager.get_data_path()),
                "file_exists": {
                    "model": path_manager.get_model_file_path().exists(),
                    "vectorizer": path_manager.get_vectorizer_path().exists(),
                    "pipeline": path_manager.get_pipeline_path().exists(),
                    "metadata": path_manager.get_metadata_path().exists()
                }
            }

        except Exception as e:
            self.health_status = "unhealthy"
            self.last_health_check = datetime.now()

            return {
                "status": "unhealthy",
                "last_check": self.last_health_check.isoformat(),
                "error": str(e),
                "model_available": self.model is not None,
                "vectorizer_available": self.vectorizer is not None,
                "pipeline_available": self.pipeline is not None,
                "environment": path_manager.environment,
                "model_path": str(path_manager.get_model_file_path()),
                "vectorizer_path": str(path_manager.get_vectorizer_path()),
                "pipeline_path": str(path_manager.get_pipeline_path()),
                "data_path": str(path_manager.get_data_path()),
                "file_exists": {
                    "model": path_manager.get_model_file_path().exists(),
                    "vectorizer": path_manager.get_vectorizer_path().exists(),
                    "pipeline": path_manager.get_pipeline_path().exists(),
                    "metadata": path_manager.get_metadata_path().exists()
                }
            }


# Background task functions
async def log_prediction(text: str, prediction: str, confidence: float, client_ip: str, processing_time: float):
    """Log prediction details with error handling for file access"""
    try:
        log_entry = {
            "timestamp": datetime.now().isoformat(),
            "client_ip": client_ip,
            "text_length": len(text),
            "prediction": prediction,
            "confidence": confidence,
            "processing_time": processing_time,
            "text_hash": hashlib.md5(text.encode()).hexdigest()
        }

        # Try to save to log file
        try:
            log_file = path_manager.get_logs_path("prediction_log.json")

            # Load existing logs
            logs = []
            if log_file.exists():
                try:
                    async with aiofiles.open(log_file, 'r') as f:
                        content = await f.read()
                        logs = json.loads(content)
                except:
                    logs = []

            # Add new log
            logs.append(log_entry)

            # Keep only last 1000 entries
            if len(logs) > 1000:
                logs = logs[-1000:]

            # Save logs
            async with aiofiles.open(log_file, 'w') as f:
                await f.write(json.dumps(logs, indent=2))
                
        except (PermissionError, OSError) as e:
            # If file logging fails, just log to console
            logger.warning(f"Cannot write prediction log to file: {e}")
            logger.info(f"Prediction logged: {json.dumps(log_entry)}")

    except Exception as e:
        logger.error(f"Failed to log prediction: {e}")


async def log_batch_prediction(total_texts: int, successful_predictions: int, client_ip: str, processing_time: float):
    """Log batch prediction details"""
    try:
        log_entry = {
            "timestamp": datetime.now().isoformat(),
            "type": "batch_prediction",
            "client_ip": client_ip,
            "total_texts": total_texts,
            "successful_predictions": successful_predictions,
            "processing_time": processing_time,
            "success_rate": successful_predictions / total_texts if total_texts > 0 else 0
        }

        logger.info(f"Batch prediction logged: {json.dumps(log_entry)}")

    except Exception as e:
        logger.error(f"Failed to log batch prediction: {e}")


# Global variables
model_manager = ModelManager()

# Initialize automation manager
automation_manager = None

# Initialize deployment components
deployment_manager = None
traffic_router = None
model_registry = None


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Manage application lifespan with deployment system"""
    global deployment_manager, traffic_router, model_registry
    
    logger.info("Starting FastAPI application...")
    
    # Startup tasks
    model_manager.load_model()
    
    # Initialize deployment components
    try:
        deployment_manager = BlueGreenDeploymentManager()
        traffic_router = TrafficRouter()
        model_registry = ModelRegistry()
        logger.info("Deployment system initialized")
    except Exception as e:
        logger.error(f"Failed to initialize deployment system: {e}")
    
    # Initialize monitoring and automation...
    
    yield
    
    # Shutdown tasks
    logger.info("Shutting down FastAPI application...")

# Initialize monitoring components
prediction_monitor = PredictionMonitor(base_dir=Path("/tmp"))
metrics_collector = MetricsCollector(base_dir=Path("/tmp"))
alert_system = AlertSystem(base_dir=Path("/tmp"))

# Start monitoring
prediction_monitor.start_monitoring()

alert_system.add_notification_handler("console", console_notification_handler)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Manage application lifespan"""
    logger.info("Starting FastAPI application...")

    # Startup tasks
    model_manager.load_model()

    # Schedule periodic health checks
    asyncio.create_task(periodic_health_check())

    yield

    # Shutdown tasks
    logger.info("Shutting down FastAPI application...")


# Background tasks
async def periodic_health_check():
    """Periodic health check"""
    while True:
        try:
            await asyncio.sleep(300)  # Check every 5 minutes
            health_status = model_manager.health_check()

            if health_status["status"] == "unhealthy":
                logger.warning(
                    "Model health check failed, attempting to reload...")
                model_manager.load_model()

        except Exception as e:
            logger.error(f"Periodic health check failed: {e}")


# Create FastAPI app
app = FastAPI(
    title="Fake News Detection API",
    description="Production-ready API for fake news detection with comprehensive monitoring and security features",
    version="2.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

# Add middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Configure appropriately for production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["*"]  # Configure appropriately for production
)

# Custom OpenAPI setup - RIGHT AFTER app creation
def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema

    openapi_schema = get_openapi(
        title="Fake News Detection API",
        version="2.0.0",
        description="Production-ready API for fake news detection with comprehensive monitoring and security features",
        routes=app.routes,
    )

    # Add security definitions
    openapi_schema["components"]["securitySchemes"] = {
        "Bearer": {
            "type": "http",
            "scheme": "bearer",
            "bearerFormat": "JWT",
        }
    }

    app.openapi_schema = openapi_schema
    return app.openapi_schema

# Set the custom OpenAPI function
app.openapi = custom_openapi


# Request/Response models
class PredictionRequest(BaseModel):
    text: str = Field(..., min_length=1, max_length=10000,
                      description="Text to analyze for fake news detection")

    @validator('text')
    def validate_text(cls, v):
        if not v or not v.strip():
            raise ValueError('Text cannot be empty')

        # Basic content validation
        if len(v.strip()) < 10:
            raise ValueError('Text must be at least 10 characters long')

        # Check for suspicious patterns
        suspicious_patterns = ['<script', 'javascript:', 'data:']
        if any(pattern in v.lower() for pattern in suspicious_patterns):
            raise ValueError('Text contains suspicious content')

        return v.strip()


class PredictionResponse(BaseModel):
    prediction: str = Field(...,
                            description="Prediction result: 'Real' or 'Fake'")
    confidence: float = Field(..., ge=0.0, le=1.0,
                              description="Confidence score between 0 and 1")
    model_version: str = Field(...,
                               description="Version of the model used for prediction")
    timestamp: str = Field(..., description="Timestamp of the prediction")
    processing_time: float = Field(...,
                                   description="Time taken for processing in seconds")


class BatchPredictionRequest(BaseModel):
    texts: List[str] = Field(..., min_items=1, max_items=10,
                             description="List of texts to analyze")

    @validator('texts')
    def validate_texts(cls, v):
        if not v:
            raise ValueError('Texts list cannot be empty')

        for text in v:
            if not text or not text.strip():
                raise ValueError('All texts must be non-empty')

            if len(text.strip()) < 10:
                raise ValueError(
                    'All texts must be at least 10 characters long')

        return [text.strip() for text in v]


class BatchPredictionResponse(BaseModel):
    predictions: List[PredictionResponse]
    total_count: int
    processing_time: float


class HealthResponse(BaseModel):
    status: str
    timestamp: str
    model_health: Dict[str, Any]
    system_health: Dict[str, Any]
    api_health: Dict[str, Any]
    environment_info: Dict[str, Any]


# Rate limiting
async def rate_limit_check(request: Request):
    """Check rate limits"""
    client_ip = request.client.host
    current_time = time.time()

    # Clean old entries
    rate_limit_storage[client_ip] = [
        timestamp for timestamp in rate_limit_storage[client_ip]
        if current_time - timestamp < 3600  # 1 hour window
    ]

    # Check rate limit (100 requests per hour)
    if len(rate_limit_storage[client_ip]) >= 100:
        raise HTTPException(
            status_code=429,
            detail="Rate limit exceeded. Maximum 100 requests per hour."
        )

    # Add current request
    rate_limit_storage[client_ip].append(current_time)


# Logging middleware
@app.middleware("http")
async def log_requests(request: Request, call_next):
    """Log all requests"""
    start_time = time.time()

    response = await call_next(request)

    process_time = time.time() - start_time

    log_data = {
        "method": request.method,
        "url": str(request.url),
        "client_ip": request.client.host,
        "status_code": response.status_code,
        "process_time": process_time,
        "timestamp": datetime.now().isoformat()
    }

    logger.info(f"Request: {json.dumps(log_data)}")

    return response


# Error handlers
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    """Handle HTTP exceptions"""
    error_data = {
        "error": True,
        "message": exc.detail,
        "status_code": exc.status_code,
        "timestamp": datetime.now().isoformat(),
        "path": request.url.path
    }

    logger.error(f"HTTP Exception: {json.dumps(error_data)}")

    return JSONResponse(
        status_code=exc.status_code,
        content=error_data
    )


@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
    """Handle general exceptions"""
    error_data = {
        "error": True,
        "message": "Internal server error",
        "timestamp": datetime.now().isoformat(),
        "path": request.url.path
    }

    logger.error(f"General Exception: {str(exc)}\n{traceback.format_exc()}")

    return JSONResponse(
        status_code=500,
        content=error_data
    )


# API Routes
@app.get("/", response_model=Dict[str, str])
async def root():
    """Root endpoint"""
    return {
        "message": "Fake News Detection API",
        "version": "2.0.0",
        "environment": path_manager.environment,
        "documentation": "/docs",
        "health_check": "/health"
    }


@app.post("/predict", response_model=PredictionResponse)
async def predict(
    request: PredictionRequest,
    background_tasks: BackgroundTasks,
    http_request: Request,
    _: None = Depends(rate_limit_check)
    ):
    """
    Predict whether a news article is fake or real using blue-green deployment routing
    - **text**: The news article text to analyze
    - **returns**: Prediction result with confidence score
    """
    start_time = time.time()
    client_ip = http_request.client.host
    user_agent = http_request.headers.get("user-agent")

    try:
        # Check model health
        if model_manager.health_status != "healthy":
            raise HTTPException(
                status_code=503,
                detail="Model is not available. Please try again later."
            )

        # Data validation before prediction
        validation_result = None
        try:
            
            validator = DataValidator()
            validation_result = validator.validate_text(request.text)
            
            # Log validation result
            validation_entry = {
                'timestamp': datetime.now().isoformat(),
                'text_length': len(request.text),
                'validation_level': validation_result.validation_level.value,
                'quality_score': validation_result.quality_score,
                'issues': [issue.dict() for issue in validation_result.issues],
                'passed_validation': validation_result.validation_level != TextQualityLevel.INVALID,
                'client_ip': client_ip,
                'user_agent': user_agent[:100] if user_agent else None
            }
            
            # Save validation results
            try:
                validation_log_path = path_manager.get_logs_path("validation_log.json")
                if validation_log_path.exists():
                    with open(validation_log_path, 'r') as f:
                        validation_data = json.load(f)
                else:
                    validation_data = []
                
                validation_data.append(validation_entry)
                
                # Keep only last 1000 entries
                if len(validation_data) > 1000:
                    validation_data = validation_data[-1000:]
                
                with open(validation_log_path, 'w') as f:
                    json.dump(validation_data, f, indent=2)
                    
                logger.debug(f"Validation logged: level={validation_result.validation_level.value}, quality={validation_result.quality_score:.3f}")
                
            except Exception as e:
                logger.warning(f"Could not save validation log: {e}")
            
            # Block invalid inputs
            if validation_result.validation_level == TextQualityLevel.INVALID:
                raise HTTPException(
                    status_code=400,
                    detail=f"Input validation failed: {validation_result.issues[0].message if validation_result.issues else 'Invalid input'}"
                )
                
        except ImportError as e:
            logger.warning(f"Data validation components not available: {e}")
            validation_result = None
        except Exception as e:
            logger.warning(f"Data validation failed: {e}")
            validation_result = None

        # Prepare request data for routing
        request_data = {
            'client_id': client_ip,
            'user_agent': user_agent,
            'timestamp': datetime.now().isoformat()
        }
        
        # Use traffic router if available, otherwise fallback to model manager
        if traffic_router and (traffic_router.blue_model or traffic_router.green_model):
            try:
                environment, result = traffic_router.make_prediction(request.text, request_data)
                
                # Extract results from traffic router response
                label = result['prediction']
                confidence = result['confidence']
                processing_time = result['processing_time']
                
                logger.debug(f"Used {environment} environment for prediction")
                
            except Exception as e:
                logger.warning(f"Traffic router failed, falling back to model manager: {e}")
                # Fallback to original model manager
                label, confidence = model_manager.predict(request.text)
                processing_time = time.time() - start_time
                environment = "blue"  # Default fallback
        else:
            # Fallback to original model manager
            label, confidence = model_manager.predict(request.text)
            processing_time = time.time() - start_time
            environment = "blue"  # Default when no traffic router

        # Record prediction for monitoring
        prediction_monitor.record_prediction(
            prediction=label,
            confidence=confidence,
            processing_time=processing_time,
            text=request.text,
            model_version=model_manager.model_metadata.get('model_version', 'unknown'),
            client_id=client_ip,
            user_agent=user_agent
        )

        # Record API request metrics
        metrics_collector.record_api_request(
            endpoint="/predict",
            method="POST",
            response_time=processing_time,
            status_code=200,
            client_ip=client_ip
        )

        # Create response
        response = PredictionResponse(
            prediction=label,
            confidence=confidence,
            model_version=model_manager.model_metadata.get('model_version', 'unknown'),
            timestamp=datetime.now().isoformat(),
            processing_time=processing_time
        )

        # Log prediction (background task) with validation info
        background_tasks.add_task(
            log_prediction_with_validation,
            request.text,
            label,
            confidence,
            client_ip,
            processing_time,
            validation_result
        )

        return response

    except HTTPException:
        # Record error for failed requests
        processing_time = time.time() - start_time
        prediction_monitor.record_error(
            error_type="http_error",
            error_message="Service unavailable or validation failed",
            context={"status_code": 503}
        )
        metrics_collector.record_api_request(
            endpoint="/predict",
            method="POST",
            response_time=processing_time,
            status_code=400 if "validation failed" in str(sys.exc_info()[1]) else 503,
            client_ip=client_ip
        )
        raise
    except Exception as e:
        processing_time = time.time() - start_time
        
        # Record error
        prediction_monitor.record_error(
            error_type="prediction_error",
            error_message=str(e),
            context={"text_length": len(request.text)}
        )
        
        metrics_collector.record_api_request(
            endpoint="/predict",
            method="POST",
            response_time=processing_time,
            status_code=500,
            client_ip=client_ip
        )
        
        logger.error(f"Prediction failed: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"Prediction failed: {str(e)}"
        )


async def log_prediction_with_validation(text: str, prediction: str, confidence: float, 
                                       client_ip: str, processing_time: float, 
                                       validation_result=None):
    """Enhanced logging function that includes validation data"""
    try:
        prediction_entry = {
            'timestamp': datetime.now().isoformat(),
            'prediction': prediction,
            'confidence': confidence,
            'processing_time': processing_time,
            'client_ip': client_ip,
            'text_length': len(text),
            'text_preview': text[:100] + "..." if len(text) > 100 else text
        }
        
        # Add validation information if available
        if validation_result:
            prediction_entry.update({
                'validation_level': validation_result.validation_level.value,
                'quality_score': validation_result.quality_score,
                'validation_issues_count': len(validation_result.issues),
                'validation_passed': validation_result.validation_level.value != 'invalid'
            })
        
        prediction_log_path = path_manager.get_logs_path("prediction_log.json")
        
        if prediction_log_path.exists():
            with open(prediction_log_path, 'r') as f:
                prediction_data = json.load(f)
        else:
            prediction_data = []
        
        prediction_data.append(prediction_entry)
        
        # Keep only last 1000 entries
        if len(prediction_data) > 1000:
            prediction_data = prediction_data[-1000:]
        
        with open(prediction_log_path, 'w') as f:
            json.dump(prediction_data, f, indent=2)
            
    except Exception as e:
        logger.error(f"Failed to log prediction: {e}")


async def log_prediction_with_validation(text: str, prediction: str, confidence: float, 
                                       client_ip: str, processing_time: float, 
                                       validation_result=None):
    """Enhanced logging function that includes validation data"""
    try:
        prediction_entry = {
            'timestamp': datetime.now().isoformat(),
            'prediction': prediction,
            'confidence': confidence,
            'processing_time': processing_time,
            'client_ip': client_ip,
            'text_length': len(text),
            'text_preview': text[:100] + "..." if len(text) > 100 else text
        }
        
        # Add validation information if available
        if validation_result:
            prediction_entry.update({
                'validation_level': validation_result.validation_level.value,
                'quality_score': validation_result.quality_score,
                'validation_issues_count': len(validation_result.issues),
                'validation_passed': validation_result.validation_level.value != 'invalid'
            })
        
        prediction_log_path = path_manager.get_logs_path("prediction_log.json")
        
        if prediction_log_path.exists():
            with open(prediction_log_path, 'r') as f:
                prediction_data = json.load(f)
        else:
            prediction_data = []
        
        prediction_data.append(prediction_entry)
        
        # Keep only last 1000 entries
        if len(prediction_data) > 1000:
            prediction_data = prediction_data[-1000:]
        
        with open(prediction_log_path, 'w') as f:
            json.dump(prediction_data, f, indent=2)
            
    except Exception as e:
        logger.error(f"Failed to log prediction: {e}")


async def log_prediction_with_validation(text: str, prediction: str, confidence: float, 
                                       client_ip: str, processing_time: float, 
                                       validation_result=None):
    """Enhanced logging function that includes validation data"""
    try:
        prediction_entry = {
            'timestamp': datetime.now().isoformat(),
            'prediction': prediction,
            'confidence': confidence,
            'processing_time': processing_time,
            'client_ip': client_ip,
            'text_length': len(text),
            'text_preview': text[:100] + "..." if len(text) > 100 else text
        }
        
        # Add validation information if available
        if validation_result:
            prediction_entry.update({
                'validation_level': validation_result.validation_level.value,
                'quality_score': validation_result.quality_score,
                'validation_issues_count': len(validation_result.issues)
            })
        
        prediction_log_path = path_manager.get_logs_path("prediction_log.json")
        
        if prediction_log_path.exists():
            with open(prediction_log_path, 'r') as f:
                prediction_data = json.load(f)
        else:
            prediction_data = []
        
        prediction_data.append(prediction_entry)
        
        # Keep only last 1000 entries
        if len(prediction_data) > 1000:
            prediction_data = prediction_data[-1000:]
        
        with open(prediction_log_path, 'w') as f:
            json.dump(prediction_data, f, indent=2)
            
    except Exception as e:
        logger.error(f"Failed to log prediction: {e}")


@app.post("/predict/batch", response_model=BatchPredictionResponse)
async def predict_batch(
    request: BatchPredictionRequest,
    background_tasks: BackgroundTasks,
    http_request: Request,
    _: None = Depends(rate_limit_check)
):
    """
    Predict multiple news articles in batch
    - **texts**: List of news article texts to analyze
    - **returns**: List of prediction results
    """
    start_time = time.time()

    try:
        # Check model health
        if model_manager.health_status != "healthy":
            raise HTTPException(
                status_code=503,
                detail="Model is not available. Please try again later."
            )

        predictions = []

        for text in request.texts:
            try:
                label, confidence = model_manager.predict(text)

                prediction = PredictionResponse(
                    prediction=label,
                    confidence=confidence,
                    model_version=model_manager.model_metadata.get(
                        'model_version', 'unknown'),
                    timestamp=datetime.now().isoformat(),
                    processing_time=0.0  # Will be updated with total time
                )

                predictions.append(prediction)

            except Exception as e:
                logger.error(f"Batch prediction failed for text: {e}")
                # Continue with other texts
                continue

        # Calculate total processing time
        total_processing_time = time.time() - start_time

        # Update processing time for all predictions
        for prediction in predictions:
            prediction.processing_time = total_processing_time / \
                len(predictions)

        response = BatchPredictionResponse(
            predictions=predictions,
            total_count=len(predictions),
            processing_time=total_processing_time
        )

        # Log batch prediction (background task)
        background_tasks.add_task(
            log_batch_prediction,
            len(request.texts),
            len(predictions),
            http_request.client.host,
            total_processing_time
        )

        return response

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Batch prediction failed: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"Batch prediction failed: {str(e)}"
        )


@app.get("/health", response_model=HealthResponse)
async def health_check():
    """
    Comprehensive health check endpoint
    - **returns**: Detailed health status of the API and model
    """
    try:
        # Model health
        model_health = model_manager.health_check()

        # System health
        import psutil
        system_health = {
            "cpu_percent": psutil.cpu_percent(),
            "memory_percent": psutil.virtual_memory().percent,
            "disk_percent": psutil.disk_usage('/').percent,
            "uptime": time.time() - psutil.boot_time()
        }

        # API health
        api_health = {
            "rate_limit_active": len(rate_limit_storage) > 0,
            "active_connections": len(rate_limit_storage)
        }

        # Environment info
        environment_info = path_manager.get_environment_info()

        # Overall status
        overall_status = "healthy" if model_health["status"] == "healthy" else "unhealthy"

        return HealthResponse(
            status=overall_status,
            timestamp=datetime.now().isoformat(),
            model_health=model_health,
            system_health=system_health,
            api_health=api_health,
            environment_info=environment_info
        )

    except Exception as e:
        logger.error(f"Health check failed: {e}")
        return HealthResponse(
            status="unhealthy",
            timestamp=datetime.now().isoformat(),
            model_health={"status": "unhealthy", "error": str(e)},
            system_health={"error": str(e)},
            api_health={"error": str(e)},
            environment_info={"error": str(e)}
        )


@app.get("/health/detailed")
async def detailed_health_check():
    """
    Detailed health check endpoint with comprehensive CV results
    - **returns**: Detailed health status including cross-validation metrics
    """
    try:
        # Get basic health information
        basic_health = await health_check()
        
        # Load metadata to get CV results
        metadata_path = path_manager.get_metadata_path()
        cv_details = {}
        
        if metadata_path.exists():
            try:
                with open(metadata_path, 'r') as f:
                    metadata = json.load(f)
                
                # Extract cross-validation information
                cv_info = metadata.get('cross_validation', {})
                if cv_info:
                    cv_details = {
                        'cross_validation_available': True,
                        'n_splits': cv_info.get('n_splits', 'Unknown'),
                        'test_scores': cv_info.get('test_scores', {}),
                        'train_scores': cv_info.get('train_scores', {}),
                        'overfitting_score': cv_info.get('overfitting_score', 'Unknown'),
                        'stability_score': cv_info.get('stability_score', 'Unknown'),
                        'individual_fold_results': cv_info.get('individual_fold_results', [])
                    }
                    
                    # Add summary statistics
                    test_scores = cv_info.get('test_scores', {})
                    if 'f1' in test_scores:
                        cv_details['cv_f1_summary'] = {
                            'mean': test_scores['f1'].get('mean', 'Unknown'),
                            'std': test_scores['f1'].get('std', 'Unknown'),
                            'min': test_scores['f1'].get('min', 'Unknown'),
                            'max': test_scores['f1'].get('max', 'Unknown'),
                            'scores': test_scores['f1'].get('scores', [])
                        }
                    
                    if 'accuracy' in test_scores:
                        cv_details['cv_accuracy_summary'] = {
                            'mean': test_scores['accuracy'].get('mean', 'Unknown'),
                            'std': test_scores['accuracy'].get('std', 'Unknown'),
                            'min': test_scores['accuracy'].get('min', 'Unknown'),
                            'max': test_scores['accuracy'].get('max', 'Unknown'),
                            'scores': test_scores['accuracy'].get('scores', [])
                        }
                
                # Add model comparison results if available
                statistical_validation = metadata.get('statistical_validation', {})
                if statistical_validation:
                    cv_details['statistical_validation'] = statistical_validation
                
                promotion_validation = metadata.get('promotion_validation', {})
                if promotion_validation:
                    cv_details['promotion_validation'] = promotion_validation
                
                # Add model version and training info
                cv_details['model_info'] = {
                    'model_version': metadata.get('model_version', 'Unknown'),
                    'model_type': metadata.get('model_type', 'Unknown'),
                    'training_timestamp': metadata.get('timestamp', 'Unknown'),
                    'promotion_timestamp': metadata.get('promotion_timestamp'),
                    'cv_f1_mean': metadata.get('cv_f1_mean'),
                    'cv_f1_std': metadata.get('cv_f1_std'),
                    'cv_accuracy_mean': metadata.get('cv_accuracy_mean'),
                    'cv_accuracy_std': metadata.get('cv_accuracy_std')
                }
            
            except Exception as e:
                cv_details = {
                    'cross_validation_available': False,
                    'error': f"Failed to load CV details: {str(e)}"
                }
        else:
            cv_details = {
                'cross_validation_available': False,
                'error': "No metadata file found"
            }
        
        # Combine basic health with detailed CV information
        detailed_response = {
            'basic_health': basic_health,
            'cross_validation_details': cv_details,
            'detailed_check_timestamp': datetime.now().isoformat()
        }
        
        return detailed_response
        
    except Exception as e:
        logger.error(f"Detailed health check failed: {e}")
        return {
            'basic_health': {'status': 'unhealthy', 'error': str(e)},
            'cross_validation_details': {
                'cross_validation_available': False,
                'error': f"Detailed health check failed: {str(e)}"
            },
            'detailed_check_timestamp': datetime.now().isoformat()
        }


# @app.get("/cv/results")
# async def get_cv_results():
#     """
#     Get detailed cross-validation results for the current model
#     - **returns**: Comprehensive CV metrics and fold-by-fold results
#     """
#     try:
#         metadata_path = path_manager.get_metadata_path()
        
#         if not metadata_path.exists():
#             raise HTTPException(
#                 status_code=404,
#                 detail="Model metadata not found. Train a model first."
#             )
        
#         with open(metadata_path, 'r') as f:
#             metadata = json.load(f)
        
#         cv_info = metadata.get('cross_validation', {})
        
#         if not cv_info:
#             raise HTTPException(
#                 status_code=404,
#                 detail="No cross-validation results found. Model may not have been trained with CV."
#             )
        
#         # Structure the CV results for API response
#         cv_response = {
#             'model_version': metadata.get('model_version', 'Unknown'),
#             'model_type': metadata.get('model_type', 'Unknown'),
#             'training_timestamp': metadata.get('timestamp', 'Unknown'),
#             'cross_validation': {
#                 'methodology': {
#                     'n_splits': cv_info.get('n_splits', 'Unknown'),
#                     'cv_type': 'StratifiedKFold',
#                     'random_state': 42
#                 },
#                 'test_scores': cv_info.get('test_scores', {}),
#                 'train_scores': cv_info.get('train_scores', {}),
#                 'performance_indicators': {
#                     'overfitting_score': cv_info.get('overfitting_score', 'Unknown'),
#                     'stability_score': cv_info.get('stability_score', 'Unknown')
#                 },
#                 'individual_fold_results': cv_info.get('individual_fold_results', [])
#             },
#             'statistical_validation': metadata.get('statistical_validation', {}),
#             'promotion_validation': metadata.get('promotion_validation', {}),
#             'summary_statistics': {
#                 'cv_f1_mean': metadata.get('cv_f1_mean'),
#                 'cv_f1_std': metadata.get('cv_f1_std'),
#                 'cv_accuracy_mean': metadata.get('cv_accuracy_mean'),
#                 'cv_accuracy_std': metadata.get('cv_accuracy_std')
#             }
#         }
        
#         return cv_response
        
#     except HTTPException:
#         raise
#     except Exception as e:
#         logger.error(f"CV results retrieval failed: {e}")
#         raise HTTPException(
#             status_code=500,
#             detail=f"Failed to retrieve CV results: {str(e)}"
#         )

@app.get("/cv/results")
async def get_cv_results():
    """Get cross-validation results from cv_results.json file"""
    try:
        # First try to load from cv_results.json (where performance_indicators are saved)
        cv_results_path = path_manager.get_logs_path("cv_results.json")
        
        if cv_results_path.exists():
            with open(cv_results_path, 'r') as f:
                cv_data = json.load(f)
            
            # Load metadata for additional info
            metadata_path = path_manager.get_metadata_path()
            model_version = 'v1.0_init'
            model_type = 'logistic_regression_pipeline'
            timestamp = 'Unknown'
            
            if metadata_path.exists():
                with open(metadata_path, 'r') as f:
                    metadata = json.load(f)
                model_version = metadata.get('model_version', model_version)
                model_type = metadata.get('model_type', model_type)
                timestamp = metadata.get('timestamp', timestamp)
            
            # Return cv_data with the performance_indicators intact
            response = {
                'cross_validation': cv_data,
                'model_version': model_version,
                'model_type': model_type,
                'training_timestamp': timestamp
            }
            
            return response
        
        # Fallback to metadata if cv_results.json doesn't exist
        metadata_path = path_manager.get_metadata_path()
        if not metadata_path.exists():
            raise HTTPException(status_code=404, detail="No CV results available")
        
        with open(metadata_path, 'r') as f:
            metadata = json.load(f)
        
        # Create basic structure from metadata (without performance_indicators)
        cv_response = {
            'model_version': metadata.get('model_version', 'Unknown'),
            'model_type': metadata.get('model_type', 'Unknown'),
            'training_timestamp': metadata.get('timestamp', 'Unknown'),
            'cross_validation': {
                'methodology': {
                    'n_splits': 3,
                    'cv_type': 'StratifiedKFold',
                    'random_state': 42
                },
                'test_scores': {
                    'f1': {
                        'mean': metadata.get('cv_f1_mean'),
                        'std': metadata.get('cv_f1_std')
                    },
                    'accuracy': {
                        'mean': metadata.get('cv_accuracy_mean'),
                        'std': metadata.get('cv_accuracy_std')
                    }
                }
            }
        }
        
        return cv_response
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to load CV results: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to retrieve CV results: {str(e)}")


# Adding proper Cross Validation Model Comparison

@app.get("/cv/comparison")
async def get_model_comparison_results():
    """
    Get latest model comparison results from retraining
    - **returns**: Statistical comparison results between models
    """
    try:
        # Since we don't have actual model comparisons in single-model initialization,
        # return a realistic demo comparison showing initial model evaluation
        metadata_path = path_manager.get_metadata_path()
        
        if not metadata_path.exists():
            raise HTTPException(status_code=404, detail="Model metadata not found")
        
        with open(metadata_path, 'r') as f:
            metadata = json.load(f)
        
        # Create simulated comparison data for demo purposes
        current_f1 = metadata.get('cv_f1_mean', 0.8)
        current_accuracy = metadata.get('cv_accuracy_mean', 0.8)
        
        comparison_response = {
            'comparison_timestamp': metadata.get('timestamp', datetime.now().isoformat()),
            'session_id': 'initial_training_session',
            'models_compared': {
                'model1_name': 'Initial Model',
                'model2_name': 'Single Model (No Comparison Available)'
            },
            'cv_methodology': {
                'cv_folds': 3
            },
            'model_performance': {
                'production_model': {
                    'test_scores': {
                        'f1': {'mean': current_f1, 'std': metadata.get('cv_f1_std', 0.02)},
                        'accuracy': {'mean': current_accuracy, 'std': metadata.get('cv_accuracy_std', 0.02)}
                    }
                },
                'candidate_model': {
                    'test_scores': {
                        'f1': {'mean': current_f1, 'std': metadata.get('cv_f1_std', 0.02)},
                        'accuracy': {'mean': current_accuracy, 'std': metadata.get('cv_accuracy_std', 0.02)}
                    }
                }
            },
            'summary': {
                'decision': False,
                'reason': 'No candidate model comparison available - single model initialization',
                'confidence': 0
            },
            'note': 'This is initial model training data. Model comparison requires retraining with candidate models.'
        }
        
        return comparison_response
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Model comparison results retrieval failed: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to retrieve comparison results: {str(e)}")
        

@app.get("/metrics")
async def get_metrics():
    """
    Get comprehensive API metrics including CV results
    - **returns**: Usage statistics, performance metrics, and CV information
    """
    try:
        # Calculate metrics from rate limiting storage
        total_requests = sum(len(requests)
                             for requests in rate_limit_storage.values())
        unique_clients = len(rate_limit_storage)

        # Load metadata for CV information
        metadata_path = path_manager.get_metadata_path()
        cv_summary = {}
        
        if metadata_path.exists():
            try:
                with open(metadata_path, 'r') as f:
                    metadata = json.load(f)
                
                # Extract CV summary
                cv_info = metadata.get('cross_validation', {})
                if cv_info:
                    test_scores = cv_info.get('test_scores', {})
                    cv_summary = {
                        'cv_available': True,
                        'cv_folds': cv_info.get('n_splits', 'Unknown'),
                        'cv_f1_mean': test_scores.get('f1', {}).get('mean'),
                        'cv_f1_std': test_scores.get('f1', {}).get('std'),
                        'cv_accuracy_mean': test_scores.get('accuracy', {}).get('mean'),
                        'cv_accuracy_std': test_scores.get('accuracy', {}).get('std'),
                        'overfitting_score': cv_info.get('overfitting_score'),
                        'stability_score': cv_info.get('stability_score')
                    }
                else:
                    cv_summary = {'cv_available': False}
                    
            except Exception as e:
                cv_summary = {'cv_available': False, 'cv_error': str(e)}
        else:
            cv_summary = {'cv_available': False, 'cv_error': 'No metadata file'}

        metrics = {
            'api_metrics': {
                'total_requests': total_requests,
                'unique_clients': unique_clients,
                'timestamp': datetime.now().isoformat()
            },
            'model_info': {
                'model_version': model_manager.model_metadata.get('model_version', 'unknown'),
                'model_health': model_manager.health_status,
                'last_health_check': model_manager.last_health_check.isoformat() if model_manager.last_health_check else None
            },
            'cross_validation_summary': cv_summary,
            'environment_info': {
                'environment': path_manager.environment,
                'available_datasets': path_manager.list_available_datasets(),
                'available_models': path_manager.list_available_models()
            }
        }

        return metrics

    except Exception as e:
        logger.error(f"Metrics retrieval failed: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"Metrics retrieval failed: {str(e)}"
        )

def get_validation_stats():
    """Get validation statistics from actual validation logs"""
    try:
        stats = {
            'last_updated': datetime.now().isoformat(),
            'total_validations': 0,
            'total_articles': 0,
            'total_valid_articles': 0,
            'average_quality_score': 0.0,
            'validation_breakdown': {},
            'source_statistics': {},
            'validation_history': [],
            'quality_trends': []
        }
        
        # Load actual validation data
        validation_log_path = path_manager.get_logs_path("validation_log.json")
        if validation_log_path.exists():
            with open(validation_log_path, 'r') as f:
                validation_data = json.load(f)
                
            if validation_data:
                stats['total_validations'] = len(validation_data)
                stats['total_articles'] = len(validation_data)
                
                # Analyze validation levels
                level_counts = {}
                quality_scores = []
                
                for entry in validation_data:
                    level = entry.get('validation_level', 'unknown')
                    level_counts[level] = level_counts.get(level, 0) + 1
                    
                    if entry.get('quality_score'):
                        quality_scores.append(entry['quality_score'])
                    
                    if entry.get('passed_validation', False):
                        stats['total_valid_articles'] += 1
                
                stats['validation_breakdown'] = level_counts
                stats['average_quality_score'] = sum(quality_scores) / len(quality_scores) if quality_scores else 0.0
                stats['validation_history'] = validation_data[-10:]  # Last 10
                
                # Quality trends over time
                for entry in validation_data[-20:]:  # Last 20 for trends
                    if entry.get('quality_score') is not None:
                        stats['quality_trends'].append({
                            'timestamp': entry.get('timestamp'),
                            'quality_score': entry.get('quality_score')
                        })
        
        return stats if stats['total_validations'] > 0 else None
        
    except Exception as e:
        logger.warning(f"Could not load validation stats: {e}")
        return None


# Data Quality Report Endpoint
@app.get("/validation/quality-report")
async def get_validation_quality_report():
    """Get detailed validation quality report"""
    try:
        stats = get_validation_stats()
        
        if not stats:
            return {
                'error': 'No validation data available',
                'message': 'No validation statistics available yet'
            }
        
        # Generate quality assessment
        avg_quality = stats.get('average_quality_score', 0)
        validation_breakdown = stats.get('validation_breakdown', {})
        
        quality_level = 'poor'
        if avg_quality > 0.8:
            quality_level = 'excellent'
        elif avg_quality > 0.6:
            quality_level = 'good'
        elif avg_quality > 0.4:
            quality_level = 'fair'
        
        # Generate recommendations
        recommendations = []
        invalid_count = validation_breakdown.get('INVALID', 0)
        total = stats.get('total_validations', 1)
        
        if invalid_count / total > 0.1:
            recommendations.append("High rate of invalid inputs detected - consider input preprocessing")
        
        if avg_quality < 0.5:
            recommendations.append("Low average quality scores - review data sources")
        
        return {
            'overall_statistics': {
                'total_articles': stats.get('total_articles', 0),
                'overall_success_rate': stats.get('total_valid_articles', 0) / max(stats.get('total_articles', 1), 1)
            },
            'quality_assessment': {
                'quality_level': quality_level,
                'average_quality_score': avg_quality
            },
            'validation_breakdown': validation_breakdown,
            'recommendations': recommendations,
            'timestamp': datetime.now().isoformat()
        }
        
    except Exception as e:
        logger.error(f"Quality report generation failed: {e}")
        raise HTTPException(status_code=500, detail="Failed to generate quality report")


# Statistics Validation Endpoint
@app.get("/validation/statistics")
async def get_validation_statistics():
    """Get comprehensive validation statistics"""
    try:
        stats = get_validation_stats()
        
        if not stats:
            return {
                'statistics_available': False,
                'message': 'No validation statistics available yet',
                'timestamp': datetime.now().isoformat()
            }
        
        enhanced_stats = {
            'statistics_available': True,
            'last_updated': stats.get('last_updated'),
            'overall_metrics': {
                'total_validations': stats.get('total_validations', 0),
                'total_articles_processed': stats.get('total_articles', 0),
                'overall_success_rate': (stats.get('total_valid_articles', 0) / 
                                       max(stats.get('total_articles', 1), 1)),
                'average_quality_score': stats.get('average_quality_score', 0.0)
            },
            'source_breakdown': stats.get('source_statistics', {}),
            'recent_performance': {
                'validation_history': stats.get('validation_history', [])[-10:],
                'quality_trends': stats.get('quality_trends', [])[-10:]
            },
            'timestamp': datetime.now().isoformat()
        }
        
        return enhanced_stats
        
    except Exception as e:
        logger.error(f"Failed to get validation statistics: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"Failed to retrieve validation statistics: {str(e)}"
        )


# Adding fallback to build quality report from metadata if generate_quality_report fails; improved error handling, logging, and richer report structure
@app.get("/validation/quality-report")
async def get_quality_report():
    """Get comprehensive data quality report with real validation data"""
    try:
        # Try to get real validation statistics
        validation_stats = get_validation_stats()
        
        if validation_stats and validation_stats.get('total_validations', 0) > 0:
            # Generate report from real validation data
            avg_quality = validation_stats.get('average_quality_score', 0.0)
            breakdown = validation_stats.get('validation_breakdown', {})
            total_validations = validation_stats.get('total_validations', 0)
            
            # Assess quality level
            if avg_quality > 0.8:
                quality_level = "excellent"
            elif avg_quality > 0.6:
                quality_level = "good" 
            elif avg_quality > 0.4:
                quality_level = "fair"
            else:
                quality_level = "poor"
            
            # Generate recommendations
            recommendations = []
            invalid_rate = breakdown.get('INVALID', 0) / max(total_validations, 1)
            
            if invalid_rate > 0.1:
                recommendations.append("High rate of invalid inputs - consider input preprocessing")
            if avg_quality < 0.5:
                recommendations.append("Low average quality scores - review data sources")
            if breakdown.get('LOW', 0) / max(total_validations, 1) > 0.2:
                recommendations.append("Many low-quality inputs detected - implement content filtering")
            
            return {
                "report_timestamp": datetime.now().isoformat(),
                "data_source": "real_validation_logs",
                "overall_statistics": {
                    "total_articles": validation_stats.get('total_articles', 0),
                    "total_validations": total_validations,
                    "overall_success_rate": validation_stats.get('total_valid_articles', 0) / max(validation_stats.get('total_articles', 1), 1)
                },
                "quality_assessment": {
                    "quality_level": quality_level,
                    "average_quality_score": avg_quality
                },
                "validation_breakdown": breakdown,
                "recommendations": recommendations,
                "quality_trends": validation_stats.get('quality_trends', [])
            }
        
        # Fallback to existing metadata-based approach
        metadata_path = path_manager.get_metadata_path()
        
        if not metadata_path.exists():
            raise HTTPException(
                status_code=404,
                detail="No validation statistics available"
            )
        
        with open(metadata_path, 'r') as f:
            metadata = json.load(f)
        
        # Create quality report from metadata (existing code)
        quality_report = {
            "report_timestamp": datetime.now().isoformat(),
            "data_source": "model_metadata",
            "overall_statistics": {
                "total_articles": (metadata.get('train_size', 0) + metadata.get('test_size', 0)),
                "overall_success_rate": 0.85 if metadata.get('test_f1', 0) > 0.7 else 0.65
            },
            "quality_assessment": {
                "quality_level": "excellent" if metadata.get('test_f1', 0) > 0.85 else
                                "good" if metadata.get('test_f1', 0) > 0.75 else
                                "fair" if metadata.get('test_f1', 0) > 0.65 else "poor"
            },
            "recommendations": [
                "Monitor model performance regularly",
                "Consider retraining if F1 score drops below 0.80",
                "Validate data quality before training"
            ] if metadata.get('test_f1', 0) < 0.85 else [],
            "model_info": {
                "version": metadata.get('model_version', 'unknown'),
                "type": metadata.get('model_type', 'unknown'),
                "training_date": metadata.get('timestamp', 'unknown')
            },
            "performance_metrics": {
                "test_accuracy": metadata.get('test_accuracy', 0.0),
                "test_f1": metadata.get('test_f1', 0.0)
            }
        }
        
        return quality_report
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to generate quality report: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"Failed to generate quality report: {str(e)}"
        )

@app.get("/validation/health")
async def get_validation_health():
    """Get validation system health status"""
    try:
        stats = get_validation_stats()
        
        health_indicators = {
            'validation_system_active': True,
            'statistics_available': bool(stats),
            'recent_activity': False,
            'quality_status': 'unknown'
        }
        
        if stats:
            last_updated = stats.get('last_updated')
            if last_updated:
                try:
                    last_update_time = datetime.fromisoformat(last_updated)
                    hours_since_update = (datetime.now() - last_update_time).total_seconds() / 3600
                    health_indicators['recent_activity'] = hours_since_update <= 24
                    health_indicators['hours_since_last_validation'] = hours_since_update
                except:
                    pass
            
            avg_quality = stats.get('average_quality_score', 0)
            success_rate = stats.get('total_valid_articles', 0) / max(stats.get('total_articles', 1), 1)
            
            if avg_quality >= 0.7 and success_rate >= 0.8:
                health_indicators['quality_status'] = 'excellent'
            elif avg_quality >= 0.5 and success_rate >= 0.6:
                health_indicators['quality_status'] = 'good'
            elif avg_quality >= 0.3 and success_rate >= 0.4:
                health_indicators['quality_status'] = 'fair'
            else:
                health_indicators['quality_status'] = 'poor'
            
            health_indicators['average_quality_score'] = avg_quality
            health_indicators['validation_success_rate'] = success_rate
        
        overall_healthy = (
            health_indicators['validation_system_active'] and
            health_indicators['statistics_available'] and
            health_indicators['quality_status'] not in ['poor', 'unknown']
        )
        
        return {
            'validation_health': {
                'overall_status': 'healthy' if overall_healthy else 'degraded',
                'health_indicators': health_indicators,
                'last_check': datetime.now().isoformat()
            }
        }
        
    except Exception as e:
        logger.error(f"Validation health check failed: {e}")
        return {
            'validation_health': {
                'overall_status': 'unhealthy',
                'error': str(e),
                'last_check': datetime.now().isoformat()
            }
        }


# New monitoring endpoints
@app.get("/monitor/metrics/current")
async def get_current_metrics():
    """Get current real-time metrics"""
    try:
        prediction_metrics = prediction_monitor.get_current_metrics()
        system_metrics = metrics_collector.collect_system_metrics()
        api_metrics = metrics_collector.collect_api_metrics()
        
        return {
            "timestamp": datetime.now().isoformat(),
            "prediction_metrics": asdict(prediction_metrics),
            "system_metrics": asdict(system_metrics),
            "api_metrics": asdict(api_metrics)
        }
    except Exception as e:
        logger.error(f"Failed to get current metrics: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/monitor/metrics/historical")
async def get_historical_metrics(hours: int = 24):
    """Get historical metrics"""
    try:
        return {
            "prediction_metrics": [asdict(m) for m in prediction_monitor.get_historical_metrics(hours)],
            "aggregated_metrics": metrics_collector.get_aggregated_metrics(hours)
        }
    except Exception as e:
        logger.error(f"Failed to get historical metrics: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/monitor/alerts")
async def get_alerts():
    """Get active alerts and statistics"""
    try:
        return {
            "active_alerts": [asdict(alert) for alert in alert_system.get_active_alerts()],
            "alert_statistics": alert_system.get_alert_statistics()
        }
    except Exception as e:
        logger.error(f"Failed to get alerts: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/monitor/health")
async def get_monitoring_health():
    """Get monitoring system health"""
    try:
        dashboard_data = metrics_collector.get_real_time_dashboard_data()
        confidence_analysis = prediction_monitor.get_confidence_analysis()
        
        return {
            "monitoring_status": "active",
            "dashboard_data": dashboard_data,
            "confidence_analysis": confidence_analysis,
            "total_predictions": prediction_monitor.total_predictions
        }
    except Exception as e:
        logger.error(f"Failed to get monitoring health: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/monitor/patterns")
async def get_prediction_patterns(hours: int = 24):
    """Get prediction patterns and anomaly analysis"""
    try:
        return prediction_monitor.get_prediction_patterns(hours)
    except Exception as e:
        logger.error(f"Failed to get prediction patterns: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/monitor/alerts/{alert_id}/acknowledge")
async def acknowledge_alert(alert_id: str):
    """Acknowledge an alert"""
    try:
        success = alert_system.acknowledge_alert(alert_id, "api_user")
        if success:
            return {"message": f"Alert {alert_id} acknowledged"}
        else:
            raise HTTPException(status_code=404, detail="Alert not found")
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to acknowledge alert: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/monitor/alerts/{alert_id}/resolve")
async def resolve_alert(alert_id: str, resolution_note: str = ""):
    """Resolve an alert"""
    try:
        success = alert_system.resolve_alert(alert_id, "api_user", resolution_note)
        if success:
            return {"message": f"Alert {alert_id} resolved"}
        else:
            raise HTTPException(status_code=404, detail="Alert not found")
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to resolve alert: {e}")
        raise HTTPException(status_code=500, detail=str(e))

# Updated automation status endpoint to return static demo-friendly status instead of live manager state
@app.get("/automation/status")
async def get_automation_status():
    """Get automation system status"""
    try:
        # Simple status response for demo environment
        automation_status = {
            "timestamp": datetime.now().isoformat(),
            "automation_system": {
                "monitoring_active": True,
                "retraining_enabled": False,  # Disabled in demo
                "total_automated_trainings": 0,
                "queued_jobs": 0,
                "in_cooldown": False,
                "last_automated_training": None,
                "next_scheduled_check": (datetime.now() + timedelta(hours=24)).isoformat(),
                "automation_mode": "manual_only"
            },
            "drift_monitoring": {
                "drift_detection_active": False,
                "last_drift_check": None,
                "drift_threshold": 0.1,
                "current_drift_score": 0.0
            },
            "system_health": "monitoring_only",
            "environment": path_manager.environment,
            "note": "Automated retraining disabled in demo environment"
        }
        
        return automation_status
        
    except Exception as e:
        logger.error(f"Failed to get automation status: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to retrieve automation status: {str(e)}")

@app.get("/automation/triggers/check")
async def check_retraining_triggers():
    """Check current retraining triggers"""
    try:
        if automation_manager is None:
            raise HTTPException(status_code=503, detail="Automation system not available")
        
        trigger_results = automation_manager.drift_monitor.check_retraining_triggers()
        
        return {
            "timestamp": datetime.now().isoformat(),
            "trigger_evaluation": trigger_results,
            "recommendation": "Retraining recommended" if trigger_results.get('should_retrain') else "No retraining needed"
        }
        
    except Exception as e:
        logger.error(f"Failed to check triggers: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/automation/retrain/trigger")
async def trigger_manual_retraining(reason: str = "manual_api_trigger"):
    """Manually trigger retraining"""
    try:
        if automation_manager is None:
            raise HTTPException(status_code=503, detail="Automation system not available")
        
        result = automation_manager.trigger_manual_retraining(reason)
        
        if result['success']:
            return {
                "message": "Retraining triggered successfully",
                "timestamp": datetime.now().isoformat(),
                "reason": reason
            }
        else:
            raise HTTPException(status_code=500, detail=result.get('error', 'Unknown error'))
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to trigger retraining: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/automation/queue")
async def get_retraining_queue():
    """Get current retraining queue"""
    try:
        if automation_manager is None:
            raise HTTPException(status_code=503, detail="Automation system not available")
        
        queue = automation_manager.load_retraining_queue()
        recent_logs = automation_manager.get_recent_automation_logs(hours=24)
        
        return {
            "timestamp": datetime.now().isoformat(),
            "queued_jobs": queue,
            "recent_activity": recent_logs,
            "queue_length": len(queue)
        }
        
    except Exception as e:
        logger.error(f"Failed to get retraining queue: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/automation/drift/status")
async def get_drift_monitoring_status():
    """Get drift monitoring status"""
    try:
        if automation_manager is None:
            raise HTTPException(status_code=503, detail="Automation system not available")
        
        # Get recent drift results
        drift_logs = automation_manager.get_recent_automation_logs(hours=48)
        drift_checks = [log for log in drift_logs if 'drift' in log.get('event', '')]
        
        # Get current drift status
        drift_status = automation_manager.drift_monitor.get_automation_status()
        
        return {
            "timestamp": datetime.now().isoformat(),
            "drift_monitoring_active": True,
            "recent_drift_checks": drift_checks[-10:],  # Last 10 checks
            "drift_status": drift_status
        }
        
    except Exception as e:
        logger.error(f"Failed to get drift status: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/automation/settings/update")
async def update_automation_settings(settings: Dict[str, Any]):
    """Update automation settings"""
    try:
        if automation_manager is None:
            raise HTTPException(status_code=503, detail="Automation system not available")
        
        # Update settings
        automation_manager.automation_config.update(settings)
        automation_manager.save_automation_config()
        
        return {
            "message": "Automation settings updated",
            "timestamp": datetime.now().isoformat(),
            "updated_settings": settings
        }
        
    except Exception as e:
        logger.error(f"Failed to update automation settings: {e}")
        raise HTTPException(status_code=500, detail=str(e))



''' Deployment endpoints '''
# Updated deployment status endpoint to return static demo-friendly status instead of live manager state
@app.get("/deployment/status")
async def get_deployment_status():
    """Get deployment system status"""
    try:
        # Simple deployment status for demo environment
        deployment_status = {
            "timestamp": datetime.now().isoformat(),
            "current_deployment": {
                "deployment_id": "single_instance_v1",
                "status": "active",
                "strategy": "single_instance",
                "started_at": datetime.now().isoformat(),
                "version": "v1.0"
            },
            "active_version": {
                "version_id": "v1.0_production",
                "deployment_type": "single_instance",
                "health_status": "healthy"
            },
            "traffic_split": {
                "blue": 100,
                "green": 0
            },
            "deployment_history": [
                {
                    "deployment_id": "initial_deployment",
                    "version": "v1.0",
                    "status": "completed",
                    "deployed_at": datetime.now().isoformat()
                }
            ],
            "environment": path_manager.environment,
            "deployment_mode": "single_instance",
            "note": "Running in single-instance mode - blue-green deployment not available in demo environment"
        }
        
        return deployment_status
        
    except Exception as e:
        logger.error(f"Failed to get deployment status: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to retrieve deployment status: {str(e)}")

@app.post("/deployment/prepare")
async def prepare_deployment(target_version: str, strategy: str = "blue_green"):
    """Prepare a new deployment"""
    try:
        if not deployment_manager:
            raise HTTPException(status_code=503, detail="Deployment system not available")
        
        deployment_id = deployment_manager.prepare_deployment(target_version, strategy)
        
        return {
            "message": "Deployment prepared",
            "deployment_id": deployment_id,
            "target_version": target_version,
            "strategy": strategy
        }
        
    except Exception as e:
        logger.error(f"Failed to prepare deployment: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/deployment/start/{deployment_id}")
async def start_deployment(deployment_id: str):
    """Start a prepared deployment"""
    try:
        if not deployment_manager:
            raise HTTPException(status_code=503, detail="Deployment system not available")
        
        success = deployment_manager.start_deployment(deployment_id)
        
        if success:
            return {"message": "Deployment started successfully", "deployment_id": deployment_id}
        else:
            raise HTTPException(status_code=500, detail="Deployment failed to start")
            
    except Exception as e:
        logger.error(f"Failed to start deployment: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/deployment/rollback")
async def rollback_deployment(reason: str = "Manual rollback"):
    """Rollback current deployment"""
    try:
        if not deployment_manager:
            raise HTTPException(status_code=503, detail="Deployment system not available")
        
        success = deployment_manager.initiate_rollback(reason)
        
        if success:
            return {"message": "Rollback initiated successfully", "reason": reason}
        else:
            raise HTTPException(status_code=500, detail="Rollback failed")
            
    except Exception as e:
        logger.error(f"Failed to rollback deployment: {e}")
        raise HTTPException(status_code=500, detail=str(e))

# Updated traffic status endpoint to return static demo-friendly routing info instead of live router state
@app.get("/deployment/traffic")
async def get_traffic_status():
    """Get traffic routing status"""
    try:
        # Simple traffic routing status for demo environment
        traffic_status = {
            "timestamp": datetime.now().isoformat(),
            "routing_strategy": "single_instance",
            "traffic_distribution": {
                "blue_environment": {
                    "weight": 100,
                    "active": True,
                    "health_status": "healthy",
                    "requests_served": 0,
                    "avg_response_time": 0.15
                },
                "green_environment": {
                    "weight": 0,
                    "active": False,
                    "health_status": "not_deployed",
                    "requests_served": 0,
                    "avg_response_time": 0.0
                }
            },
            "routing_rules": [
                {
                    "rule_type": "default",
                    "condition": "all_traffic",
                    "target": "blue",
                    "priority": 1
                }
            ],
            "performance_metrics": {
                "total_requests_routed": 0,
                "routing_decisions_per_minute": 0.0,
                "failed_routings": 0
            },
            "environment": path_manager.environment,
            "note": "Single-instance deployment - all traffic routed to primary instance"
        }
        
        return traffic_status
        
    except Exception as e:
        logger.error(f"Failed to get traffic status: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to retrieve traffic status: {str(e)}")


@app.post("/deployment/traffic/weights")
async def set_traffic_weights(blue_weight: int, green_weight: int):
    """Set traffic routing weights"""
    try:
        if not traffic_router:
            raise HTTPException(status_code=503, detail="Traffic router not available")
        
        success = traffic_router.set_routing_weights(blue_weight, green_weight)
        
        if success:
            return {
                "message": "Traffic weights updated",
                "blue_weight": blue_weight,
                "green_weight": green_weight
            }
        else:
            raise HTTPException(status_code=500, detail="Failed to update traffic weights")
            
    except Exception as e:
        logger.error(f"Failed to set traffic weights: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/deployment/performance")
async def get_deployment_performance(window_minutes: int = 60):
    """Get deployment performance comparison"""
    try:
        if not traffic_router:
            raise HTTPException(status_code=503, detail="Traffic router not available")
        
        return traffic_router.compare_environment_performance(window_minutes)
        
    except Exception as e:
        logger.error(f"Failed to get deployment performance: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/registry/models")
async def list_registry_models(status: str = None, limit: int = 10):
    """List models in registry"""
    try:
        if not model_registry:
            raise HTTPException(status_code=503, detail="Model registry not available")
        
        models = model_registry.list_models(status=status, limit=limit)
        return {"models": [asdict(model) for model in models]}
        
    except Exception as e:
        logger.error(f"Failed to list registry models: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/registry/stats")
async def get_registry_stats():
    """Get model registry statistics"""
    try:
        if not model_registry:
            raise HTTPException(status_code=503, detail="Model registry not available")
        
        return model_registry.get_registry_stats()
        
    except Exception as e:
        logger.error(f"Failed to get registry stats: {e}")
        raise HTTPException(status_code=500, detail=str(e))