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

from flask import Flask, render_template, request, jsonify, session, redirect, url_for, Response, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
from werkzeug.middleware.proxy_fix import ProxyFix
import cv2
import numpy as np
import os
import sys
from datetime import datetime, date
import base64
from pathlib import Path
import threading
import queue
import mimetypes
import json
import uuid
import shutil
import tempfile

# ===================== Dynamic Path Detection (Fully Portable) =====================
# Determine project root regardless of where app.py is located or device
# This makes the project fully portable across different machines and paths

def detect_project_root():
    """
    Dynamically detect PROJECT_ROOT by looking for config/ and src/ directories
    Works on any device, any installation path
    """
    current = Path(__file__).parent.parent
    if (current / 'config').exists() and (current / 'src').exists():
        return current
    
    # Fallback: search upwards
    current = Path(__file__).parent
    while current != current.parent:
        if (current / 'config').exists() and (current / 'src').exists():
            return current
        current = current.parent
    
    # Last resort: current working directory
    return Path.cwd()

PROJECT_ROOT = detect_project_root()

# Ensure PROJECT_ROOT is in Python path for imports
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

# Determine webapp folder dynamically
WEBAPP_FOLDER = PROJECT_ROOT / 'webapp'

print(f"\n{'='*60}")
print(f"🌍 PROJECT CONFIGURATION (Portable Setup)")
print(f"{'='*60}")
print(f"πŸ“ PROJECT_ROOT: {PROJECT_ROOT}")
print(f"πŸ“ WEBAPP_FOLDER: {WEBAPP_FOLDER}")
print(f"{'='*60}\n")

# Import detection modules from new src structure
from src import (
    ViolenceDetector,
    YOLODetector,
    WeaponPersonDetector,
    PoseDetection,
    AnomalyDetector,
    VideoCapture,
)

# Import centralized configuration
from config import (
    MODEL_PATHS,
    get_model_path,
    DETECTION_THRESHOLDS,
    PROCESSING_PARAMS,
    SECRET_KEY,
    DATABASE_URI,
    MAX_CONTENT_LENGTH,
    UPLOAD_FOLDER,
    PROCESSED_FOLDER,
)

# Import model downloader for Hugging Face Hub models
from src.utils.model_downloader import setup_all_models

# ===================== Setup Models =====================
# Download models from Hugging Face Hub on startup
setup_all_models()

# ===================== Codec Selection =====================
def get_video_codec():
    """
    Select the best video codec for cross-platform compatibility.
    XVID is widely supported on Windows, Mac, and Linux.
    """
    try:
        # Try XVID first (best Windows compatibility)
        codec = cv2.VideoWriter_fourcc(*'XVID')
        # Test if codec is available
        test_path = str(Path(tempfile.gettempdir()) / 'codec_test.avi')
        test_writer = cv2.VideoWriter(test_path, codec, 1.0, (640, 480))
        if test_writer.isOpened():
            test_writer.release()
            if os.path.exists(test_path):
                os.remove(test_path)
            return codec, '.avi'
    except Exception:
        pass
    
    try:
        # Fallback to MJPG (Motion JPEG) - universally supported but larger files
        codec = cv2.VideoWriter_fourcc(*'MJPG')
        test_path = str(Path(tempfile.gettempdir()) / 'codec_test.avi')
        test_writer = cv2.VideoWriter(test_path, codec, 1.0, (640, 480))
        if test_writer.isOpened():
            test_writer.release()
            if os.path.exists(test_path):
                os.remove(test_path)
            return codec, '.avi'
    except Exception:
        pass
    
    # Final fallback - return XVID (should work on most systems)
    return cv2.VideoWriter_fourcc(*'XVID'), '.avi'

app = Flask(__name__, template_folder=str(WEBAPP_FOLDER / 'templates'), 
            static_folder=str(WEBAPP_FOLDER / 'static'))
app.config['SECRET_KEY'] = SECRET_KEY
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['UPLOAD_FOLDER'] = str(UPLOAD_FOLDER)
app.config['PROCESSED_FOLDER'] = str(PROCESSED_FOLDER)
app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH

# ===================== Secure Session Configuration for Hugging Face =====================
# These settings ensure cookies work correctly on Hugging Face Spaces (HTTPS environment)
app.config['SESSION_COOKIE_SECURE'] = True  # Only send cookies over HTTPS
app.config['SESSION_COOKIE_HTTPONLY'] = True  # Prevent JavaScript from accessing cookies
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'  # Allow cross-site form submissions
app.config['PERMANENT_SESSION_LIFETIME'] = 86400  # Session valid for 24 hours
app.config['SESSION_REFRESH_EACH_REQUEST'] = True  # Refresh session timeout on each request

# ===================== Proxy Middleware for Hugging Face =====================
# Apply ProxyFix to handle X-Forwarded-* headers from reverse proxy (HF Spaces)
# This ensures Flask recognizes HTTPS connections from the proxy
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_port=1, x_prefix=1)

# Folders are created by config/settings.py
# Ensure they exist
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs(app.config['PROCESSED_FOLDER'], exist_ok=True)

db = SQLAlchemy(app)

# ===================== Database Models =====================
class User(db.Model):
    """User model for authentication"""
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(200), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
    
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)


class AnalysisHistory(db.Model):
    """Store analysis history"""
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    analysis_type = db.Column(db.String(50), nullable=False)  # 'video' or 'live'
    filename = db.Column(db.String(200))
    detections = db.Column(db.Text)
    alert_count = db.Column(db.Integer, default=0)
    detection_count = db.Column(db.Integer, default=0)
    duration = db.Column(db.Integer, default=0)  # Duration in seconds for live monitoring
    models_used = db.Column(db.Text)  # JSON string of selected models
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    ended_at = db.Column(db.DateTime)
    # New fields for video analysis
    original_filename = db.Column(db.String(200))  # Original uploaded filename
    processed_video_url = db.Column(db.String(500))  # URL to processed video
    preview_image_url = db.Column(db.String(500))  # URL to preview image
    emergency_frames = db.Column(db.Text)  # JSON array of emergency frame filenames
    total_frames = db.Column(db.Integer, default=0)  # Total frames in video
    processed_frames = db.Column(db.Integer, default=0)  # Frames that were analyzed
    frame_summaries = db.Column(db.Text)  # JSON with frame-by-frame details


class PersonDetection(db.Model):
    """Store person detection records for live camera monitoring"""
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    person_count = db.Column(db.Integer, default=0)  # Number of people detected
    is_present = db.Column(db.Boolean, default=False)  # Whether person is currently present
    confidence = db.Column(db.Float, default=0.0)  # Detection confidence score
    detection_details = db.Column(db.Text)  # JSON string with additional details
    detected_at = db.Column(db.DateTime, default=datetime.utcnow)
    session_date = db.Column(db.Date, default=datetime.utcnow)  # For grouping by date
    
    def __repr__(self):
        return f'<PersonDetection {self.id}: {self.person_count} people on {self.detected_at}>'


class DetectionHistory(db.Model):
    """Store detection screenshots for weapons, unusual activity, and risks"""
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    detection_type = db.Column(db.String(50), nullable=False)  # 'weapon', 'unusual', 'risk'
    alert_level = db.Column(db.String(20), default='MEDIUM')  # LOW, MEDIUM, HIGH, CRITICAL
    confidence = db.Column(db.Float, default=0.0)  # Detection confidence
    image_filename = db.Column(db.String(200), nullable=False)  # Image filename in uploads/
    detection_details = db.Column(db.Text)  # JSON string with detection info (class, action, etc)
    detected_at = db.Column(db.DateTime, default=datetime.utcnow)
    session_date = db.Column(db.Date, default=datetime.utcnow)  # For grouping by date
    
    def __repr__(self):
        return f'<DetectionHistory {self.id}: {self.detection_type} on {self.detected_at}>'


class LiveSession(db.Model):
    """Store live monitoring session recordings and metadata"""
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    session_name = db.Column(db.String(200))  # User-friendly name
    video_filename = db.Column(db.String(200), nullable=False)  # MP4 filename in uploads/sessions/
    preview_image = db.Column(db.String(200))  # First frame preview
    detection_count = db.Column(db.Integer, default=0)  # Total detections
    alert_count = db.Column(db.Integer, default=0)  # Total alerts
    threat_count = db.Column(db.Integer, default=0)  # Critical threats (weapons, violence)
    duration = db.Column(db.Integer, default=0)  # Recording duration in seconds
    total_frames = db.Column(db.Integer, default=0)  # Total frames recorded
    models_used = db.Column(db.Text)  # JSON string of models used
    detections_summary = db.Column(db.Text)  # JSON with detection breakdown
    alerts_summary = db.Column(db.Text)  # JSON with alerts list
    emergency_frames = db.Column(db.Text)  # JSON array of emergency frame filenames
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    ended_at = db.Column(db.DateTime)
    is_critical = db.Column(db.Boolean, default=False)  # Flag for critical incidents
    notes = db.Column(db.Text)  # User notes
    
    def __repr__(self):
        return f'<LiveSession {self.id}: {self.session_name} on {self.created_at}>'


# ===================== Model Manager =====================
class ModelManager:
    """Manages all AI models for detection"""
    
    def __init__(self):
        self.models = {}
        self.load_models()
    
    def load_models(self):
        """Load all available models from ai_models/ directory"""
        ai_models_dir = PROJECT_ROOT / 'ai_models'
        
        print(f"\nπŸ“ Looking for models in: {ai_models_dir}")
        print(f"πŸ“ Directory exists: {ai_models_dir.exists()}")
        
        # List what's in the directory for debugging
        if ai_models_dir.exists():
            print(f"πŸ“‚ Contents of ai_models:")
            for item in ai_models_dir.rglob("*"):
                if item.is_file():
                    print(f"   - {item.relative_to(ai_models_dir)}")
        
        def find_model_file(patterns):
            """Find model file matching any of the patterns"""
            for pattern in patterns:
                # Try direct path
                path = ai_models_dir / pattern
                if path.exists():
                    return path
                
                # Try with ai_models/ prefix (nested structure)
                path = ai_models_dir / 'ai_models' / pattern
                if path.exists():
                    return path
            
            return None
        
        try:
            # Load Violence Detection Model
            violence_path = find_model_file(['activity_recognition/violence_model.h5'])
            if violence_path:
                self.models['violence'] = ViolenceDetector()
                print(f"βœ“ Violence Detection loaded from: {violence_path.relative_to(PROJECT_ROOT)}")
            else:
                print(f"⚠ Violence model not found")
        except Exception as e:
            print(f"βœ— Error loading violence model: {e}")
        
        try:
            # Load YOLO Object Detection Model
            yolo_path = find_model_file(['object_detection/yolov8n.pt'])
            if yolo_path:
                self.models['yolo'] = YOLODetector(model_path=str(yolo_path))
                print(f"βœ“ YOLO Object Detection loaded from: {yolo_path.relative_to(PROJECT_ROOT)}")
            else:
                print(f"⚠ YOLO model not found")
        except Exception as e:
            print(f"βœ— Error loading YOLO model: {e}")
        
        try:
            # Load Gun/Weapon Detection Model
            gun_path = find_model_file(['weapon_detection/best.pt'])
            person_path = find_model_file(['object_detection/yolov8n.pt'])

            if gun_path and person_path:
                self.models['weapon'] = WeaponPersonDetector(
                    gun_model_path=str(gun_path),
                    person_model_path=str(person_path)
                )
                print(f"βœ“ Weapon Detection loaded")
            else:
                print(f"⚠ Weapon detection models not found")
        except Exception as e:
            print(f"βœ— Error loading weapon model: {e}")

        try:
            # Load Pose Detection Model
            pose_path = find_model_file(['pose_detection/yolo11n-pose.pt'])
            if pose_path:
                self.models['pose'] = PoseDetection(model_path=str(pose_path))
                print(f"βœ“ Pose Detection loaded from: {pose_path.relative_to(PROJECT_ROOT)}")
            else:
                print(f"⚠ Pose model not found")
        except Exception as e:
            print(f"βœ— Error loading pose model: {e}")
        
        try:
            # Load Anomaly Detection Model
            anomaly_path = find_model_file(['weapon_detection/best.bin'])
            if anomaly_path:
                try:
                    self.models['anomaly'] = AnomalyDetector(model_path=str(anomaly_path))
                    print(f"βœ“ Anomaly Detection loaded")
                except Exception as init_error:
                    print(f"⚠ Failed to init anomaly detector: {init_error}")
            else:
                print(f"⚠ Anomaly model not found")
        except Exception as e:
            print(f"βœ— Error with anomaly model: {e}")
        
        try:
            # Load Analysis Model (Fight/Behavior Detection) - try multiple variants
            analysis_path = find_model_file([
                'analysis_models/fight_detection_model.h5',
                'analysis_models/CustomCNN.h5',
                'analysis_models/binarycnn200.h5'
            ])
            if analysis_path:
                try:
                    from tensorflow import keras
                    self.models['analysis'] = keras.models.load_model(str(analysis_path))
                    print(f"βœ“ Fight/Behavior Detection loaded from: {analysis_path.name}")
                except Exception as init_error:
                    print(f"⚠ Failed to load analysis model: {init_error}")
            else:
                print(f"⚠ Analysis models not found")
        except Exception as e:
            print(f"βœ— Error loading analysis model: {e}")
        
        try:
            # Load LSTM Model (Behavior/Activity Sequence Analysis)
            lstm_path = find_model_file([
                'LSTM Model/MobBiLSTM_model_saved101.keras',
                'LSTM_Model/MobBiLSTM_model_saved101.keras'
            ])
            if lstm_path:
                try:
                    from tensorflow import keras
                    self.models['lstm'] = keras.models.load_model(str(lstm_path), compile=False)
                    print(f"βœ“ LSTM Sequence Analysis loaded")
                except Exception as lstm_error:
                    print(f"⚠ Failed to load LSTM model: {lstm_error}")
            else:
                print(f"⚠ LSTM model not found")
        except Exception as e:
            print(f"βœ— Error with LSTM model: {e}")
        
        print(f"\nβœ“ Total models loaded: {len(self.models)}\n")
    
    def add_model(self, model_name, model_instance):
        """Add a new model dynamically"""
        self.models[model_name] = model_instance
    
    def get_model(self, model_name):
        """Get a specific model"""
        return self.models.get(model_name)
    
    def list_models(self):
        """List all available models"""
        return list(self.models.keys())
    
    def get_model_details(self):
        """Get details about all available models (loaded and available)"""
        model_info = {
            'violence': {'name': 'Violence Detection', 'description': 'Detects violent activities in video'},
            'yolo': {'name': 'Object Detection', 'description': 'Detects common objects (people, cars, etc)'},
            'weapon': {'name': 'Weapon Detection', 'description': 'Detects guns, knives and other weapons'},
            'pose': {'name': 'Pose Detection', 'description': 'Detects human poses and body movements'},
            'anomaly': {'name': 'Anomaly Detection (best.bin)', 'description': 'Detects unusual/anomalous behavior patterns'},
            'analysis': {'name': 'Advanced Analysis (Fight/Behavior)', 'description': 'Advanced behavior and fight detection analysis'},
            'lstm': {'name': 'LSTM Sequence Analysis', 'description': 'Temporal behavior analysis using bidirectional LSTM'},
        }
        
        model_details = {}
        # Return all models that are actually loaded
        for model_name in self.models.keys():
            model_details[model_name] = {
                'name': model_info.get(model_name, {}).get('name', model_name),
                'description': model_info.get(model_name, {}).get('description', ''),
                'enabled': True
            }
        
        return model_details


# Initialize model manager
model_manager = ModelManager()

# ===================== Video Processing =====================
class VideoProcessor:
    """Processes video frames and applies AI models"""
    
    def __init__(self):
        self.active_stream = None
        self.processing = False
        self.frame_index = 0
        self.alert_hit_threshold = 3
        self.unsafe_hit_streak = 0
        self.unsafe_alert_latched = False
        self.selected_models = None  # None means use all models
        # Temporal tracking for statistics (cumulative in video)
        self.person_detection_frames = 0
        self.weapon_detection_frames = 0
        self.person_consecutive_frames = 0
        self.weapon_consecutive_frames = 0
        self.weapon_alert_triggered = False  # Track if weapon alert already triggered
        # Session tracking
        self.session_detections = []
        self.session_alerts = []
        # LSTM frame buffer for temporal analysis (30 frames = ~1.5 seconds @ 20fps)
        self.lstm_frame_buffer = []
        self.lstm_buffer_size = 16
        self.lstm_prediction_cache = None
        self.last_pose_summary = None

    def set_selected_models(self, model_list):
        """Set which models to use for processing (None means all models)"""
        self.selected_models = model_list if model_list else None
    
    def is_model_selected(self, model_name):
        """Check if a model should be used"""
        if self.selected_models is None:
            return True
        return model_name in self.selected_models

    def reset_session_state(self):
        """Reset temporal detector state before a new video/live analysis session."""
        self.frame_index = 0
        self.unsafe_hit_streak = 0
        self.unsafe_alert_latched = False
        pose_model = model_manager.get_model('pose')
        if pose_model:
            try:
                pose_model.reset_movement_state()
            except Exception as e:
                pass
        
        anomaly_model = model_manager.get_model('anomaly')
        if anomaly_model:
            try:
                anomaly_model.reset()
            except Exception as e:
                pass
        
        # Reset temporal tracking
        self.person_detection_frames = 0
        self.weapon_detection_frames = 0
        self.person_consecutive_frames = 0
        self.weapon_consecutive_frames = 0
        # Reset pose tracking
        self.last_pose_summary = None
        self.weapon_alert_triggered = False
        # Reset session tracking
        self.session_detections = []
        self.session_alerts = []
        # Reset LSTM buffer
        self.lstm_frame_buffer = []
        self.lstm_prediction_cache = None

    def _update_alert_streak(self, condition_active, current_streak, is_latched):
        """Trigger one alert only after N consecutive hits, then wait for reset."""
        if condition_active:
            current_streak += 1
        else:
            return 0, False, False

        if current_streak >= self.alert_hit_threshold and not is_latched:
            return current_streak, True, True

        return current_streak, is_latched, False

    def _short_text(self, text, max_chars=28):
        """Trim long text so it fits compact overlay cells."""
        if not text:
            return "None"
        if len(text) <= max_chars:
            return text
        return text[:max_chars - 3] + "..."

    def _build_overlay_summary(self, results):
        """Build top panel summary from frame detections and alerts."""
        object_classes = []
        weapon_classes = []

        for det in results['detections']:
            det_type = det.get('type')
            det_class = det.get('class', 'unknown')
            if det_type == 'object':
                object_classes.append(det_class)
            elif det_type == 'weapon':
                weapon_classes.append(det_class)

        unique_objects = sorted(set(object_classes))
        unique_weapons = sorted(set(weapon_classes))

        object_text = ', '.join(unique_objects[:3]) if unique_objects else 'None'
        weapon_text = ', '.join(unique_weapons[:2]) if unique_weapons else 'None'

        behavior_text = 'Normal Activity'
        pose_summary = results.get('pose', {})
        pose_risk = pose_summary.get('risk_level')
        pose_action = pose_summary.get('action')
        if pose_risk and pose_risk != 'SAFE':
            behavior_text = f"{pose_risk.replace('_', ' ')}: {pose_action}"
        elif any(alert.get('type') == 'violence' for alert in results['alerts']):
            behavior_text = 'Violence Detected'

        if results['alerts']:
            highest_severity = results['alerts'][0].get('severity', 'ALERT')
            alert_text = f"{len(results['alerts'])} Active ({highest_severity})"
        else:
            alert_text = 'No Active Alerts'

        return {
            'Detected Objects': self._short_text(object_text),
            'Weapon Status': self._short_text(weapon_text),
            'Alert System': self._short_text(alert_text),
            'Behavior Analysis': self._short_text(behavior_text)
        }

    def _draw_top_info_panel(self, frame, summary):
        """Draw a compact 2x2 information panel at the top-center of the frame."""
        frame_h, frame_w = frame.shape[:2]

        panel_w = min(max(int(frame_w * 0.62), 360), max(frame_w - 20, 200))
        panel_h = min(max(int(frame_h * 0.20), 110), 170)

        x1 = (frame_w - panel_w) // 2
        y1 = 10
        x2 = x1 + panel_w
        y2 = y1 + panel_h

        overlay = frame.copy()
        cv2.rectangle(overlay, (x1, y1), (x2, y2), (18, 18, 18), -1)
        cv2.addWeighted(overlay, 0.65, frame, 0.35, 0, frame)

        cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 200, 255), 1)

        cell_w = panel_w // 2
        cell_h = panel_h // 2

        cv2.line(frame, (x1 + cell_w, y1), (x1 + cell_w, y2), (70, 70, 70), 1)
        cv2.line(frame, (x1, y1 + cell_h), (x2, y1 + cell_h), (70, 70, 70), 1)

        cells = [
            ('Detected Objects', summary['Detected Objects'], (80, 220, 80)),
            ('Weapon Status', summary['Weapon Status'], (70, 200, 255)),
            ('Alert System', summary['Alert System'], (0, 120, 255)),
            ('Behavior Analysis', summary['Behavior Analysis'], (160, 180, 255))
        ]

        for idx, (title, value, color) in enumerate(cells):
            col = idx % 2
            row = idx // 2
            tx = x1 + col * cell_w + 10
            ty = y1 + row * cell_h + 20

            cv2.putText(frame, title, (tx, ty), cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 1)
            cv2.putText(frame, value, (tx, ty + 22), cv2.FONT_HERSHEY_SIMPLEX, 0.48, (240, 240, 240), 1)

    def _draw_person_bounding_boxes(self, frame, detections):
        """Draw bounding boxes for detected persons with labels"""
        person_detections = [det for det in detections if det.get('class') == 'person']
        
        for det in person_detections:
            bbox = det.get('bbox', [])
            confidence = det.get('confidence', 0.0)
            
            if len(bbox) >= 4:
                x1, y1, x2, y2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
                
                # Ensure coordinates are within frame bounds
                h, w = frame.shape[:2]
                x1, y1 = max(0, x1), max(0, y1)
                x2, y2 = min(w, x2), min(h, y2)
                
                # Draw bounding box (green for person)
                color = (0, 255, 0)  # Green in BGR
                thickness = 2
                cv2.rectangle(frame, (x1, y1), (x2, y2), color, thickness)
                
                # Draw label with confidence
                label = f"Person {confidence:.2f}"
                label_size, baseline = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
                
                # Draw label background
                label_top = max(y1 - label_size[1] - 5, 0)
                cv2.rectangle(frame, (x1, label_top), (x1 + label_size[0], label_top + label_size[1] + 5), color, -1)
                
                # Draw label text
                cv2.putText(frame, label, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)

    def _severity_rank(self, severity):
        ranks = {'LOW': 1, 'MEDIUM': 2, 'HIGH': 3, 'CRITICAL': 4}
        return ranks.get((severity or '').upper(), 0)

    def _save_detection_screenshot(self, frame, detection_type, alert_level, confidence, details=None):
        """Save a screenshot of the detection region to database"""
        try:
            from flask import session

            user_id = session.get('user_id')
            if not user_id:
                return None
            
            # Generate unique filename
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            unique_id = str(uuid.uuid4())[:8]
            filename = f"detection_{detection_type}_{timestamp}_{unique_id}.jpg"
            
            # Create uploads directory if it doesn't exist
            upload_dir = UPLOAD_FOLDER / 'detections'
            upload_dir.mkdir(parents=True, exist_ok=True)
            
            # Save the frame
            filepath = upload_dir / filename
            cv2.imwrite(str(filepath), frame)
            
            # Save to database
            detection_record = DetectionHistory(
                user_id=user_id,
                detection_type=detection_type,
                alert_level=alert_level,
                confidence=confidence,
                image_filename=filename,
                detection_details=json.dumps(details) if details else None,
                detected_at=datetime.now(),
                session_date=date.today()
            )
            db.session.add(detection_record)
            db.session.commit()
            
            return detection_record.id
        except Exception as e:
            pass
            return None

    def _overlay_detections(self, frame, detections):
        """Draw compact detection boxes for key weapon/object detections."""
        colors = {
            'weapon': (0, 0, 255),
            'object': (0, 200, 0),
        }
        for det in detections:
            bbox = det.get('bbox')
            if not bbox or len(bbox) != 4:
                continue

            x1, y1, x2, y2 = [int(v) for v in bbox]
            det_type = det.get('type', 'object')
            label = f"{det.get('class', det_type)} {det.get('confidence', 0):.2f}"
            color = colors.get(det_type, (255, 180, 0))

            cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2 if det_type == 'weapon' else 1)
            (text_w, text_h), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.45, 1)
            text_y1 = max(0, y1 - text_h - 8)
            cv2.rectangle(frame, (x1, text_y1), (x1 + text_w + 8, y1), color, -1)
            cv2.putText(frame, label, (x1 + 4, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 255, 255), 1)

    def _annotate_pose_banner(self, frame, pose_summary):
        """Draw pose risk banner below the top info panel when pose is available."""
        if not pose_summary:
            return

        risk_level = pose_summary.get('risk_level', 'SAFE')
        action = pose_summary.get('action', 'other')
        score = pose_summary.get('risk_score', 0.0)

        if risk_level == 'HIGH_RISK':
            color = (0, 0, 220)
        elif risk_level == 'LOW_RISK':
            color = (0, 140, 255)
        else:
            color = (0, 128, 0)

        text = f"Pose Risk: {risk_level} | Action: {action} | Score: {score:.2f}"
        top = 188
        bottom = min(frame.shape[0] - 1, top + 34)
        cv2.rectangle(frame, (10, top), (frame.shape[1] - 10, bottom), color, -1)
        cv2.putText(frame, text, (20, top + 23), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)

    def _build_frame_summary(self, frame_number, results):
        """Create a UI-friendly frame-wise summary."""
        detections = results['detections']
        alerts = results['alerts']
        pose_summary = results.get('pose')

        highest_alert = max(alerts, key=lambda alert: self._severity_rank(alert.get('severity')), default=None)
        weapon_names = sorted({det['class'] for det in detections if det.get('type') == 'weapon'})
        object_names = sorted({det['class'] for det in detections if det.get('type') == 'object'})

        return {
            'frame_number': frame_number,
            'weapon_count': len([det for det in detections if det.get('type') == 'weapon']),
            'object_count': len([det for det in detections if det.get('type') == 'object']),
            'weapon_classes': weapon_names,
            'object_classes': object_names[:6],
            'pose_risk': pose_summary.get('risk_level', 'UNKNOWN') if pose_summary else 'UNAVAILABLE',
            'pose_action': pose_summary.get('action', 'unknown') if pose_summary else 'unknown',
            'pose_score': float(pose_summary.get('risk_score', 0.0)) if pose_summary else 0.0,
            'alert_state': highest_alert.get('severity', 'SAFE') if highest_alert else 'SAFE',
            'alert_message': highest_alert.get('message', 'No active alert') if highest_alert else 'No active alert',
            'detections': detections,
            'alerts': alerts,
        }

    def process_frame(self, frame):
        """Process a single frame with selected models"""
        self.frame_index += 1
        results = {
            'detections': [],
            'alerts': [],
            'annotated_frame': frame.copy(),
            'pose': None,
        }
        frame_result = None
        
        # Weapon Detection (Gun/Knife + Person counting)
        if self.is_model_selected('weapon') and 'weapon' in model_manager.models:
            try:
                weapon_model = model_manager.get_model('weapon')
                frame_result = weapon_model.process_frame(frame)
                
                # Track weapon detections without drawing frame bounding boxes
                for weapon in frame_result.weapons:
                    results['detections'].append({
                        'type': 'weapon',
                        'class': weapon.class_name,
                        'confidence': float(weapon.confidence),
                        'bbox': list(weapon.bbox)
                    })
                
            except Exception as e:
                pass

        # Pose Detection - Always run (needed for behavior analysis panel display)
        if 'pose' in model_manager.models:
            try:
                pose_model = model_manager.get_model('pose')
                pose_result = pose_model.predict(frame)[0]
                movement = pose_model.assess_movement(pose_result)
                results['pose'] = {
                    'risk_level': movement.get('risk_level', 'SAFE'),
                    'action': movement.get('action', 'other'),
                    'risk_score': float(movement.get('risk_score', 0.0)),
                    'details': movement.get('details', {}),
                }
            except Exception as e:
                pass
        
        # YOLO Object Detection (conf threshold matching main_cctv.py)
        if self.is_model_selected('yolo') and 'yolo' in model_manager.models:
            try:
                yolo_model = model_manager.get_model('yolo')
                detections = yolo_model.detect(frame, conf_threshold=DETECTION_THRESHOLDS['yolo'])
                
                for det in detections:
                    results['detections'].append({
                        'type': 'object',
                        'class': det.class_name,
                        'confidence': float(det.confidence),
                        'bbox': list(det.bbox)
                    })
            except Exception as e:
                pass
        
        # Violence Detection (conf threshold matching main_cctv.py)
        if self.is_model_selected('violence') and 'violence' in model_manager.models:
            try:
                violence_model = model_manager.get_model('violence')
                violence_result = violence_model.detect_violence(frame, confidence_threshold=DETECTION_THRESHOLDS['violence'])
                
                if violence_result.is_violence:
                    results['alerts'].append({
                        'type': 'violence',
                        'severity': violence_result.alert_level,
                        'confidence': float(violence_result.confidence),
                        'message': f'Violence detected: {violence_result.class_name}'
                    })
                    # Save screenshot of violence detection
                    self._save_detection_screenshot(
                        frame,
                        'violence',
                        violence_result.alert_level,
                        float(violence_result.confidence),
                        {'violence_class': violence_result.class_name}
                    )
            except Exception as e:
                pass
        
        # Anomaly Detection
        if self.is_model_selected('anomaly') and 'anomaly' in model_manager.models:
            try:
                anomaly_model = model_manager.get_model('anomaly')
                anomaly_result = anomaly_model.predict_frame(frame)
                
                if anomaly_result is not None:
                    results['detections'].append({
                        'type': 'anomaly',
                        'is_anomaly': anomaly_result.is_anomaly,
                        'confidence': float(anomaly_result.confidence),
                        'anomaly_score': float(anomaly_result.anomaly_score),
                        'alert_level': anomaly_result.alert_level,
                    })
                    
                    if anomaly_result.is_anomaly:
                        results['alerts'].append({
                            'type': 'anomaly_detected',
                            'severity': anomaly_result.alert_level,
                            'confidence': float(anomaly_result.confidence),
                            'message': anomaly_result.description,
                            'anomaly_score': float(anomaly_result.anomaly_score),
                        })
                        # Save screenshot of anomaly detection
                        self._save_detection_screenshot(
                            frame,
                            'anomaly',
                            anomaly_result.alert_level,
                            float(anomaly_result.confidence),
                            {'anomaly_score': float(anomaly_result.anomaly_score), 'description': anomaly_result.description}
                        )
            except Exception as e:
                pass

        has_weapon = any(det.get('type') == 'weapon' for det in results['detections'])
        has_person = any(det.get('class') == 'person' for det in results['detections'])
        
        # Track person and weapon detection duration (for statistics)
        if has_person:
            self.person_consecutive_frames += 1
        else:
            self.person_consecutive_frames = 0
        
        if has_weapon:
            self.weapon_consecutive_frames += 1
        else:
            self.weapon_consecutive_frames = 0
        
        # Only increment detection counters after 3+ consecutive frames (temporal threshold)
        if self.person_consecutive_frames >= 3 and self.person_consecutive_frames == 3:
            self.person_detection_frames += 1
        
        if self.weapon_consecutive_frames >= 3 and self.weapon_consecutive_frames == 3:
            self.weapon_detection_frames += 1
        
        # Add detection duration info to results
        results['person_detected'] = has_person
        results['weapon_detected'] = has_weapon
        results['person_consecutive_frames'] = self.person_consecutive_frames
        results['weapon_consecutive_frames'] = self.weapon_consecutive_frames
        
        pose_summary = results.get('pose')
        unsafe_pose = pose_summary and pose_summary.get('risk_level') in {'LOW_RISK', 'HIGH_RISK'}

        # WEAPON ALERT: Trigger alert if 3+ cumulative weapon detections in entire video
        if self.weapon_detection_frames >= self.alert_hit_threshold and not self.weapon_alert_triggered:
            self.weapon_alert_triggered = True
            results['alerts'].append({
                'type': 'weapon_detected',
                'severity': 'HIGH',
                'message': f'Weapon detected {self.weapon_detection_frames} times in video',
                'person_count': frame_result.person_count if frame_result else 0,
                'total_weapon_detections': self.weapon_detection_frames,
            })
            # Save screenshot of weapon detection
            weapon_det = next((d for d in results['detections'] if d.get('type') == 'weapon'), None)
            if weapon_det:
                self._save_detection_screenshot(
                    frame,
                    'weapon',
                    'HIGH',
                    weapon_det.get('confidence', 0.0),
                    {'weapon_class': weapon_det.get('class', 'unknown')}
                )

        if has_weapon and unsafe_pose:
            self.unsafe_hit_streak, self.unsafe_alert_latched, unsafe_should_alert = self._update_alert_streak(
                True,
                self.unsafe_hit_streak,
                self.unsafe_alert_latched,
            )
            if unsafe_should_alert:
                severity = 'CRITICAL' if pose_summary.get('risk_level') == 'HIGH_RISK' else 'HIGH'
                results['alerts'].append({
                    'type': 'weapon_unsafe_pose',
                    'severity': severity,
                    'message': (
                        f"Weapon and unsafe pose confirmed after {self.alert_hit_threshold} hits: "
                        f"{pose_summary.get('action', 'unknown')} ({pose_summary.get('risk_level')})"
                    ),
                    'pose_action': pose_summary.get('action', 'unknown'),
                    'pose_risk': pose_summary.get('risk_level', 'SAFE'),
                    'pose_score': float(pose_summary.get('risk_score', 0.0)),
                    'hit_count': self.unsafe_hit_streak,
                })
                # Save screenshot of risky pose + weapon
                self._save_detection_screenshot(
                    frame,
                    'risk',
                    severity,
                    pose_summary.get('risk_score', 0.0),
                    {
                        'action': pose_summary.get('action', 'unknown'),
                        'risk_level': pose_summary.get('risk_level', 'SAFE'),
                        'has_weapon': True
                    }
                )
        else:
            self.unsafe_hit_streak = 0
            self.unsafe_alert_latched = False

        # Show all frame insights in one compact top panel (2x2 small boxes)
        self._overlay_detections(results['annotated_frame'], results['detections'])
        self._draw_person_bounding_boxes(results['annotated_frame'], results['detections'])
        summary = self._build_overlay_summary(results)
        self._draw_top_info_panel(results['annotated_frame'], summary)
        # Store pose info for display in behavior analysis panel instead of on frame
        self.last_pose_summary = results.get('pose')
        
        # Process LSTM for temporal behavior analysis
        if self.is_model_selected('lstm') and 'lstm' in model_manager.models:
            try:
                lstm_result = self._process_lstm_frame(results['annotated_frame'])
                if lstm_result:
                    results['lstm_prediction'] = lstm_result
                    # Add LSTM annotation to frame
                    self._annotate_lstm_result(results['annotated_frame'], lstm_result)
            except Exception as e:
                pass
        
        results['frame_summary'] = self._build_frame_summary(self.frame_index, results)
        
        return results
    
    def _process_lstm_frame(self, frame):
        """Process frame through LSTM model for temporal behavior analysis."""
        try:
            # Resize frame to model's expected size: 64x64
            h, w = frame.shape[:2]
            target_size = (64, 64)
            resized = cv2.resize(frame, target_size)
            
            # Convert BGR to RGB if needed
            if len(resized.shape) == 3 and resized.shape[2] == 3:
                rgb_frame = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB)
            else:
                rgb_frame = resized
            
            # Normalize to [0, 1]
            normalized = rgb_frame.astype(np.float32) / 255.0
            
            # Add frame to buffer (don't expand dims yet, just add the frame)
            self.lstm_frame_buffer.append(normalized)
            
            # Keep buffer to exactly 16 frames for model input
            if len(self.lstm_frame_buffer) > 16:
                self.lstm_frame_buffer.pop(0)
            
            # Only predict when we have full sequence (16 frames)
            if len(self.lstm_frame_buffer) == 16:
                lstm_model = model_manager.get_model('lstm')
                if lstm_model:
                    try:
                        # Stack frames into sequence: (16, 64, 64, 3)
                        sequence = np.array(self.lstm_frame_buffer)  # Shape: (16, 64, 64, 3)
                        
                        # Add batch dimension: (1, 16, 64, 64, 3)
                        batch_sequence = np.expand_dims(sequence, axis=0)
                        
                        # Predict
                        predictions = lstm_model.predict(batch_sequence, verbose=0)
                        
                        # Extract prediction
                        if isinstance(predictions, np.ndarray):
                            pred_value = float(np.max(predictions))
                            pred_class = int(np.argmax(predictions))
                            
                            # Determine behavior label
                            behavior_labels = ['normal', 'anomalous', 'violent', 'suspicious']
                            behavior = behavior_labels[min(pred_class, len(behavior_labels)-1)]
                            
                            # Cache the prediction
                            self.lstm_prediction_cache = {
                                'behavior': behavior,
                                'confidence': min(pred_value, 1.0),
                                'class': pred_class,
                                'buffer_size': len(self.lstm_frame_buffer)
                            }
                            
                            return self.lstm_prediction_cache
                    except Exception as lstm_pred_error:
                        pass
        except Exception as e:
            pass
        
        return None if not self.lstm_prediction_cache else self.lstm_prediction_cache
    
    def _annotate_lstm_result(self, frame, lstm_result):
        """Draw LSTM prediction on frame."""
        if not lstm_result:
            return
        
        behavior = lstm_result.get('behavior', 'unknown')
        confidence = lstm_result.get('confidence', 0.0)
        
        # Color coding: green for normal, orange for anomalous, red for violent
        color_map = {
            'normal': (0, 255, 0),
            'anomalous': (0, 165, 255),
            'violent': (0, 0, 255),
            'suspicious': (0, 165, 255),
        }
        
        color = color_map.get(behavior, (128, 128, 128))
        
        # Draw LSTM result at bottom of frame
        h, w = frame.shape[:2]
        text = f"LSTM: {behavior.upper()} ({confidence:.2f})"
        text_size = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)[0]
        
        x = max(0, w - text_size[0] - 10)
        y = min(h, h - 10)
        
        cv2.rectangle(frame, (x-5, y-text_size[1]-5), (x+text_size[0]+5, y+5), color, -1)
        cv2.putText(frame, text, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)


video_processor = VideoProcessor()

# Background video analysis job tracking
analysis_jobs = {}  # job_id -> state dict (in-memory, transient)

# Camera stream generator
camera_lock = threading.Lock()
current_camera = None
selected_camera_index = 0  # Default to camera 0

# Video recording
recording_lock = threading.Lock()
is_recording = False
video_writer = None
recording_filename = None
recording_start_time = None
last_recorded_frame = None

def enumerate_cameras(max_cameras=10):
    """Detect all available cameras"""
    available_cameras = []
    
    for i in range(max_cameras):
        cap = cv2.VideoCapture(i)
        if cap.isOpened():
            # Get camera properties
            width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
            fps = cap.get(cv2.CAP_PROP_FPS)
            
            camera_info = {
                'index': i,
                'name': f"Camera {i}",
                'resolution': f"{width}x{height}",
                'fps': round(fps, 1),
                'available': True
            }
            available_cameras.append(camera_info)
            cap.release()
    
    return available_cameras

def generate_camera_frames():
    """Generate frames from camera using VideoCapture with motion detection (matches main_cctv.py)"""
    global current_camera, selected_camera_index

    with camera_lock:
        if current_camera is None:
            # Try to open the selected camera
            current_camera = VideoCapture(selected_camera_index, use_motion_detection=True)
            if not current_camera.start(verbose=False):
                # If selected camera fails, try to find any available camera
                available = enumerate_cameras()
                if available:
                    # Try the first available camera
                    for cam in available:
                        current_camera = VideoCapture(cam['index'], use_motion_detection=True)
                        if current_camera.start(verbose=False):
                            selected_camera_index = cam['index']
                            break
                        current_camera = None

                if current_camera is None:
                    return

            # Cap camera resolution to 640x480 for lighter streaming
            if current_camera.cap is not None:
                current_camera.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
                current_camera.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

            video_processor.reset_session_state()

    frame_counter = 0
    process_every_n = 3  # Run heavy AI models every 3rd frame for performance
    last_results = None

    try:
        for original, rois, fg_mask in current_camera.stream_rois():
            frame_counter += 1

            # Run AI every Nth frame; redraw cached overlay on the rest (fast)
            if frame_counter % process_every_n == 0 or last_results is None:
                results = video_processor.process_frame(original)
                last_results = results
                annotated_frame = results['annotated_frame']
            else:
                annotated_frame = original.copy()
                if last_results:
                    video_processor._overlay_detections(annotated_frame, last_results['detections'])
                    video_processor._draw_person_bounding_boxes(annotated_frame, last_results['detections'])
                    summary = video_processor._build_overlay_summary(last_results)
                    video_processor._draw_top_info_panel(annotated_frame, summary)

            # Handle video recording if enabled
            global is_recording, video_writer, recording_filename, last_recorded_frame

            with recording_lock:
                if is_recording and annotated_frame is not None:
                    # Initialize video writer on first frame
                    if video_writer is None:
                        video_dir = UPLOAD_FOLDER / 'videos'
                        video_dir.mkdir(parents=True, exist_ok=True)

                        height, width = annotated_frame.shape[:2]
                        fourcc, ext = get_video_codec()

                        # Create filename with timestamp
                        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
                        recording_filename = f"video_{timestamp}{ext}"
                        filepath = video_dir / recording_filename

                        video_writer = cv2.VideoWriter(
                            str(filepath),
                            fourcc,
                            15.0,  # 15 FPS matches our every-3rd-frame AI processing
                            (width, height)
                        )

                        global recording_start_time
                        recording_start_time = datetime.now()

                    # Write frame to video
                    if video_writer.isOpened():
                        video_writer.write(annotated_frame)
                        last_recorded_frame = annotated_frame.copy()

            # Encode at 75% JPEG quality β€” significantly reduces bandwidth/CPU
            ret, buffer = cv2.imencode('.jpg', annotated_frame, [cv2.IMWRITE_JPEG_QUALITY, 75])
            if not ret:
                continue
            frame_bytes = buffer.tobytes()

            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n')
    except GeneratorExit:
        pass


# ===================== Routes =====================

@app.route('/')
def home():
    """Public homepage with project information"""
    return render_template('home.html')


@app.route('/login')
def login_page():
    """Login/Register page"""
    if 'user_id' in session:
        return redirect(url_for('dashboard'))
    return render_template('login.html')


@app.route('/index')
def index():
    """Redirect old index route to login"""
    return redirect(url_for('login_page'))


@app.route('/register', methods=['POST'])
def register():
    """Register new user"""
    try:
        data = request.json
        username = data.get('username')
        email = data.get('email')
        password = data.get('password')
        
        # Validate input
        if not username or not email or not password:
            return jsonify({'success': False, 'message': 'All fields are required'}), 400
        
        # Check if user exists
        if User.query.filter_by(username=username).first():
            return jsonify({'success': False, 'message': 'Username already exists'}), 400
        
        if User.query.filter_by(email=email).first():
            return jsonify({'success': False, 'message': 'Email already registered'}), 400
        
        # Create new user
        user = User(username=username, email=email)
        user.set_password(password)
        db.session.add(user)
        db.session.commit()
        
        return jsonify({'success': True, 'message': 'Registration successful! Please login.'})
    
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500


@app.route('/login', methods=['POST'])
def login():
    """Login user"""
    try:
        data = request.json
        username = data.get('username')
        password = data.get('password')
        
        user = User.query.filter_by(username=username).first()
        
        if user and user.check_password(password):
            session.permanent = True  # Make session persistent across requests
            session['user_id'] = user.id
            session['username'] = user.username
            return jsonify({'success': True, 'message': 'Login successful!'})
        else:
            return jsonify({'success': False, 'message': 'Invalid username or password'}), 401
    
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500


@app.route('/logout')
def logout():
    """Logout user"""
    session.clear()
    return redirect(url_for('home'))


@app.route('/dashboard')
def dashboard():
    """Main dashboard after login"""
    if 'user_id' not in session:
        return redirect(url_for('login_page'))
    
    return render_template('dashboard.html', username=session.get('username'))


@app.route('/live-camera')
def live_camera():
    """Live camera analysis page"""
    if 'user_id' not in session:
        return redirect(url_for('login_page'))
    
    return render_template('live_camera.html')


@app.route('/video-analysis')
def video_analysis():
    """Video upload and analysis page"""
    if 'user_id' not in session:
        return redirect(url_for('login_page'))
    
    return render_template('video_analysis.html')


@app.route('/camera_feed')
def camera_feed():
    """Video streaming route"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    return Response(generate_camera_frames(),
                   mimetype='multipart/x-mixed-replace; boundary=frame')


@app.route('/processed/<path:filename>')
def processed_file(filename):
    """Serve processed previews and videos."""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    return send_from_directory(app.config['PROCESSED_FOLDER'], filename)


@app.route('/upload_video', methods=['POST'])
def upload_video():
    """Upload video for analysis"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    try:
        if 'video' not in request.files:
            return jsonify({'success': False, 'message': 'No video file uploaded'}), 400
        
        file = request.files['video']
        if file.filename == '':
            return jsonify({'success': False, 'message': 'No file selected'}), 400
        
        # Save file
        filename = secure_filename(file.filename)
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        filename = f"{timestamp}_{filename}"
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(filepath)
        
        # Process video
        results = process_video_file(filepath)
        
        # Save to history with all details
        history = AnalysisHistory(
            user_id=session['user_id'],
            analysis_type='video',
            filename=filename,
            original_filename=file.filename,
            detections=json.dumps(results.get('detections', [])),
            alert_count=len(results.get('alerts', [])),
            detection_count=len(results.get('detections', [])),
            models_used=json.dumps(session.get('selected_models', [])),
            processed_video_url=results.get('output_url'),
            preview_image_url=results.get('preview_url'),
            emergency_frames=json.dumps(results.get('emergency_frames', [])),
            total_frames=results.get('total_frames', 0),
            processed_frames=results.get('processed_frames', 0),
            frame_summaries=json.dumps(results.get('frame_summaries', []))
        )
        db.session.add(history)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Video processed successfully',
            'analysis_id': history.id,
            'results': results
        })
    
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500


def process_video_file(filepath):
    """Process an uploaded video file with selected models and capture emergency frames"""
    cap = cv2.VideoCapture(filepath)
    all_detections = []
    all_alerts = []
    frame_count = 0
    processed_frames = 0
    frame_summaries = []
    emergency_frames = []  # Track captured emergency frames
    
    # Set selected models if specified in session
    selected_models = session.get('selected_models', [])
    if selected_models:
        video_processor.set_selected_models(selected_models)

    input_path = Path(filepath)
    processed_name = f"{input_path.stem}_processed.mp4"
    preview_name = f"{input_path.stem}_preview.jpg"
    processed_path = Path(app.config['PROCESSED_FOLDER']) / processed_name
    preview_path = Path(app.config['PROCESSED_FOLDER']) / preview_name
    
    # Create emergency frames directory
    emergency_frames_dir = Path(app.config['PROCESSED_FOLDER']) / 'emergency_frames'
    emergency_frames_dir.mkdir(parents=True, exist_ok=True)

    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 640
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 480
    fps = cap.get(cv2.CAP_PROP_FPS) or 20.0
    fourcc, ext = get_video_codec()
    # Update processed filename to use correct extension
    processed_name = f"{input_path.stem}_processed{ext}"
    processed_path = Path(app.config['PROCESSED_FOLDER']) / processed_name
    writer = cv2.VideoWriter(
        str(processed_path),
        fourcc,
        fps,
        (width, height),
    )

    video_processor.reset_session_state()
    
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break
        
        # Process every Nth frame to speed up (from PROCESSING_PARAMS)
        if frame_count % PROCESSING_PARAMS['frame_skip'] == 0:
            results = video_processor.process_frame(frame)
            all_detections.extend(results['detections'])
            all_alerts.extend(results['alerts'])
            frame_summaries.append(results['frame_summary'])
            writer.write(results['annotated_frame'])
            processed_frames += 1
            if processed_frames == 1:
                cv2.imwrite(str(preview_path), results['annotated_frame'])
            
            # Capture emergency frames (HIGH or CRITICAL alerts, or weapons detected)
            has_critical_alert = any(alert.get('severity') in {'HIGH', 'CRITICAL'} for alert in results['alerts'])
            has_weapon = any(det.get('type') == 'weapon' for det in results['detections'])
            has_violence = any(alert.get('type') == 'violence' for alert in results['alerts'])
            has_anomaly_alert = any(alert.get('type') == 'anomaly_detected' for alert in results['alerts'])
            
            if has_critical_alert or has_weapon or has_violence or has_anomaly_alert:
                # Save emergency frame with timestamp
                emergency_filename = f"emergency_frame_{processed_frames}_t{frame_count}.jpg"
                emergency_path = emergency_frames_dir / emergency_filename
                cv2.imwrite(str(emergency_path), results['annotated_frame'])
                emergency_frames.append({
                    'filename': emergency_filename,
                    'frame_number': processed_frames,
                    'timestamp_frame': frame_count,
                    'alert_type': 'CRITICAL' if has_critical_alert else ('WEAPON' if has_weapon else ('VIOLENCE' if has_violence else 'ANOMALY')),
                    'has_weapon': has_weapon,
                    'has_violence': has_violence,
                    'has_anomaly': has_anomaly_alert
                })
        
        frame_count += 1
    
    cap.release()
    writer.release()

    risk_counts = {'SAFE': 0, 'LOW_RISK': 0, 'HIGH_RISK': 0, 'UNAVAILABLE': 0}
    for summary in frame_summaries:
        risk_counts[summary['pose_risk']] = risk_counts.get(summary['pose_risk'], 0) + 1

    output_url = url_for('processed_file', filename=processed_name) if processed_frames else None
    preview_url = url_for('processed_file', filename=preview_name) if processed_frames else None
    output_mime = mimetypes.guess_type(processed_name)[0] or 'video/mp4'
    
    return {
        'total_frames': frame_count,
        'processed_frames': processed_frames,
        'detections': all_detections,
        'alerts': all_alerts,
        'frame_summaries': frame_summaries,
        'output_url': output_url,
        'output_mime': output_mime,
        'preview_url': preview_url,
        'emergency_frames': emergency_frames,
        'summary': {
            'total_detections': len(all_detections),
            'total_alerts': len(all_alerts),
            'emergency_frames_count': len(emergency_frames),
            'weapon_alert_frames': sum(1 for frame in frame_summaries if frame['weapon_count'] > 0),
            'unsafe_pose_frames': sum(1 for frame in frame_summaries if frame['pose_risk'] in {'LOW_RISK', 'HIGH_RISK'}),
            'critical_frames': sum(1 for frame in frame_summaries if frame['alert_state'] == 'CRITICAL'),
            'pose_risk_counts': risk_counts,
        }
    }


@app.route('/api/models')
def list_models():
    """List all available models"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    models = model_manager.list_models()
    return jsonify({'models': models})


@app.route('/api/available-models')
def get_available_models():
    """Get detailed information about available models"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    models = model_manager.get_model_details()
    return jsonify({'models': models})


@app.route('/api/set-models', methods=['POST'])
def set_active_models():
    """Set which models to use for analysis"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    try:
        data = request.get_json()
        selected_models = data.get('models', [])
        
        # Store in session
        session['selected_models'] = selected_models
        session.modified = True
        
        # Also update the video processor
        video_processor.set_selected_models(selected_models)
        
        return jsonify({
            'success': True,
            'message': f'Models updated: {selected_models if selected_models else "All"}',
            'selected': selected_models
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400


@app.route('/api/get-selected-models')
def get_selected_models():
    """Get currently selected models for the user"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    selected = session.get('selected_models', [])
    return jsonify({'selected_models': selected})


@app.route('/api/live-stats')
def get_live_stats():
    """Get live monitoring statistics"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    pose_data = {}
    if video_processor.last_pose_summary:
        pose_data = {
            'risk_level': video_processor.last_pose_summary.get('risk_level', 'SAFE'),
            'action': video_processor.last_pose_summary.get('action', 'unknown'),
            'risk_score': video_processor.last_pose_summary.get('risk_score', 0.0)
        }
    
    return jsonify({
        'detection_count': session.get('total_detections', 0),
        'alert_count': session.get('total_alerts', 0),
        'person_detections': video_processor.person_detection_frames,
        'weapon_detections': video_processor.weapon_detection_frames,
        'person_visible': video_processor.person_consecutive_frames >= 3,
        'weapon_visible': video_processor.weapon_consecutive_frames >= 3,
        'pose_analysis': pose_data
    })


@app.route('/api/start-camera', methods=['POST'])
def start_camera_session():
    """Start a camera monitoring session with selected models"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    try:
        data = request.get_json()
        selected_models = data.get('selectedModels', [])
        
        # Store session metadata
        session['monitoring_session_start'] = datetime.utcnow().isoformat()
        session['monitoring_models'] = selected_models
        session.modified = True
        
        # Reset statistics counters for new session
        video_processor.reset_session_state()
        
        return jsonify({
            'success': True,
            'message': 'Camera monitoring session started',
            'models': selected_models
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400


@app.route('/api/cameras', methods=['GET'])
def get_available_cameras():
    """Get list of all available cameras"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    try:
        cameras = enumerate_cameras()
        return jsonify({
            'success': True,
            'cameras': cameras,
            'selected': selected_camera_index
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400


@app.route('/api/select-camera', methods=['POST'])
def select_camera():
    """Select which camera to use"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    global current_camera, selected_camera_index
    
    try:
        data = request.get_json()
        camera_index = data.get('camera_index', 0)
        
        # Stop current camera
        with camera_lock:
            if current_camera is not None:
                current_camera.stop()
                current_camera = None
            
            selected_camera_index = camera_index
        
        return jsonify({
            'success': True,
            'message': f'Camera {camera_index} selected',
            'selected': camera_index
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400


# ===================== Helper Functions =====================
def parse_iso_timestamp(timestamp_str):
    """Parse ISO format timestamp, handling 'Z' suffix for UTC"""
    if isinstance(timestamp_str, str):
        # Remove 'Z' suffix if present (indicates UTC)
        if timestamp_str.endswith('Z'):
            timestamp_str = timestamp_str[:-1]
        try:
            return datetime.fromisoformat(timestamp_str)
        except (ValueError, TypeError):
            return datetime.utcnow()
    elif isinstance(timestamp_str, datetime):
        return timestamp_str
    return datetime.utcnow()


@app.route('/api/save-monitoring-session', methods=['POST'])
def save_monitoring_session():
    """Save monitoring session results to database with optional video recording"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    try:
        user_id = session['user_id']
        data = request.get_json()
        
        # Check if recording filename is provided (from live camera session)
        recording_filename = data.get('recordingFilename')
        video_filename = None
        preview_filename = None
        
        if recording_filename:
            # Move the recorded video from uploads/videos/ to processed/sessions/
            try:
                sessions_dir = PROCESSED_FOLDER / 'sessions'
                sessions_dir.mkdir(parents=True, exist_ok=True)

                timestamp = datetime.utcnow().strftime('%Y%m%d_%H%M%S')
                user_folder = sessions_dir / f"user_{user_id}"
                user_folder.mkdir(parents=True, exist_ok=True)

                # Source video file
                source_path = UPLOAD_FOLDER / 'videos' / recording_filename
                if source_path.exists():
                    # Copy to session folder with new name
                    video_filename = f"session_{timestamp}_{uuid.uuid4().hex[:8]}.mp4"
                    dest_path = user_folder / video_filename
                    shutil.copy2(str(source_path), str(dest_path))

                    preview_filename = None
                    preview_path = None

                    # Extract preview frame from video
                    try:
                        cap = cv2.VideoCapture(str(dest_path))
                        ret, frame = cap.read()
                        if ret:
                            preview_filename = f"preview_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
                            preview_path = user_folder / preview_filename
                            cv2.imwrite(str(preview_path), frame)
                        cap.release()
                    except Exception:
                        pass

                    # Create LiveSession record (paths relative to PROCESSED_FOLDER)
                    live_session = LiveSession(
                        user_id=user_id,
                        session_name=data.get('sessionName', f"Live Session {timestamp}"),
                        video_filename=str(dest_path.relative_to(PROCESSED_FOLDER)),
                        preview_image=str(preview_path.relative_to(PROCESSED_FOLDER)) if preview_path else None,
                        detection_count=data.get('totalDetections', 0),
                        alert_count=data.get('totalAlerts', 0),
                        threat_count=data.get('threatCount', 0),
                        duration=int(data.get('duration', 0)),
                        total_frames=data.get('totalFrames', 0),
                        models_used=json.dumps(data.get('selectedModels', [])),
                        detections_summary=json.dumps(data.get('detectionsSummary', {})),
                        alerts_summary=json.dumps(data.get('alertsSummary', [])),
                        emergency_frames=json.dumps(data.get('emergencyFrames', [])),
                        created_at=parse_iso_timestamp(data.get('startTime')),
                        ended_at=parse_iso_timestamp(data.get('endTime')),
                        is_critical=data.get('isCritical', False)
                    )
                    db.session.add(live_session)
                    db.session.commit()

                    return jsonify({
                        'success': True,
                        'message': 'Live session saved successfully',
                        'session_id': live_session.id,
                        'video_url': url_for('processed_file', filename=str(dest_path.relative_to(PROCESSED_FOLDER)))
                    })
            except Exception:
                pass
                # Continue without video if save fails
        
        # Check if base64 video data is provided
        video_data = data.get('videoData')
        if video_data:
            # Create sessions directory if it doesn't exist
            sessions_dir = PROCESSED_FOLDER / 'sessions'
            sessions_dir.mkdir(parents=True, exist_ok=True)

            # Generate unique filename
            timestamp = datetime.utcnow().strftime('%Y%m%d_%H%M%S')
            user_folder = sessions_dir / f"user_{user_id}"
            user_folder.mkdir(parents=True, exist_ok=True)

            video_filename = f"session_{timestamp}_{uuid.uuid4().hex[:8]}.mp4"
            video_path = user_folder / video_filename

            # Decode base64 video data and save
            try:
                # Remove data URL prefix if present
                if video_data.startswith('data:'):
                    video_data = video_data.split(',', 1)[1]

                video_bytes = base64.b64decode(video_data)
                with open(video_path, 'wb') as f:
                    f.write(video_bytes)

                preview_filename = None
                preview_path = None

                # Extract preview frame from video
                try:
                    cap = cv2.VideoCapture(str(video_path))
                    ret, frame = cap.read()
                    if ret:
                        preview_filename = f"preview_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
                        preview_path = user_folder / preview_filename
                        cv2.imwrite(str(preview_path), frame)
                    cap.release()
                except Exception:
                    pass

                # Create LiveSession record (paths relative to PROCESSED_FOLDER)
                live_session = LiveSession(
                    user_id=user_id,
                    session_name=data.get('sessionName', f"Session {timestamp}"),
                    video_filename=str(video_path.relative_to(PROCESSED_FOLDER)),
                    preview_image=str(preview_path.relative_to(PROCESSED_FOLDER)) if preview_path else None,
                    detection_count=data.get('totalDetections', 0),
                    alert_count=data.get('totalAlerts', 0),
                    threat_count=data.get('threatCount', 0),
                    duration=int(data.get('duration', 0)),
                    total_frames=data.get('totalFrames', 0),
                    models_used=json.dumps(data.get('selectedModels', [])),
                    detections_summary=json.dumps(data.get('detectionsSummary', {})),
                    alerts_summary=json.dumps(data.get('alertsSummary', [])),
                    emergency_frames=json.dumps(data.get('emergencyFrames', [])),
                    created_at=parse_iso_timestamp(data.get('startTime')),
                    ended_at=parse_iso_timestamp(data.get('endTime')),
                    is_critical=data.get('isCritical', False)
                )
                db.session.add(live_session)
                db.session.commit()
                
                return jsonify({
                    'success': True,
                    'message': f'Live session saved successfully',
                    'session_id': live_session.id,
                    'video_url': f"/processed/sessions/user_{user_id}/{video_filename}"
                })
            except Exception as e:
                pass
                # Continue without video if save fails
        
        # Fallback: Create AnalysisHistory record (for backward compatibility)
        history = AnalysisHistory(
            user_id=user_id,
            analysis_type='live',
            detection_count=data.get('totalDetections', 0),
            alert_count=data.get('totalAlerts', 0),
            duration=data.get('duration', 0),
            models_used=str(data.get('selectedModels', [])),
            created_at=parse_iso_timestamp(data.get('startTime')),
            ended_at=parse_iso_timestamp(data.get('endTime')),
            detections=str(data.get('detections', []))
        )
        
        db.session.add(history)
        db.session.commit()
        
        # Clear session monitoring data
        session.pop('monitoring_session_start', None)
        session.pop('monitoring_models', None)
        session.modified = True
        
        return jsonify({
            'success': True,
            'message': f'Monitoring session saved. Detection Count: {data.get("totalDetections", 0)}, Alerts: {data.get("totalAlerts", 0)}',
            'session_id': history.id
        })
    except Exception as e:
        pass
        return jsonify({'success': False, 'error': str(e)}), 400


@app.route('/api/save-person-detection', methods=['POST'])
def save_person_detection():
    """Save person detection data to database"""
    if 'user_id' not in session:
        return jsonify({'success': False, 'error': 'Unauthorized'}), 401
    
    try:
        data = request.get_json()
        user_id = session['user_id']
        
        # Create person detection record
        person_detection = PersonDetection(
            user_id=user_id,
            person_count=data.get('person_count', 0),
            is_present=data.get('is_present', False),
            confidence=data.get('confidence', 0.0),
            detection_details=data.get('detection_details'),
            detected_at=datetime.utcnow(),
            session_date=datetime.utcnow().date()
        )
        
        db.session.add(person_detection)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Person detection saved',
            'detection_id': person_detection.id
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'error': str(e)}), 400


@app.route('/api/person-detection-history', methods=['GET'])
def get_person_detection_history():
    """Get person detection history for current user"""
    if 'user_id' not in session:
        return jsonify({'success': False, 'error': 'Unauthorized'}), 401
    
    try:
        user_id = session['user_id']
        
        # Get all person detection records for today
        today = datetime.utcnow().date()
        detections = PersonDetection.query.filter_by(
            user_id=user_id,
            session_date=today
        ).all()
        
        if not detections:
            return jsonify({
                'success': True,
                'data': {
                    'total_detections': 0,
                    'currently_present': False,
                    'detection_records': []
                }
            })
        
        # Calculate statistics
        total_detections = sum(d.person_count for d in detections)
        latest_detection = detections[-1]
        currently_present = latest_detection.is_present
        
        return jsonify({
            'success': True,
            'data': {
                'total_detections': total_detections,
                'currently_present': currently_present,
                'latest_confidence': latest_detection.confidence,
                'detection_count': len(detections),
                'detection_records': [
                    {
                        'id': d.id,
                        'person_count': d.person_count,
                        'is_present': d.is_present,
                        'confidence': d.confidence,
                        'detected_at': d.detected_at.isoformat()
                    }
                    for d in detections
                ]
            }
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400


@app.route('/api/detection-history', methods=['GET'])
def get_detection_history():
    """Get threat detection history (weapons, unusual activity, risks) and live sessions"""
    if 'user_id' not in session:
        return jsonify({'success': False, 'error': 'Unauthorized'}), 401
    
    try:
        user_id = session['user_id']
        limit = request.args.get('limit', 20, type=int)
        detection_type = request.args.get('type', None)  # Filter by type: weapon, unusual, risk, session
        include_sessions = request.args.get('include_sessions', 'true').lower() == 'true'
        
        result_data = []
        
        # Get detection history
        if not detection_type or detection_type != 'session':
            query = DetectionHistory.query.filter_by(user_id=user_id)
            
            if detection_type:
                query = query.filter_by(detection_type=detection_type)
            
            detections = query.order_by(DetectionHistory.detected_at.desc()).limit(limit).all()
            
            for d in detections:
                result_data.append({
                    'id': d.id,
                    'type': 'detection',
                    'detection_type': d.detection_type,
                    'alert_level': d.alert_level,
                    'confidence': d.confidence,
                    'image_filename': d.image_filename,
                    'detected_at': d.detected_at.isoformat(),
                    'details': json.loads(d.detection_details) if d.detection_details else {}
                })
        
        # Get live sessions if requested
        if include_sessions and (not detection_type or detection_type == 'session'):
            sessions = LiveSession.query.filter_by(user_id=user_id).order_by(LiveSession.created_at.desc()).limit(limit).all()
            
            for live_sess in sessions:
                result_data.append({
                    'id': live_sess.id,
                    'type': 'session',
                    'session_name': live_sess.session_name,
                    'detection_count': live_sess.detection_count,
                    'alert_count': live_sess.alert_count,
                    'threat_count': live_sess.threat_count,
                    'duration': live_sess.duration,
                    'video_filename': live_sess.video_filename,
                    'preview_image': live_sess.preview_image,
                    'is_critical': live_sess.is_critical,
                    'created_at': live_sess.created_at.isoformat(),
                    'details': {
                        'models_used': json.loads(live_sess.models_used) if live_sess.models_used else [],
                        'emergency_frames': json.loads(live_sess.emergency_frames) if live_sess.emergency_frames else []
                    }
                })
        
        # Sort by timestamp
        result_data.sort(key=lambda x: x.get('detected_at') or x.get('created_at'), reverse=True)
        
        return jsonify({
            'success': True,
            'data': result_data
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400


@app.route('/api/detection-image/<filename>')
def get_detection_image(filename):
    """Get detection screenshot image"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    try:
        # Security check: verify filename format
        user_id = session['user_id']
        
        # Find the detection record to verify ownership
        detection = DetectionHistory.query.filter_by(
            user_id=user_id,
            image_filename=filename
        ).first()
        
        if not detection:
            return jsonify({'error': 'Image not found'}), 404
        
        # Serve the image
        upload_dir = UPLOAD_FOLDER / 'detections'
        filepath = upload_dir / filename

        if filepath.exists():
            return send_from_directory(str(upload_dir), filename)
        else:
            return jsonify({'error': 'Image file not found'}), 404
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/stop_camera', methods=['POST'])
def stop_camera():
    """Stop the camera stream"""
    global current_camera
    
    with camera_lock:
        if current_camera is not None:
            current_camera.stop()
            current_camera = None
    
    return jsonify({'success': True})


@app.route('/api/start-recording', methods=['POST'])
def start_recording():
    """Start video recording"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    global is_recording
    
    with recording_lock:
        if is_recording:
            return jsonify({'success': False, 'error': 'Recording already in progress'}), 400
        
        is_recording = True
    
    return jsonify({
        'success': True,
        'message': 'Recording started',
        'timestamp': datetime.utcnow().isoformat()
    })


@app.route('/api/stop-recording', methods=['POST'])
def stop_recording():
    """Stop video recording"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    global is_recording, video_writer, recording_filename, recording_start_time
    
    with recording_lock:
        if not is_recording:
            return jsonify({'success': False, 'error': 'No recording in progress'}), 400
        
        # Finalize video writer
        if video_writer is not None:
            video_writer.release()
            video_writer = None
        
        is_recording = False
        
        duration = 0
        if recording_start_time:
            duration = (datetime.now() - recording_start_time).total_seconds()
            recording_start_time = None
    
    return jsonify({
        'success': True,
        'message': 'Recording stopped',
        'filename': recording_filename,
        'duration': round(duration, 2),
        'timestamp': datetime.utcnow().isoformat()
    })


@app.route('/api/recording-status', methods=['GET'])
def get_recording_status():
    """Get current recording status"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    duration = 0
    if is_recording and recording_start_time:
        duration = (datetime.now() - recording_start_time).total_seconds()
    
    return jsonify({
        'success': True,
        'is_recording': is_recording,
        'filename': recording_filename,
        'duration': round(duration, 2),
        'start_time': recording_start_time.isoformat() if recording_start_time else None
    })


@app.route('/api/videos', methods=['GET'])
def get_videos():
    """Get list of recorded videos"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    try:
        video_dir = UPLOAD_FOLDER / 'videos'
        if not video_dir.exists():
            return jsonify({'success': True, 'videos': []})

        videos = []
        all_videos = sorted(
            list(video_dir.glob('*.mp4')) + list(video_dir.glob('*.avi')),
            key=lambda f: f.stat().st_mtime, reverse=True
        )
        for video_file in all_videos:
            stat = video_file.stat()
            videos.append({
                'filename': video_file.name,
                'size': round(stat.st_size / 1024 / 1024, 2),  # MB
                'created': datetime.fromtimestamp(stat.st_mtime).isoformat(),
                'path': f'/api/download-video/{video_file.name}'
            })

        return jsonify({'success': True, 'videos': videos})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400


@app.route('/api/images', methods=['GET'])
def get_images():
    """Get list of captured images"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    try:
        image_dir = UPLOAD_FOLDER / 'detections'
        if not image_dir.exists():
            return jsonify({'success': True, 'images': []})

        images = []
        for image_file in sorted(image_dir.glob('*.jpg'), reverse=True):
            stat = image_file.stat()
            images.append({
                'filename': image_file.name,
                'size': round(stat.st_size / 1024, 2),  # KB
                'created': datetime.fromtimestamp(stat.st_mtime).isoformat(),
                'path': f'/api/detection-image/{image_file.name}'
            })

        return jsonify({'success': True, 'images': images})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400


@app.route('/api/download-video/<filename>', methods=['GET'])
def download_video(filename):
    """Download a recorded video"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    try:
        # Security: validate filename format
        if not filename.endswith(('.mp4', '.avi')) or '..' in filename:
            return jsonify({'error': 'Invalid filename'}), 400

        video_dir = UPLOAD_FOLDER / 'videos'
        filepath = video_dir / filename

        if not filepath.exists():
            return jsonify({'error': 'Video not found'}), 404

        return send_from_directory(str(video_dir), filename, as_attachment=True)
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/api/download-image/<filename>', methods=['GET'])
def download_image(filename):
    """Download a captured image"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    
    try:
        # Security: validate filename format
        if not filename.endswith('.jpg') or '..' in filename:
            return jsonify({'error': 'Invalid filename'}), 400

        image_dir = UPLOAD_FOLDER / 'detections'
        filepath = image_dir / filename

        if not filepath.exists():
            return jsonify({'error': 'Image not found'}), 404

        return send_from_directory(str(image_dir), filename, as_attachment=True)
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/api/sessions/<int:session_id>', methods=['DELETE'])
def delete_session(session_id):
    """Delete a live monitoring session and its associated files"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    try:
        user_id = session['user_id']
        live_sess = LiveSession.query.filter_by(id=session_id, user_id=user_id).first()
        if not live_sess:
            return jsonify({'success': False, 'error': 'Session not found'}), 404

        # Delete associated files
        for attr, base_dir in [('video_filename', PROCESSED_FOLDER), ('preview_image', PROCESSED_FOLDER)]:
            fname = getattr(live_sess, attr, None)
            if fname:
                fpath = base_dir / fname
                if fpath.exists():
                    fpath.unlink()

        db.session.delete(live_sess)
        db.session.commit()
        return jsonify({'success': True})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'error': str(e)}), 400


@app.route('/api/videos/<filename>', methods=['DELETE'])
def delete_video(filename):
    """Delete a raw recorded video file"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    try:
        if '..' in filename or not filename.endswith('.mp4'):
            return jsonify({'success': False, 'error': 'Invalid filename'}), 400
        fpath = UPLOAD_FOLDER / 'videos' / filename
        if fpath.exists():
            fpath.unlink()
        return jsonify({'success': True})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400


@app.route('/api/images/<filename>', methods=['DELETE'])
def delete_image(filename):
    """Delete a detection image and its DB record"""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401
    try:
        if '..' in filename or not filename.endswith('.jpg'):
            return jsonify({'success': False, 'error': 'Invalid filename'}), 400
        user_id = session['user_id']
        record = DetectionHistory.query.filter_by(user_id=user_id, image_filename=filename).first()
        if record:
            db.session.delete(record)
            db.session.commit()
        fpath = UPLOAD_FOLDER / 'detections' / filename
        if fpath.exists():
            fpath.unlink()
        return jsonify({'success': True})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'error': str(e)}), 400


@app.route('/api/video-analysis-history/<int:analysis_id>', methods=['GET'])
def get_video_analysis(analysis_id):
    """Get details of a specific video analysis"""
    if 'user_id' not in session:
        return jsonify({'success': False, 'error': 'Unauthorized'}), 401
    
    try:
        user_id = session['user_id']
        analysis = AnalysisHistory.query.filter_by(
            id=analysis_id,
            user_id=user_id,
            analysis_type='video'
        ).first()
        
        if not analysis:
            return jsonify({'success': False, 'error': 'Analysis not found'}), 404
        
        return jsonify({
            'success': True,
            'data': {
                'id': analysis.id,
                'original_filename': analysis.original_filename,
                'uploaded_filename': analysis.filename,
                'created_at': analysis.created_at.isoformat(),
                'total_frames': analysis.total_frames,
                'processed_frames': analysis.processed_frames,
                'detection_count': analysis.detection_count,
                'alert_count': analysis.alert_count,
                'processed_video_url': analysis.processed_video_url,
                'preview_image_url': analysis.preview_image_url,
                'models_used': json.loads(analysis.models_used) if analysis.models_used else [],
                'emergency_frames': json.loads(analysis.emergency_frames) if analysis.emergency_frames else [],
                'frame_summaries': json.loads(analysis.frame_summaries) if analysis.frame_summaries else [],
                'detections': json.loads(analysis.detections) if analysis.detections else []
            }
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400


@app.route('/api/video-analysis-list', methods=['GET'])
def get_video_analysis_list():
    """Get list of all video analyses for current user"""
    if 'user_id' not in session:
        return jsonify({'success': False, 'error': 'Unauthorized'}), 401
    
    try:
        user_id = session['user_id']
        limit = request.args.get('limit', 20, type=int)
        
        analyses = AnalysisHistory.query.filter_by(
            user_id=user_id,
            analysis_type='video'
        ).order_by(AnalysisHistory.created_at.desc()).limit(limit).all()
        
        return jsonify({
            'success': True,
            'data': [
                {
                    'id': a.id,
                    'original_filename': a.original_filename,
                    'created_at': a.created_at.isoformat(),
                    'detection_count': a.detection_count,
                    'alert_count': a.alert_count,
                    'total_frames': a.total_frames,
                    'processed_frames': a.processed_frames,
                    'preview_image_url': a.preview_image_url,
                    'emergency_frames_count': len(json.loads(a.emergency_frames)) if a.emergency_frames else 0
                }
                for a in analyses
            ]
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400


@app.route('/api/reanalyze-video/<int:analysis_id>', methods=['POST'])
def reanalyze_video(analysis_id):
    """Re-analyze a previously uploaded video with new or same models"""
    if 'user_id' not in session:
        return jsonify({'success': False, 'error': 'Unauthorized'}), 401
    
    try:
        user_id = session['user_id']
        analysis = AnalysisHistory.query.filter_by(
            id=analysis_id,
            user_id=user_id,
            analysis_type='video'
        ).first()
        
        if not analysis:
            return jsonify({'success': False, 'error': 'Analysis not found'}), 404
        
        # Get original uploaded video file
        upload_dir = Path(app.config['UPLOAD_FOLDER'])
        video_path = upload_dir / analysis.filename
        
        if not video_path.exists():
            return jsonify({'success': False, 'error': 'Original video file not found'}), 404
        
        # Re-process video (models are set from session)
        results = process_video_file(str(video_path))
        
        # Create new analysis record
        new_history = AnalysisHistory(
            user_id=user_id,
            analysis_type='video',
            filename=analysis.filename,
            original_filename=analysis.original_filename,
            detections=json.dumps(results.get('detections', [])),
            alert_count=len(results.get('alerts', [])),
            detection_count=len(results.get('detections', [])),
            models_used=json.dumps(session.get('selected_models', [])),
            processed_video_url=results.get('output_url'),
            preview_image_url=results.get('preview_url'),
            emergency_frames=json.dumps(results.get('emergency_frames', [])),
            total_frames=results.get('total_frames', 0),
            processed_frames=results.get('processed_frames', 0),
            frame_summaries=json.dumps(results.get('frame_summaries', []))
        )
        db.session.add(new_history)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Video re-analyzed successfully',
            'analysis_id': new_history.id,
            'results': results
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500


@app.route('/api/emergency-frames/<int:analysis_id>', methods=['GET'])
def get_emergency_frames(analysis_id):
    """Get emergency frames captured during video analysis"""
    if 'user_id' not in session:
        return jsonify({'success': False, 'error': 'Unauthorized'}), 401
    
    try:
        user_id = session['user_id']
        analysis = AnalysisHistory.query.filter_by(
            id=analysis_id,
            user_id=user_id,
            analysis_type='video'
        ).first()
        
        if not analysis:
            return jsonify({'success': False, 'error': 'Analysis not found'}), 404
        
        emergency_frames = json.loads(analysis.emergency_frames) if analysis.emergency_frames else []
        
        # Build full URLs for emergency frame images
        frames_with_urls = []
        for frame_info in emergency_frames:
            frame_data = frame_info.copy()
            frame_data['image_url'] = url_for('processed_file', filename=f"emergency_frames/{frame_info['filename']}")
            frames_with_urls.append(frame_data)
        
        return jsonify({
            'success': True,
            'data': {
                'analysis_id': analysis_id,
                'total_emergency_frames': len(frames_with_urls),
                'frames': frames_with_urls
            }
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400


# ===================== Async Video Analysis =====================

@app.route('/api/start-video-analysis', methods=['POST'])
def start_video_analysis():
    """Upload a video and queue it for background analysis. Returns a job_id."""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401

    if 'video' not in request.files:
        return jsonify({'success': False, 'message': 'No video file uploaded'}), 400

    file = request.files['video']
    if not file.filename:
        return jsonify({'success': False, 'message': 'No file selected'}), 400

    ext = Path(file.filename).suffix.lower()
    if ext not in {'.mp4', '.avi', '.mov', '.mkv'}:
        return jsonify({'success': False, 'message': 'Unsupported file type'}), 400

    filename = secure_filename(file.filename)
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    save_name = f"{timestamp}_{filename}"
    filepath = UPLOAD_FOLDER / save_name
    file.save(str(filepath))

    selected_models = session.get('selected_models', [])
    user_id = session['user_id']

    job_id = str(uuid.uuid4())
    analysis_jobs[job_id] = {
        'status': 'queued',
        'progress': 0,
        'current_frame': 0,
        'total_frames': 0,
        'alerts': [],
        'high_risk_alerts': [],
        'detection_count': 0,
        'alert_count': 0,
        'results': None,
        'analysis_id': None,
        'error': None,
    }

    thread = threading.Thread(
        target=_process_video_background,
        args=(job_id, str(filepath), user_id, selected_models, file.filename),
        daemon=True,
    )
    thread.start()

    return jsonify({'success': True, 'job_id': job_id})


@app.route('/api/analysis-progress/<job_id>')
def get_analysis_progress(job_id):
    """Poll current progress of a background analysis job."""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401

    job = analysis_jobs.get(job_id)
    if not job:
        return jsonify({'success': False, 'error': 'Job not found'}), 404

    return jsonify({
        'success': True,
        'status': job['status'],
        'progress': job['progress'],
        'current_frame': job['current_frame'],
        'total_frames': job['total_frames'],
        'alerts': job['alerts'][-30:],
        'high_risk_alerts': job['high_risk_alerts'],
        'detection_count': job['detection_count'],
        'alert_count': job['alert_count'],
        'results': job['results'] if job['status'] == 'done' else None,
        'analysis_id': job['analysis_id'],
        'error': job.get('error'),
    })


def _process_video_background(job_id, filepath, user_id, selected_models, original_filename):
    """Process a video file in a background thread with real-time job state updates."""
    with app.app_context():
        job = analysis_jobs.get(job_id)
        if not job:
            return

        job['status'] = 'processing'

        try:
            # Dedicated processor per job β€” avoids conflicts with live camera
            local_proc = VideoProcessor()
            if selected_models:
                local_proc.set_selected_models(selected_models)
            local_proc.reset_session_state()

            cap = cv2.VideoCapture(filepath)
            total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 1
            fps = cap.get(cv2.CAP_PROP_FPS) or 20.0
            width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 640
            height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 480

            job['total_frames'] = total_frames

            input_path = Path(filepath)
            fourcc, ext = get_video_codec()
            processed_name = f"{input_path.stem}_processed{ext}"
            preview_name = f"{input_path.stem}_preview.jpg"
            processed_path = PROCESSED_FOLDER / processed_name
            preview_path = PROCESSED_FOLDER / preview_name

            emergency_dir = PROCESSED_FOLDER / 'emergency_frames'
            emergency_dir.mkdir(parents=True, exist_ok=True)
            det_dir = UPLOAD_FOLDER / 'detections'
            det_dir.mkdir(parents=True, exist_ok=True)

            writer = cv2.VideoWriter(
                str(processed_path),
                fourcc,
                fps,
                (width, height),
            )

            all_detections = []
            all_alerts = []
            frame_summaries = []
            emergency_frames = []
            frame_count = 0
            processed_frames = 0

            while cap.isOpened():
                ret, frame = cap.read()
                if not ret:
                    break

                if frame_count % PROCESSING_PARAMS['frame_skip'] == 0:
                    results = local_proc.process_frame(frame)
                    all_detections.extend(results['detections'])
                    all_alerts.extend(results['alerts'])
                    frame_summaries.append(results['frame_summary'])
                    writer.write(results['annotated_frame'])
                    processed_frames += 1

                    if processed_frames == 1:
                        cv2.imwrite(str(preview_path), results['annotated_frame'])

                    job['detection_count'] = len(all_detections)
                    job['alert_count'] = len(all_alerts)

                    has_weapon = any(d.get('type') == 'weapon' for d in results['detections'])
                    has_violence = any(a.get('type') == 'violence' for a in results['alerts'])
                    has_critical = any(a.get('severity') in {'HIGH', 'CRITICAL'} for a in results['alerts'])

                    # Capture emergency frame for any critical event
                    if has_critical or has_weapon or has_violence:
                        ef_name = f"emrg_{processed_frames}_t{frame_count}.jpg"
                        cv2.imwrite(str(emergency_dir / ef_name), results['annotated_frame'])
                        alert_type = ('CRITICAL' if has_critical else
                                      'WEAPON' if has_weapon else 'VIOLENCE')
                        emergency_frames.append({
                            'filename': ef_name,
                            'frame_number': processed_frames,
                            'timestamp_frame': frame_count,
                            'alert_type': alert_type,
                            'has_weapon': has_weapon,
                            'has_violence': has_violence,
                            'has_anomaly': False,
                        })

                    # Process each alert β€” persist HIGH/CRITICAL ones and push to frontend
                    for alert in results['alerts']:
                        sev = alert.get('severity', 'LOW')
                        alert_entry = {
                            'frame': processed_frames,
                            'type': alert.get('type', 'unknown'),
                            'severity': sev,
                            'message': alert.get('message', ''),
                            'confidence': float(alert.get('confidence', 0.0)),
                        }
                        job['alerts'].append(alert_entry)

                        if sev in ('HIGH', 'CRITICAL'):
                            job['high_risk_alerts'].append(alert_entry)

                            atype = alert.get('type', '')
                            if 'weapon' in atype:
                                det_type = 'weapon'
                            elif 'violence' in atype:
                                det_type = 'violence'
                            else:
                                det_type = 'risk'

                            # Save screenshot + DB record
                            try:
                                uid8 = str(uuid.uuid4())[:8]
                                ts_str = datetime.now().strftime('%Y%m%d_%H%M%S')
                                det_filename = f"det_{det_type}_{ts_str}_{uid8}.jpg"
                                cv2.imwrite(str(det_dir / det_filename), results['annotated_frame'])

                                record = DetectionHistory(
                                    user_id=user_id,
                                    detection_type=det_type,
                                    alert_level=sev,
                                    confidence=float(alert.get('confidence', 0.0)),
                                    image_filename=det_filename,
                                    detection_details=json.dumps({
                                        'alert_type': alert.get('type'),
                                        'message': alert.get('message'),
                                        'frame_number': processed_frames,
                                        'source': 'video_analysis',
                                    }),
                                    detected_at=datetime.now(),
                                    session_date=date.today(),
                                )
                                db.session.add(record)
                                db.session.commit()
                            except Exception:
                                db.session.rollback()

                frame_count += 1
                job['current_frame'] = frame_count
                if total_frames > 0:
                    job['progress'] = min(95, int((frame_count / total_frames) * 95))

            cap.release()
            writer.release()

            output_url = f"/processed/{processed_name}" if processed_frames else None
            preview_url = f"/processed/{preview_name}" if processed_frames else None

            risk_counts = {}
            for s in frame_summaries:
                risk_counts[s['pose_risk']] = risk_counts.get(s['pose_risk'], 0) + 1

            # Strip per-frame detections/alerts from summaries β€” they're captured in
            # all_detections / all_alerts and would bloat the JSON response significantly.
            slim_summaries = [
                {k: v for k, v in s.items() if k not in ('detections', 'alerts')}
                for s in frame_summaries
            ]

            results_data = {
                'total_frames': frame_count,
                'processed_frames': processed_frames,
                'detections': all_detections,
                'alerts': all_alerts,
                'frame_summaries': slim_summaries,
                'output_url': output_url,
                'output_mime': 'video/mp4',
                'preview_url': preview_url,
                'emergency_frames': emergency_frames,
                'summary': {
                    'total_detections': len(all_detections),
                    'total_alerts': len(all_alerts),
                    'emergency_frames_count': len(emergency_frames),
                    'weapon_alert_frames': sum(1 for f in frame_summaries if f['weapon_count'] > 0),
                    'unsafe_pose_frames': sum(1 for f in frame_summaries if f['pose_risk'] in {'LOW_RISK', 'HIGH_RISK'}),
                    'critical_frames': sum(1 for f in frame_summaries if f['alert_state'] == 'CRITICAL'),
                    'pose_risk_counts': risk_counts,
                },
            }

            try:
                history = AnalysisHistory(
                    user_id=user_id,
                    analysis_type='video',
                    filename=Path(filepath).name,
                    original_filename=original_filename,
                    detections=json.dumps(all_detections),
                    alert_count=len(all_alerts),
                    detection_count=len(all_detections),
                    models_used=json.dumps(selected_models),
                    processed_video_url=output_url,
                    preview_image_url=preview_url,
                    emergency_frames=json.dumps(emergency_frames),
                    total_frames=frame_count,
                    processed_frames=processed_frames,
                    frame_summaries=json.dumps(slim_summaries),
                )
                db.session.add(history)
                db.session.commit()
                job['analysis_id'] = history.id
            except Exception:
                db.session.rollback()

            # Ensure all values in results_data are JSON-safe (converts any residual numpy types)
            try:
                json.dumps(results_data)
            except TypeError:
                results_data = json.loads(json.dumps(results_data, default=lambda o: float(o) if hasattr(o, '__float__') else str(o)))

            job['results'] = results_data
            job['status'] = 'done'
            job['progress'] = 100

        except Exception as e:
            job['status'] = 'error'
            job['error'] = str(e)
            try:
                db.session.rollback()
            except Exception:
                pass


# ===================== Initialize Database =====================
def _migrate_db():
    """Add any missing columns to existing tables (safe for repeated runs)."""
    from sqlalchemy import text
    migrations = [
        "ALTER TABLE analysis_history ADD COLUMN original_filename VARCHAR(200)",
        "ALTER TABLE analysis_history ADD COLUMN processed_video_url VARCHAR(500)",
        "ALTER TABLE analysis_history ADD COLUMN preview_image_url VARCHAR(500)",
        "ALTER TABLE analysis_history ADD COLUMN emergency_frames TEXT",
        "ALTER TABLE analysis_history ADD COLUMN total_frames INTEGER DEFAULT 0",
        "ALTER TABLE analysis_history ADD COLUMN processed_frames INTEGER DEFAULT 0",
        "ALTER TABLE analysis_history ADD COLUMN frame_summaries TEXT",
    ]
    for stmt in migrations:
        try:
            db.session.execute(text(stmt))
            db.session.commit()
        except Exception:
            db.session.rollback()


with app.app_context():
    db.create_all()
    _migrate_db()


if __name__ == '__main__':
    import os
    
    # Print NETRA ASCII banner with styling
    banner = """
    
    ╔══════════════════════════════════════════════════════════════════╗
    β•‘                                                                  β•‘
    β•‘   β–ˆβ–ˆβ–ˆβ•—   β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—                     β•‘
    β•‘   β–ˆβ–ˆβ–ˆβ–ˆβ•—  β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β•β•β•β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—                    β•‘
    β•‘   β–ˆβ–ˆβ•”β–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—     β–ˆβ–ˆβ•‘   β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘                    β•‘
    β•‘   β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β•     β–ˆβ–ˆβ•‘   β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘                    β•‘
    β•‘   β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—   β–ˆβ–ˆβ•‘   β–ˆβ–ˆβ•‘  β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘  β–ˆβ–ˆβ•‘                    β•‘
    β•‘   β•šβ•β•  β•šβ•β•β•β•β•šβ•β•β•β•β•β•β•   β•šβ•β•   β•šβ•β•  β•šβ•β•β•šβ•β•  β•šβ•β•                    β•‘
    β•‘                                                                  β•‘
    β•‘         AI-Powered Video Surveillance & Analysis System          β•‘
    β•‘                                                                  β•‘
    β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
    """
    print(banner)
    print("\n" + "═"*70)
    print(f"  πŸ“Š Available Models: {model_manager.list_models()}")
    print("═"*70)
    
    # Detect environment
    is_hf_spaces = os.getenv('SYSTEM') == 'spaces' or os.path.exists('/.dockerenv')
    
    if is_hf_spaces:
        # Hugging Face Spaces environment
        host = '0.0.0.0'
        port = 7860
        debug = False
        use_reloader = False
        print(f"\n  πŸš€ Running on Hugging Face Spaces")
    else:
        # Local development
        host = '0.0.0.0'
        port = int(os.getenv('PORT', 5001))
        debug = True
        use_reloader = True
        print(f"\n  πŸ’» Running in Local Development Mode")
    
    print(f"\n  🌐 Access Application:")
    print(f"     β†’ http://localhost:{port}")
    print(f"     β†’ http://127.0.0.1:{port}")
    print(f"\n  βš™οΈ  Configuration:")
    print(f"     β†’ Debug Mode: {'ON' if debug else 'OFF'}")
    print(f"     β†’ Host: {host} (all interfaces)")
    print(f"     β†’ Port: {port}")
    print(f"     β†’ Environment: {'Hugging Face Spaces' if is_hf_spaces else 'Local Development'}")
    print(f"\n  πŸ“ Project Root: {PROJECT_ROOT}")
    print("\n" + "═"*70)
    print("\n  βœ… Server is RUNNING")
    print("  Press CTRL+C to stop the server\n")
    print("═"*70 + "\n")
    
    app.run(
        debug=debug, 
        host=host, 
        port=port, 
        threaded=True,
        use_reloader=use_reloader
    )