File size: 74,947 Bytes
823a8d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca70edf
 
 
 
6e0503e
 
 
ca70edf
6e0503e
ca70edf
6e0503e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
823a8d9
ca70edf
a356929
 
 
823a8d9
ca70edf
a356929
ca70edf
 
823a8d9
a356929
 
 
 
 
 
823a8d9
a356929
6e0503e
823a8d9
6e0503e
 
 
823a8d9
6e0503e
 
823a8d9
 
6e0503e
 
 
 
823a8d9
6e0503e
 
 
 
823a8d9
6e0503e
823a8d9
f9fc492
 
ca70edf
f9fc492
823a8d9
f9fc492
823a8d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9fc492
823a8d9
f9fc492
823a8d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9fc492
823a8d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9fc492
823a8d9
 
 
f9fc492
 
 
 
 
 
 
 
823a8d9
 
 
 
f9fc492
 
 
 
 
823a8d9
 
f9fc492
 
 
 
 
 
 
823a8d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e0503e
 
823a8d9
6e0503e
823a8d9
 
 
 
6e0503e
823a8d9
 
 
 
6e0503e
823a8d9
 
 
 
6e0503e
823a8d9
 
 
 
 
 
 
 
 
6e0503e
823a8d9
 
 
 
 
 
6e0503e
823a8d9
 
 
 
 
6e0503e
823a8d9
 
 
 
 
 
d49d951
823a8d9
 
 
 
 
 
d49d951
823a8d9
d49d951
823a8d9
 
 
 
 
6e0503e
 
 
823a8d9
ca70edf
6e0503e
823a8d9
 
 
 
 
 
 
 
 
 
 
6e0503e
823a8d9
6e0503e
823a8d9
 
 
 
 
 
6e0503e
823a8d9
 
 
 
 
 
6e0503e
823a8d9
 
 
 
6e0503e
823a8d9
 
 
ca70edf
6e0503e
 
 
ca70edf
823a8d9
 
6e0503e
823a8d9
6e0503e
 
823a8d9
6e0503e
 
 
a356929
 
6e0503e
a356929
6e0503e
823a8d9
 
 
 
 
 
 
 
 
6e0503e
823a8d9
 
 
 
f9fc492
823a8d9
 
f9fc492
 
 
 
823a8d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca70edf
823a8d9
 
ca70edf
 
823a8d9
 
 
 
 
 
ca70edf
823a8d9
ca70edf
823a8d9
 
ca70edf
823a8d9
 
 
 
 
ca70edf
823a8d9
ca70edf
823a8d9
 
ca70edf
 
 
 
 
823a8d9
 
 
 
 
 
 
 
 
ca70edf
823a8d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
711d74c
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
import os
import pickle
from flask import Flask, render_template, request, redirect, url_for, session, jsonify, send_file, flash
from flask_pymongo import PyMongo
from flask_session import Session
from bson.objectid import ObjectId
from werkzeug.security import generate_password_hash, check_password_hash
import pandas as pd
from datetime import datetime, timedelta
import json
import io
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
import bcrypt
import pymongo
from pymongo.errors import ServerSelectionTimeoutError, ConnectionFailure
import ssl
import certifi
import logging

# Set up comprehensive logging
try:
    from logging_config import setup_logging, log_request_info
    logger = setup_logging()
    print("Comprehensive logging configured successfully")
except Exception as e:
    # Fallback to basic logging
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)
    logger.warning(f"Failed to configure comprehensive logging: {e}")

app = Flask(__name__)

# CRITICAL: Use a STRONG, FIXED secret key for session signing
# This is ESSENTIAL for session persistence on Hugging Face Spaces
# NEVER use a default or weak key - it will cause session loss
app.secret_key = os.environ.get("SECRET_KEY") or "a_very_strong_static_key_here_change_this_before_production_DO_NOT_USE_DEFAULT"

# Session configuration for production - Enhanced for Hugging Face Spaces
# 
# CRITICAL Hugging Face Spaces Issue:
# 
# Sessions don't persist because:
# 1. Spaces are serverless containers
# 2. Default Flask SESSION_TYPE='null' only keeps session in memory per request
# 3. After redirect, session data is gone -> app thinks user is not logged in
# 
# Solution: Use filesystem-based sessions so session data persists across requests
# 
# Configuration details:
# - SESSION_TYPE='filesystem' - Store sessions in filesystem instead of memory
# - SESSION_FILE_DIR - Directory for session files (uses /tmp for HF Spaces)
# - SESSION_PERMANENT=True - Make sessions permanent
# - SESSION_USE_SIGNER=True - Add cryptographic signing for security
# 
# FIX FOR WERKZEUG COMPATIBILITY ISSUE:
# Added SESSION_SERIALIZER to use custom JSON serializer instead of pickle
# This resolves the "cannot use a string pattern on a bytes-like object" error

# MODEL VERSION WARNINGS:
# The warnings about sklearn model versions are just warnings and won't break functionality.
# The models should still work correctly even with the version mismatch.
# For production, retrain models with the current scikit-learn version (1.3.2).

from datetime import timedelta

# Determine session directory - use /tmp for HF Spaces or local tmp
session_dir = '/tmp/flask_session' if os.path.exists('/tmp') else './flask_session'
try:
    os.makedirs(session_dir, exist_ok=True)
except:
    session_dir = None  # Will use default temp directory

# Custom JSON serializer for Flask-Session to avoid pickle/Werkzeug issues
class JSONSerializer:
    def dumps(self, obj):
        return json.dumps(obj)
    
    def loads(self, data):
        if isinstance(data, bytes):
            data = data.decode('utf-8')
        return json.loads(data)

# CRITICAL: Proper session configuration for Hugging Face Spaces
# Use SameSite=None and Secure=True so cookies are sent when the app is embedded
# in an iframe or used behind proxies (like Hugging Face Spaces). Optionally
# set SESSION_COOKIE_DOMAIN via env if you need to scope cookies to a domain.
app.config.update(
    SECRET_KEY=os.environ.get("SECRET_KEY") or "a_very_strong_static_key_here_change_this_before_production_DO_NOT_USE_DEFAULT",

    # CRITICAL: These settings are required for Hugging Face Spaces
    SESSION_COOKIE_SECURE=True,  # MUST be True for HTTPS (HF Spaces uses HTTPS)
    SESSION_COOKIE_HTTPONLY=True,
    # IMPORTANT: use 'None' to allow cross-site cookies (iframe). Browsers require
    # SameSite=None together with Secure=True for cross-site cookie delivery.
    SESSION_COOKIE_SAMESITE='None',
    # Optional domain for the session cookie (set via env). Useful in some deployments.
    SESSION_COOKIE_DOMAIN=os.environ.get('SESSION_COOKIE_DOMAIN') or None,

    PERMANENT_SESSION_LIFETIME=timedelta(hours=1),

    # Filesystem session storage for Hugging Face Spaces
    SESSION_TYPE='filesystem',
    SESSION_FILE_DIR=session_dir,
    SESSION_FILE_THRESHOLD=500,
    SESSION_FILE_MODE=0o600,
    SESSION_PERMANENT=True,
    SESSION_USE_SIGNER=True,  # Adds extra security
    SESSION_SERIALIZER=JSONSerializer()  # FIX: Use JSON instead of pickle
)

# Initialize session
Session(app)

# Ensure session directory exists
try:
    session_dir = app.config.get('SESSION_FILE_DIR')
    if session_dir:
        os.makedirs(session_dir, exist_ok=True)
        print(f"Session directory ensured: {session_dir}")
except Exception as e:
    print(f"Warning: Could not create session directory: {e}")

# FIX: Add ProxyFix for Hugging Face Spaces
from werkzeug.middleware.proxy_fix import ProxyFix

app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)

# Optional .env support for local development
try:
    from dotenv import load_dotenv
    load_dotenv()
    print("Loaded .env (if present)")
except Exception:
    pass

# Import debug routes
try:
    from debug_routes import add_debug_routes
    add_debug_routes(app)
    print("Debug routes added successfully")
except Exception as e:
    print(f"Failed to add debug routes: {e}")

# MongoDB Configuration (keep your existing code)
def create_mongo_client():
    """Create a secure MongoDB client for deployment."""
    uri = os.environ.get('MONGODB_URI')

    if not uri:
        print("No MONGODB_URI provided - running in limited offline mode.")
        return None

    try:
        client_options = [
            {
                'tls': True,
                'serverSelectionTimeoutMS': 5000,
                'connectTimeoutMS': 5000,
                'socketTimeoutMS': 5000,
                'tlsCAFile': certifi.where()
            },
            {
                'tls': True,
                'tlsAllowInvalidCertificates': True,
                'tlsAllowInvalidHostnames': True,
                'serverSelectionTimeoutMS': 5000,
                'connectTimeoutMS': 5000,
                'socketTimeoutMS': 5000
            },
            {
                'tls': True,
                'ssl': True,
                'serverSelectionTimeoutMS': 5000,
                'connectTimeoutMS': 5000,
                'socketTimeoutMS': 5000
            }
        ]
        
        client = None
        last_error = None
        
        for options in client_options:
            try:
                client = pymongo.MongoClient(uri, **options)
                client.admin.command('ping')
                print("MongoDB connected successfully ✅")
                return client
            except Exception as e:
                last_error = e
                logger.warning(f"MongoDB connection attempt failed with options {options}: {e}")
                continue
        
        if last_error:
            raise last_error
            
    except (ServerSelectionTimeoutError, ConnectionFailure, Exception) as e:
        print("MongoDB connection failed ❌", e)
        logger.error(f"MongoDB connection failed: {e}")
        return None

# Create MongoDB client
mongo_client = create_mongo_client()

if mongo_client:
    db = mongo_client.get_database(os.environ.get('MONGODB_DB', 'healthcare_db'))

    class MongoWrapper:
        def __init__(self, database, client):
            self.db = database
            self.cx = client

    mongo = MongoWrapper(db, mongo_client)
    print("MongoDB connection established successfully!")
else:
    class _NullCollection:
        def find_one(self, *a, **k):
            return None
        def find(self, *a, **k):
            return []
        def insert_one(self, *a, **k):
            raise RuntimeError("Database not available in this environment")
        def update_one(self, *a, **k):
            raise RuntimeError("Database not available in this environment")
        def delete_one(self, *a, **k):
            raise RuntimeError("Database not available in this environment")
        def count_documents(self, *a, **k):
            return 0
        def aggregate(self, *a, **k):
            return []

    class _NullDB:
        def __getattr__(self, name):
            return _NullCollection()

    class _NullMongoWrapper:
        def __init__(self):
            self.db = _NullDB()
            self.cx = None

    mongo = _NullMongoWrapper()
    print("Failed to establish MongoDB connection. Application will run in limited mode.")

# Get the working directory
working_dir = os.path.dirname(os.path.abspath(__file__))

# Load the saved models
diabetes_model = pickle.load(open(f'{working_dir}/saved models/diabetes_model.sav', 'rb'))
heart_disease_model = pickle.load(open(f'{working_dir}/saved models/heart_disease_model.sav', 'rb'))
parkinsons_model = pickle.load(open(f'{working_dir}/saved models/parkinsons_model.sav', 'rb'))

# FIX: Enhanced session debugging
@app.before_request
def before_request():
    if request.endpoint and not request.endpoint.startswith('static'):
        logger.info(f"=== BEFORE REQUEST ===")
        logger.info(f"Endpoint: {request.endpoint}")
        logger.info(f"Method: {request.method}")
        logger.info(f"Session ID: {session.get('_id', 'No session ID')}")
        logger.info(f"Session Data: {dict(session)}")
        logger.info(f"User ID in session: {session.get('user_id')}")
        logger.info(f"Cookies: {request.cookies}")
        logger.info(f"======================")

@app.after_request
def after_request(response):
    if request.endpoint and not request.endpoint.startswith('static'):
        logger.info(f"=== AFTER REQUEST ===")
        logger.info(f"Status: {response.status_code}")
        logger.info(f"Session modified: {session.modified}")
        logger.info(f"Session Data: {dict(session)}")
        logger.info(f"=====================")
    return response

# FIX: Add session persistence middleware
@app.before_request
def make_session_permanent():
    session.permanent = True
    # Refresh session on each request to keep it alive
    session.modified = True

# Routes for authentication
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if mongo is None:
        flash('Database connection error. Please contact administrator.', 'error')
        return redirect(url_for('index'))
        
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        phone = request.form['phone']
        password = request.form['password']
        confirm_password = request.form['confirm_password']
        role = request.form.get('role', 'user')  # Default to user
        specialization = request.form.get('specialization', '')  # For doctors
        
        # Validate input
        if not name or not email or not phone or not password:
            flash('All fields are required!', 'error')
            return redirect(url_for('register'))
        
        # Check if passwords match
        if password != confirm_password:
            flash('Passwords do not match!', 'error')
            return redirect(url_for('register'))
            
        # Check password strength
        if len(password) < 6:
            flash('Password must be at least 6 characters long!', 'error')
            return redirect(url_for('register'))
        
        # Check if user already exists
        try:
            existing_user = mongo.db.users.find_one({'email': email})
            if existing_user:
                flash('Email already registered!', 'error')
                return redirect(url_for('register'))
        except Exception as e:
            flash('Database error. Please try again later.', 'error')
            return redirect(url_for('register'))
        
        # Hash the password
        try:
            hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
        except Exception as e:
            flash('Error processing password. Please try again.', 'error')
            return redirect(url_for('register'))
        
        # Insert new user into database
        user_data = {
            'name': name,
            'email': email,
            'phone': phone,
            'password': hashed_password,
            'role': role,  # user or doctor
            'specialization': specialization if role == 'doctor' else '',
            'created_at': datetime.now()
        }
        
        try:
            result = mongo.db.users.insert_one(user_data)
            if result.acknowledged:
                flash('Registration successful! Please log in.', 'success')
                return redirect(url_for('login'))
            else:
                flash('Registration failed. Please try again later.', 'error')
                return redirect(url_for('register'))
        except Exception as e:
            flash(f'Registration failed: {str(e)}', 'error')
            return redirect(url_for('register'))

    
    return render_template('auth/register.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    logger.info(f"Login request method: {request.method}")
    logger.info(f"Session before login processing: {dict(session)}")
    logger.info(f"Request headers: {dict(request.headers)}")
    
    # CRITICAL: Do not clear session on GET request to /login
    # Only clear session on explicit logout
    
    if mongo is None:
        logger.error("Database connection is None")
        flash('Database connection error. Please contact administrator.', 'error')
        return redirect(url_for('index'))
        
    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        
        logger.info(f"Login attempt - Email: {email}")
        logger.info(f"Form data: email={email}, password={'[REDACTED]' if password else 'None'}")
        
        # Validate input
        if not email or not password:
            logger.warning("Email and password are required")
            flash('Email and password are required!', 'error')
            return redirect(url_for('login'))
        
        try:
            # Find user in database
            logger.info("Searching for user in database...")
            user = mongo.db.users.find_one({'email': email})
            logger.info(f"User found: {user is not None}")
            
            if user and bcrypt.checkpw(password.encode('utf-8'), user['password']):
                logger.info("Password verified successfully")
                # Set session variables
                session['user_id'] = str(user['_id'])
                session['username'] = user['name']
                session['user_email'] = user['email']
                session['user_role'] = user['role']
                session.permanent = True  # Make session permanent
                
                logger.info(f"Session after login: {dict(session)}")
                
                # CRITICAL: Ensure session is properly saved before redirect
                # Force session to be saved
                session.modified = True
                
                # CRITICAL: Set response headers for proper cookie handling
                # Redirect based on role
                if user['role'] == 'admin':
                    redirect_url = url_for('admin_dashboard')
                elif user['role'] == 'doctor':
                    # send doctors to their appointments view
                    redirect_url = url_for('doctor_appointments')
                else:
                    redirect_url = url_for('user_dashboard')
                
                logger.info(f"Redirecting to: {redirect_url}")
                # Session has been marked modified and permanent above. Return a
                # normal redirect and let Flask-Session set the cookie header.
                response = redirect(redirect_url)
                logger.info(f"Response headers (pre-send): {dict(response.headers)}")
                return response
            else:
                logger.warning("Invalid credentials")
                flash('Invalid email or password!', 'error')
                return redirect(url_for('login'))
        except Exception as e:
            logger.error(f"Login error: {e}", exc_info=True)
            flash('Login failed. Please try again later.', 'error')
            return redirect(url_for('login'))
    
    logger.info(f"Session on GET request: {dict(session)}")
    return render_template('auth/login.html')

@app.route('/logout')
def logout():
    logger.info("=== LOGOUT ===")
    session.clear()
    flash('You have been logged out successfully!', 'success')
    response = redirect(url_for('index'))
    # Clear session cookie
    response.set_cookie('session', '', expires=0)
    return response

@app.route('/forgot-password', methods=['GET', 'POST'])
def forgot_password():
    if mongo is None:
        flash('Database connection error. Please contact administrator.', 'error')
        return redirect(url_for('index'))
        
    if request.method == 'POST':
        email = request.form['email']
        try:
            user = mongo.db.users.find_one({'email': email})
            if not user:
                flash('Email not found!', 'error')
                return redirect(url_for('forgot_password'))

            # Generate a 6-digit OTP and store it with expiry (10 minutes)
            import random
            otp = '{:06d}'.format(random.randint(0, 999999))
            expiry = datetime.now() + timedelta(minutes=10)

            # Store OTP in a password_resets collection
            mongo.db.password_resets.update_one(
                {'email': email},
                {'$set': {'otp': otp, 'expiry': expiry}},
                upsert=True
            )

            # Send OTP via Gmail SMTP using EMAIL_USER/EMAIL_PASSWORD environment variables.
            # We use a small helper in email_utils which wraps SMTP_SSL for secure sending.
            msg_body = f"Your OTP for password reset is: {otp}. It is valid for 10 minutes."
            try:
                from email_utils import send_email

                send_email(email, 'Password Reset OTP - Multiple Disease Prediction', msg_body)
            except Exception as e:
                print(f"Failed to send OTP email: {e}")
                flash('Failed to send OTP email. Please contact administrator.', 'error')
                return redirect(url_for('forgot_password'))

            flash('An OTP has been sent to your email. Please enter it to reset your password.', 'success')
            return redirect(url_for('verify_otp'))
        except Exception as e:
            flash('Database error. Please try again later.', 'error')
    
    return render_template('auth/forgot_password.html')


@app.route('/verify-otp', methods=['GET', 'POST'])
def verify_otp():
    if request.method == 'POST':
        email = request.form['email']
        otp = request.form['otp']
        new_password = request.form['new_password']

        # Validate input
        if not email or not otp or not new_password:
            flash('All fields are required!', 'error')
            return redirect(url_for('verify_otp'))

        record = mongo.db.password_resets.find_one({'email': email})
        if not record:
            flash('No OTP request found for this email.', 'error')
            return redirect(url_for('verify_otp'))

        if datetime.now() > record['expiry']:
            flash('OTP has expired. Please request a new one.', 'error')
            return redirect(url_for('forgot_password'))

        if record['otp'] != otp:
            flash('Invalid OTP. Please try again.', 'error')
            return redirect(url_for('verify_otp'))
            
        # Check password strength
        if len(new_password) < 6:
            flash('Password must be at least 6 characters long!', 'error')
            return redirect(url_for('verify_otp'))

        # Update password for user
        try:
            hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt())
        except Exception as e:
            flash('Error processing password. Please try again.', 'error')
            return redirect(url_for('verify_otp'))
            
        try:
            mongo.db.users.update_one({'email': email}, {'$set': {'password': hashed_password}})
        except Exception as e:
            flash('Failed to update password. Please try again later.', 'error')
            return redirect(url_for('verify_otp'))

        # Remove the OTP record
        try:
            mongo.db.password_resets.delete_one({'email': email})
        except Exception as e:
            # Log the error but don't fail the operation
            print(f'Failed to delete OTP record: {e}')

        flash('Password reset successful. Please log in with your new password.', 'success')
        return redirect(url_for('login'))

    return render_template('auth/verify_otp.html')

# Profile Management
@app.route('/profile', methods=['GET', 'POST'])
def profile():
    if mongo is None:
        flash('Database connection error. Please contact administrator.', 'error')
        return redirect(url_for('index'))
        
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    try:
        user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
    except Exception as e:
        flash('Database error. Please try again later.', 'error')
        return redirect(url_for('user_dashboard'))
    
    if not user:
        flash('User not found!', 'error')
        return redirect(url_for('login'))
    
    if request.method == 'POST':
        # Get form data
        name = request.form['name']
        email = request.form['email']
        phone = request.form['phone']
        current_password = request.form['current_password']
        new_password = request.form['new_password']
        confirm_password = request.form['confirm_password']
        
        # Validate input
        if not name or not email or not phone or not current_password:
            flash('All required fields must be filled!', 'error')
            return redirect(url_for('profile'))
        
        # Verify current password
        if not bcrypt.checkpw(current_password.encode('utf-8'), user['password']):
            flash('Current password is incorrect!', 'error')
            return redirect(url_for('profile'))
        
        # Check if email is already taken by another user
        try:
            if email != user['email']:
                existing_user = mongo.db.users.find_one({'email': email, '_id': {'$ne': ObjectId(session['user_id'])}})
                if existing_user:
                    flash('Email is already taken by another user!', 'error')
                    return redirect(url_for('profile'))
        except Exception as e:
            flash('Database error. Please try again later.', 'error')
            return redirect(url_for('profile'))
        
        # Prepare update data
        update_data = {
            'name': name,
            'email': email,
            'phone': phone
        }
        
        # Update password if provided
        if new_password:
            if new_password != confirm_password:
                flash('New passwords do not match!', 'error')
                return redirect(url_for('profile'))
            
            # Check password strength
            if len(new_password) < 6:
                flash('New password must be at least 6 characters long!', 'error')
                return redirect(url_for('profile'))
            
            # Hash new password
            try:
                hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt())
                update_data['password'] = hashed_password
            except Exception as e:
                flash('Error processing password. Please try again.', 'error')
                return redirect(url_for('profile'))
        
        # Update user in database
        try:
            result = mongo.db.users.update_one(
                {'_id': ObjectId(session['user_id'])},
                {'$set': update_data}
            )
            
            if result.modified_count > 0:
                # Update session data
                session['username'] = name
                session['user_email'] = email
                
                flash('Profile updated successfully!', 'success')
                return redirect(url_for('profile'))
            else:
                flash('No changes were made to your profile.', 'info')
                return redirect(url_for('profile'))
        except Exception as e:
            flash('Profile update failed. Please try again later.', 'error')
            return redirect(url_for('profile'))
    
    # Get prediction counts for statistics
    try:
        prediction_count = mongo.db.patient_history.count_documents({'user_id': session['user_id']})
        heart_count = mongo.db.patient_history.count_documents({'user_id': session['user_id'], 'disease_type': 'Heart Disease'})
        diabetes_count = mongo.db.patient_history.count_documents({'user_id': session['user_id'], 'disease_type': 'Diabetes'})
        parkinsons_count = mongo.db.patient_history.count_documents({'user_id': session['user_id'], 'disease_type': "Parkinson's"})
    except Exception as e:
        flash('Database error. Please try again later.', 'error')
        prediction_count = 0
        heart_count = 0
        diabetes_count = 0
        parkinsons_count = 0
    
    return render_template('user/profile.html', 
                         user=user,
                         prediction_count=prediction_count,
                         heart_count=heart_count,
                         diabetes_count=diabetes_count,
                         parkinsons_count=parkinsons_count)

# User Appointments
@app.route('/user/appointments', methods=['GET', 'POST'])
def user_appointments():
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    if request.method == 'POST':
        # Get form data
        disease_type = request.form['disease_type']
        date_str = request.form['date']
        time = request.form['time']
        notes = request.form['notes']
        
        # Get checkbox details (symptoms, purpose of visit)
        details_selected = request.form.getlist('details')
        
        # Validate that date is in the future
        appointment_datetime = datetime.strptime(f"{date_str} {time}", '%Y-%m-%d %H:%M')
        if appointment_datetime <= datetime.now():
            flash('Appointment date and time must be in the future!', 'error')
            return redirect(url_for('user_appointments'))
        
        # Check for overlapping appointments for the doctor
        # Since appointments are unassigned at booking, we check only for existing identical patient bookings
        existing_appointment = mongo.db.appointments.find_one({
            'user_id': session['user_id'],
            'date': datetime.strptime(date_str, '%Y-%m-%d'),
            'time': time,
            'status': {'$in': ['pending', 'confirmed']}
        })
        
        if existing_appointment:
            flash('This time slot is already booked. Please choose another time.', 'error')
            return redirect(url_for('user_appointments'))
        
        # Create appointment data
        appointment_data = {
            'user_id': session['user_id'],
            'disease_type': disease_type,
            'details_selected': details_selected,
            'date': datetime.strptime(date_str, '%Y-%m-%d'),  # Convert to datetime object
            'time': time,
            'notes': notes,
            'status': 'pending',
            # doctor will be set when a doctor confirms the appointment
            'doctor': '',
            'doctor_id': '',
            'created_at': datetime.now()
        }
        
        # Insert appointment into database
        mongo.db.appointments.insert_one(appointment_data)
        
        flash('Appointment booked successfully! Please wait for confirmation.', 'success')
        return redirect(url_for('user_appointments'))
    
    # Get upcoming appointments for the user
    upcoming_appointments = list(mongo.db.appointments.find(
        {'user_id': session['user_id'], 'date': {'$gte': datetime.now()}}
    ).sort('date', 1))
    
    # Get user's prediction history to suggest disease types
    prediction_history = list(mongo.db.patient_history.find(
        {'user_id': session['user_id']}
    ).sort('date', -1).limit(10))
    
    return render_template('user/appointments.html', 
                         upcoming_appointments=upcoming_appointments,
                         prediction_history=prediction_history)

# Cancel Appointment
@app.route('/user/cancel-appointment/<appointment_id>')
def cancel_appointment(appointment_id):
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    # Update appointment status to cancelled
    result = mongo.db.appointments.update_one(
        {'_id': ObjectId(appointment_id), 'user_id': session['user_id']},
        {'$set': {'status': 'cancelled'}}
    )
    
    if result.modified_count > 0:
        flash('Appointment cancelled successfully!', 'success')
    else:
        flash('Appointment not found or you do not have permission to cancel it!', 'error')
    
    return redirect(url_for('user_appointments'))

# Admin Appointments
@app.route('/admin/appointments')
def admin_appointments():
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    # Check if user is admin
    user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
    if user['role'] != 'admin':
        flash('Access denied!', 'error')
        return redirect(url_for('user_dashboard'))
    
    # Get pending appointments
    pending_appointments = list(mongo.db.appointments.find(
        {'status': 'pending'}
    ).sort('date', 1))
    
    # Add patient information to pending appointments
    for appointment in pending_appointments:
        patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])})
        appointment['patient_name'] = patient['name'] if patient else 'Unknown'
        appointment['patient_email'] = patient['email'] if patient else 'Unknown'
    
    # Get confirmed appointments
    confirmed_appointments = list(mongo.db.appointments.find(
        {'status': 'confirmed'}
    ).sort([('date', 1), ('time', 1)]))
    
    # Add patient information to confirmed appointments
    for appointment in confirmed_appointments:
        patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])})
        appointment['patient_name'] = patient['name'] if patient else 'Unknown'
        appointment['patient_email'] = patient['email'] if patient else 'Unknown'
    
    return render_template('admin/appointments.html', 
                         pending_appointments=pending_appointments,
                         confirmed_appointments=confirmed_appointments)

# Confirm Appointment
@app.route('/admin/appointments/<appointment_id>/confirm', methods=['POST'])
def confirm_appointment(appointment_id):
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    # Check if user is admin
    user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
    if user['role'] != 'admin':
        flash('Access denied!', 'error')
        return redirect(url_for('user_dashboard'))
    
    # Update appointment status to confirmed
    result = mongo.db.appointments.update_one(
        {'_id': ObjectId(appointment_id)},
        {'$set': {'status': 'confirmed'}}
    )
    
    if result.modified_count > 0:
        flash('Appointment confirmed successfully!', 'success')
    else:
        flash('Appointment not found!', 'error')
    
    return redirect(url_for('admin_appointments'))

# Reject Appointment
@app.route('/admin/appointments/<appointment_id>/reject', methods=['POST'])
def reject_appointment(appointment_id):
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    # Check if user is admin
    user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
    if user['role'] != 'admin':
        flash('Access denied!', 'error')
        return redirect(url_for('user_dashboard'))
    
    # Update appointment status to cancelled
    result = mongo.db.appointments.update_one(
        {'_id': ObjectId(appointment_id)},
        {'$set': {'status': 'cancelled'}}
    )
    
    if result.modified_count > 0:
        flash('Appointment rejected successfully!', 'success')
    else:
        flash('Appointment not found!', 'error')
    
    return redirect(url_for('admin_appointments'))

# User dashboard - KEEPING THE BETTER IMPLEMENTATION
@app.route('/user/dashboard')
def user_dashboard():
    logger.info(f"=== DASHBOARD REQUEST ===")
    logger.info(f"Session data: {dict(session)}")
    logger.info(f"User ID in session: {session.get('user_id')}")
    
    # Check if user is logged in
    if 'user_id' not in session:
        logger.warning("No user_id in session, redirecting to login")
        flash('Please log in to access the dashboard!', 'error')
        return redirect(url_for('login'))
    
    # Verify user exists in database
    try:
        user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
        logger.info(f"User from database: {user is not None}")
    except Exception as e:
        logger.error(f"Error fetching user from database: {e}", exc_info=True)
        user = None
    
    if not user:
        logger.warning("User not found in database, clearing session and redirecting")
        session.clear()
        flash('User not found. Please log in again.', 'error')
        return redirect(url_for('login'))
    
    # CRITICAL: Ensure session stays alive
    session.permanent = True
    session.modified = True
    
    # Get recent predictions
    try:
        recent_predictions = list(mongo.db.patient_history.find(
            {'user_id': session['user_id']}
        ).sort('date', -1).limit(5))
        logger.info(f"Found {len(recent_predictions)} recent predictions")
    except Exception as e:
        logger.error(f"Error fetching recent predictions: {e}", exc_info=True)
        recent_predictions = []
    
    logger.info(f"Rendering dashboard for user: {user['name']}")
    return render_template('user/dashboard.html', 
                         user=user, 
                         recent_predictions=recent_predictions)

@app.route('/user/dashboard/data')
def user_dashboard_data():
    """Return JSON with data for Plotly charts for the logged-in user."""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401

    # 1) Prediction results distribution
    prediction_pipeline = [
        {'$match': {'user_id': session['user_id']}},
        {'$group': {'_id': '$result', 'count': {'$sum': 1}}}
    ]
    prediction_counts = {'positive': 0, 'negative': 0}
    for doc in mongo.db.patient_history.aggregate(prediction_pipeline):
        result = doc.get('_id', '').lower()
        if 'likely' in result:
            prediction_counts['positive'] += doc.get('count', 0)
        else:
            prediction_counts['negative'] += doc.get('count', 0)

    # 2) Predictions over time (last 30 days)
    from datetime import timedelta
    today = datetime.now()
    start_date = today - timedelta(days=29)
    
    trend_pipeline = [
        {'$match': {'user_id': session['user_id'], 'date': {'$gte': start_date}}},
        {'$group': {'_id': {'$dateToString': {'format':'%Y-%m-%d', 'date':'$date'}}, 'count': {'$sum':1}}},
        {'$sort': {'_id': 1}}
    ]
    trend_docs = list(mongo.db.patient_history.aggregate(trend_pipeline))
    # prepare arrays for the last 30 days
    dates = []
    counts = []
    for i in range(30):
        d = (start_date + timedelta(days=i)).strftime('%Y-%m-%d')
        dates.append(d)
        counts.append(0)
    date_index = {dates[i]: i for i in range(len(dates))}
    for doc in trend_docs:
        idx = date_index.get(doc['_id'])
        if idx is not None:
            counts[idx] = doc['count']

    # 3) Disease type distribution
    disease_pipeline = [
        {'$match': {'user_id': session['user_id']}},
        {'$group': {'_id': '$disease_type', 'count': {'$sum': 1}}}
    ]
    disease_docs = list(mongo.db.patient_history.aggregate(disease_pipeline))
    disease_labels = [d['_id'] for d in disease_docs]
    disease_counts = [d['count'] for d in disease_docs]

    # 4) Confidence scores distribution
    confidence_pipeline = [
        {'$match': {'user_id': session['user_id']}},
        {'$project': {'range': {'$concat': [
            {'$cond': [{'$lt': ['$confidence', 50]}, '0-49%', '']},
            {'$cond': [{'$and': [{'$gte': ['$confidence', 50]}, {'$lt': ['$confidence', 80]}]}, '50-79%', '']},
            {'$cond': [{'$gte': ['$confidence', 80]}, '80-100%', '']}
        ]}}},
        {'$group': {'_id': '$range', 'count': {'$sum': 1}}}
    ]
    confidence_docs = list(mongo.db.patient_history.aggregate(confidence_pipeline))
    confidence_labels = [d['_id'] for d in confidence_docs if d['_id']]
    confidence_counts = [d['count'] for d in confidence_docs if d['_id']]

    return jsonify({
        'predictions': prediction_counts,
        'trend': {'dates': dates, 'counts': counts},
        'diseases': {'labels': disease_labels, 'counts': disease_counts},
        'confidence': {'labels': confidence_labels, 'counts': confidence_counts}
    })

# Admin dashboard
@app.route('/admin/dashboard')
def admin_dashboard():
    if 'user_id' not in session:
        flash('Please log in to access the dashboard!', 'error')
        return redirect(url_for('login'))
    
    # Check if user is admin
    user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
    if user['role'] != 'admin':
        flash('Access denied!', 'error')
        return redirect(url_for('user_dashboard'))
    
    # Get statistics
    total_users = mongo.db.users.count_documents({})
    heart_predictions = mongo.db.patient_history.count_documents({'disease_type': 'Heart Disease'})
    diabetes_predictions = mongo.db.patient_history.count_documents({'disease_type': 'Diabetes'})
    parkinsons_predictions = mongo.db.patient_history.count_documents({'disease_type': "Parkinson's"})
    
    # Get recent users (limit to 5)
    recent_users = list(mongo.db.users.find().sort('created_at', -1).limit(5))
    
    # Get all predictions (limit to 10)
    all_predictions = list(mongo.db.patient_history.find().sort('date', -1).limit(10))
    
    # Add user names to predictions
    for prediction in all_predictions:
        user = mongo.db.users.find_one({'_id': ObjectId(prediction['user_id'])})
        prediction['user_name'] = user['name'] if user else 'Unknown'
    
    return render_template('admin/dashboard.html',
                         total_users=total_users,
                         heart_predictions=heart_predictions,
                         diabetes_predictions=diabetes_predictions,
                         parkinsons_predictions=parkinsons_predictions,
                         recent_users=recent_users,
                         all_predictions=all_predictions)

# Heart Disease Prediction
@app.route('/user/heart-disease', methods=['GET', 'POST'])
def heart_disease_prediction():
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    if request.method == 'POST':
        try:
            # Get form data
            age = float(request.form['age'])
            sex = float(request.form['sex'])
            cp = float(request.form['cp'])
            trestbps = float(request.form['trestbps'])
            chol = float(request.form['chol'])
            fbs = float(request.form['fbs'])
            restecg = float(request.form['restecg'])
            thalach = float(request.form['thalach'])
            exang = float(request.form['exang'])
            oldpeak = float(request.form['oldpeak'])
            slope = float(request.form['slope'])
            ca = float(request.form['ca'])
            thal = float(request.form['thal'])
            
            # Create input array for prediction
            input_data = [age, sex, cp, trestbps, chol, fbs, restecg, thalach, exang, oldpeak, slope, ca, thal]
            
            # Make prediction
            prediction = heart_disease_model.predict([input_data])
            
            # Check if predict_proba is available and properly configured
            try:
                if hasattr(heart_disease_model, 'predict_proba') and callable(getattr(heart_disease_model, 'predict_proba')):
                    probability = heart_disease_model.predict_proba([input_data])
                    # Determine confidence based on the prediction
                    if prediction[0] == 1:
                        confidence = probability[0][1] * 100
                    else:
                        confidence = probability[0][0] * 100
                else:
                    # If predict_proba is not available, use a default confidence
                    confidence = 90.0 if prediction[0] == 1 else 10.0
            except Exception as e:
                # Handle any errors with predict_proba
                print(f"Warning: predict_proba failed with error: {e}")
                confidence = 90.0 if prediction[0] == 1 else 10.0
            
            # Determine result
            if prediction[0] == 1:
                result = "The person is likely to have heart disease"
            else:
                result = "The person is unlikely to have heart disease"
            
            # Store prediction in database
            prediction_data = {
                'user_id': session['user_id'],
                'disease_type': 'Heart Disease',
                'input_data': {
                    'age': age,
                    'sex': sex,
                    'cp': cp,
                    'trestbps': trestbps,
                    'chol': chol,
                    'fbs': fbs,
                    'restecg': restecg,
                    'thalach': thalach,
                    'exang': exang,
                    'oldpeak': oldpeak,
                    'slope': slope,
                    'ca': ca,
                    'thal': thal
                },
                'result': result,
                'confidence': confidence,
                'date': datetime.now()
            }
            
            mongo.db.patient_history.insert_one(prediction_data)
            
            # Add prediction data to session for display
            session['prediction_result'] = {
                'disease_type': 'Heart Disease',
                'result': result,
                'confidence': confidence,
                'input_data': prediction_data['input_data']
            }
            
            return redirect(url_for('prediction_result'))
            
        except Exception as e:
            flash(f'Error processing prediction: {str(e)}', 'error')
            return redirect(url_for('heart_disease_prediction'))
    
    return render_template('user/heart_disease.html')

# Diabetes Prediction
@app.route('/user/diabetes', methods=['GET', 'POST'])
def diabetes_prediction():
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    if request.method == 'POST':
        try:
            # Get form data
            pregnancies = float(request.form['pregnancies'])
            glucose = float(request.form['glucose'])
            blood_pressure = float(request.form['blood_pressure'])
            skin_thickness = float(request.form['skin_thickness'])
            insulin = float(request.form['insulin'])
            bmi = float(request.form['bmi'])
            diabetes_pedigree = float(request.form['diabetes_pedigree'])
            age = float(request.form['age'])
            
            # Create input array for prediction
            input_data = [pregnancies, glucose, blood_pressure, skin_thickness, insulin, bmi, diabetes_pedigree, age]
            
            # Make prediction
            prediction = diabetes_model.predict([input_data])
            
            # Check if predict_proba is available and properly configured
            try:
                if hasattr(diabetes_model, 'predict_proba') and callable(getattr(diabetes_model, 'predict_proba')):
                    probability = diabetes_model.predict_proba([input_data])
                    # Determine confidence based on the prediction
                    if prediction[0] == 1:
                        confidence = probability[0][1] * 100
                    else:
                        confidence = probability[0][0] * 100
                else:
                    # If predict_proba is not available, use a default confidence
                    confidence = 90.0 if prediction[0] == 1 else 10.0
            except Exception as e:
                # Handle any errors with predict_proba
                print(f"Warning: predict_proba failed with error: {e}")
                confidence = 90.0 if prediction[0] == 1 else 10.0
            
            # Determine result
            if prediction[0] == 1:
                result = "The person is likely to have diabetes"
            else:
                result = "The person is unlikely to have diabetes"
            
            # Store prediction in database
            prediction_data = {
                'user_id': session['user_id'],
                'disease_type': 'Diabetes',
                'input_data': {
                    'pregnancies': pregnancies,
                    'glucose': glucose,
                    'blood_pressure': blood_pressure,
                    'skin_thickness': skin_thickness,
                    'insulin': insulin,
                    'bmi': bmi,
                    'diabetes_pedigree': diabetes_pedigree,
                    'age': age
                },
                'result': result,
                'confidence': confidence,
                'date': datetime.now()
            }
            
            mongo.db.patient_history.insert_one(prediction_data)
            
            # Add prediction data to session for display
            session['prediction_result'] = {
                'disease_type': 'Diabetes',
                'result': result,
                'confidence': confidence,
                'input_data': prediction_data['input_data']
            }
            
            return redirect(url_for('prediction_result'))
            
        except Exception as e:
            flash(f'Error processing prediction: {str(e)}', 'error')
            return redirect(url_for('diabetes_prediction'))
    
    return render_template('user/diabetes.html')

# Parkinson's Prediction
@app.route('/user/parkinsons', methods=['GET', 'POST'])
def parkinsons_prediction():
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    if request.method == 'POST':
        try:
            # Get form data
            fo = float(request.form['fo'])
            fhi = float(request.form['fhi'])
            flo = float(request.form['flo'])
            jitter_percent = float(request.form['jitter_percent'])
            jitter_abs = float(request.form['jitter_abs'])
            rap = float(request.form['rap'])
            ppq = float(request.form['ppq'])
            ddp = float(request.form['ddp'])
            shimmer = float(request.form['shimmer'])
            shimmer_db = float(request.form['shimmer_db'])
            apq3 = float(request.form['apq3'])
            apq5 = float(request.form['apq5'])
            apq = float(request.form['apq'])
            dda = float(request.form['dda'])
            nhr = float(request.form['nhr'])
            hnr = float(request.form['hnr'])
            rpde = float(request.form['rpde'])
            dfa = float(request.form['dfa'])
            spread1 = float(request.form['spread1'])
            spread2 = float(request.form['spread2'])
            d2 = float(request.form['d2'])
            ppe = float(request.form['ppe'])
            
            # Create input array for prediction
            input_data = [fo, fhi, flo, jitter_percent, jitter_abs, rap, ppq, ddp, shimmer, shimmer_db, 
                         apq3, apq5, apq, dda, nhr, hnr, rpde, dfa, spread1, spread2, d2, ppe]
            
            # Make prediction
            prediction = parkinsons_model.predict([input_data])
            
            # Check if predict_proba is available and properly configured
            try:
                if hasattr(parkinsons_model, 'predict_proba') and callable(getattr(parkinsons_model, 'predict_proba')):
                    probability = parkinsons_model.predict_proba([input_data])
                    # Determine confidence based on the prediction
                    if prediction[0] == 1:
                        confidence = probability[0][1] * 100
                    else:
                        confidence = probability[0][0] * 100
                else:
                    # If predict_proba is not available, use a default confidence
                    confidence = 90.0 if prediction[0] == 1 else 10.0
            except Exception as e:
                # Handle any errors with predict_proba
                print(f"Warning: predict_proba failed with error: {e}")
                confidence = 90.0 if prediction[0] == 1 else 10.0
            
            # Determine result
            if prediction[0] == 1:
                result = "The person is likely to have Parkinson's disease"
            else:
                result = "The person is unlikely to have Parkinson's disease"
            
            # Store prediction in database
            prediction_data = {
                'user_id': session['user_id'],
                'disease_type': "Parkinson's",
                'input_data': {
                    'fo': fo,
                    'fhi': fhi,
                    'flo': flo,
                    'jitter_percent': jitter_percent,
                    'jitter_abs': jitter_abs,
                    'rap': rap,
                    'ppq': ppq,
                    'ddp': ddp,
                    'shimmer': shimmer,
                    'shimmer_db': shimmer_db,
                    'apq3': apq3,
                    'apq5': apq5,
                    'apq': apq,
                    'dda': dda,
                    'nhr': nhr,
                    'hnr': hnr,
                    'rpde': rpde,
                    'dfa': dfa,
                    'spread1': spread1,
                    'spread2': spread2,
                    'd2': d2,
                    'ppe': ppe
                },
                'result': result,
                'confidence': confidence,
                'date': datetime.now()
            }
            
            mongo.db.patient_history.insert_one(prediction_data)
            
            # Add prediction data to session for display
            session['prediction_result'] = {
                'disease_type': "Parkinson's",
                'result': result,
                'confidence': confidence,
                'input_data': prediction_data['input_data']
            }
            
            return redirect(url_for('prediction_result'))
            
        except Exception as e:
            flash(f'Error processing prediction: {str(e)}', 'error')
            return redirect(url_for('parkinsons_prediction'))
    
    return render_template('user/parkinsons.html')

# Prediction Result
@app.route('/user/result')
def prediction_result():
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    if 'prediction_result' not in session:
        flash('No prediction result found!', 'error')
        return redirect(url_for('user_dashboard'))
    
    result = session['prediction_result']
    return render_template('user/result.html', result=result)

# Patient History
@app.route('/user/history')
def patient_history():
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    # Get all predictions for the user
    history = list(mongo.db.patient_history.find(
        {'user_id': session['user_id']}
    ).sort('date', -1))
    
    return render_template('user/history.html', history=history)

# Detailed Report
@app.route('/user/report/<report_id>')
def detailed_report(report_id):
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    # Get the report
    report = mongo.db.patient_history.find_one(
        {'_id': ObjectId(report_id), 'user_id': session['user_id']}
    )
    
    if not report:
        flash('Report not found!', 'error')
        return redirect(url_for('patient_history'))
    
    return render_template('user/report.html', report=report)

# Delete Report
@app.route('/user/delete-report/<report_id>')
def delete_report(report_id):
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    # Delete the report
    result = mongo.db.patient_history.delete_one(
        {'_id': ObjectId(report_id), 'user_id': session['user_id']}
    )
    
    if result.deleted_count > 0:
        flash('Report deleted successfully!', 'success')
    else:
        flash('Report not found or you do not have permission to delete it!', 'error')
    
    return redirect(url_for('patient_history'))

# Download Result as PDF (from session)
@app.route('/user/download-result')
def download_result():
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    if 'prediction_result' not in session:
        flash('No prediction result found!', 'error')
        return redirect(url_for('user_dashboard'))
    
    result = session['prediction_result']
    
    # Create PDF in memory
    buffer = io.BytesIO()
    c = canvas.Canvas(buffer, pagesize=letter)
    width, height = letter
    
    # Add content to PDF
    c.setFont("Helvetica-Bold", 16)
    c.drawString(100, height - 50, "Multiple Disease Prediction System")
    
    c.setFont("Helvetica-Bold", 14)
    c.drawString(100, height - 100, f"{result['disease_type']} Prediction Report")
    
    c.setFont("Helvetica", 12)
    c.drawString(100, height - 130, f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M')}")
    c.drawString(100, height - 150, f"Result: {result['result']}")
    c.drawString(100, height - 170, f"Confidence: {result['confidence']:.2f}%")
    
    # Add input data
    c.setFont("Helvetica-Bold", 12)
    c.drawString(100, height - 200, "Input Data:")
    
    c.setFont("Helvetica", 10)
    y_position = height - 220
    for key, value in result['input_data'].items():
        c.drawString(120, y_position, f"{key.replace('_', ' ').title()}: {value}")
        y_position -= 15
        if y_position < 100:  # Start new page if needed
            c.showPage()
            y_position = height - 100
    
    # Add disclaimer
    c.setFont("Helvetica-Oblique", 10)
    c.drawString(100, 50, "Note: This prediction is based on machine learning algorithms and should not be")
    c.drawString(100, 35, "considered as a medical diagnosis. Please consult with a healthcare professional.")
    
    c.save()
    
    # Prepare response
    buffer.seek(0)
    return send_file(
        buffer,
        as_attachment=True,
        download_name=f"{result['disease_type']}_prediction_report.pdf",
        mimetype='application/pdf'
    )

# Download Report as PDF (from database)
@app.route('/user/download-report/<report_id>')
def download_report(report_id):
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    # Get the report
    report = mongo.db.patient_history.find_one(
        {'_id': ObjectId(report_id), 'user_id': session['user_id']}
    )
    
    if not report:
        flash('Report not found!', 'error')
        return redirect(url_for('patient_history'))
    
    # Create PDF in memory
    buffer = io.BytesIO()
    c = canvas.Canvas(buffer, pagesize=letter)
    width, height = letter
    
    # Add content to PDF
    c.setFont("Helvetica-Bold", 16)
    c.drawString(100, height - 50, "Multiple Disease Prediction System")
    
    c.setFont("Helvetica-Bold", 14)
    c.drawString(100, height - 100, f"{report['disease_type']} Prediction Report")
    
    c.setFont("Helvetica", 12)
    c.drawString(100, height - 130, f"Date: {report['date'].strftime('%Y-%m-%d %H:%M')}")
    c.drawString(100, height - 150, f"Result: {report['result']}")
    c.drawString(100, height - 170, f"Confidence: {report['confidence']:.2f}%")
    
    # Add input data
    c.setFont("Helvetica-Bold", 12)
    c.drawString(100, height - 200, "Input Data:")
    
    c.setFont("Helvetica", 10)
    y_position = height - 220
    for key, value in report['input_data'].items():
        c.drawString(120, y_position, f"{key.replace('_', ' ').title()}: {value}")
        y_position -= 15
        if y_position < 100:  # Start new page if needed
            c.showPage()
            y_position = height - 100
    
    # Add disclaimer
    c.setFont("Helvetica-Oblique", 10)
    c.drawString(100, 50, "Note: This prediction is based on machine learning algorithms and should not be")
    c.drawString(100, 35, "considered as a medical diagnosis. Please consult with a healthcare professional.")
    
    c.save()
    
    # Prepare response
    buffer.seek(0)
    return send_file(
        buffer,
        as_attachment=True,
        download_name=f"{report['disease_type']}_prediction_report_{report_id}.pdf",
        mimetype='application/pdf'
    )

# Doctor Appointments
@app.route('/doctor/appointments')
def doctor_appointments():
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    # Check if user is doctor
    user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
    if user['role'] != 'doctor':
        flash('Access denied!', 'error')
        return redirect(url_for('user_dashboard'))
    
    # Get pending appointments matching doctor's specialization
    # Map common specializations to disease keywords to improve matching
    specialization_map = {
        'Cardiologist': ['heart', 'cardio', 'cardiologist'],
        'Endocrinologist': ['diabetes', 'endocrine', 'endocrinologist'],
        "Neurologist": ['parkinson', 'neuro', 'neurologist'],
        'General Practitioner': []
    }

    spec = user.get('specialization', '') or ''
    keywords = []
    for key, vals in specialization_map.items():
        if spec.lower() == key.lower():
            keywords = vals
            break

    if keywords:
        # build regex to match any of the keywords
        regex_parts = '|'.join([f"{kw}" for kw in keywords])
        pending_appointments = list(mongo.db.appointments.find({
            'disease_type': {'$regex': regex_parts, '$options': 'i'},
            'status': 'pending'
        }).sort('date', 1))
    else:
        # fallback: if no specialization or GP, show appointments assigned to this doctor or all pending
        pending_appointments = list(mongo.db.appointments.find({
            '$or': [
                {'doctor': {'$regex': user['name'], '$options': 'i'}},
                {'status': 'pending'}
            ]
        }).sort('date', 1))
    
    # Add patient information to pending appointments
    for appointment in pending_appointments:
        patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])})
        appointment['patient_name'] = patient['name'] if patient else 'Unknown'
        appointment['patient_email'] = patient['email'] if patient else 'Unknown'
    
    # Get confirmed appointments
    confirmed_appointments = list(mongo.db.appointments.find({
        'doctor': {'$regex': user['name'], '$options': 'i'},
        'status': 'confirmed'
    }).sort([('date', 1), ('time', 1)]))
    
    # Add patient information to confirmed appointments
    for appointment in confirmed_appointments:
        patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])})
        appointment['patient_name'] = patient['name'] if patient else 'Unknown'
        appointment['patient_email'] = patient['email'] if patient else 'Unknown'
    
    return render_template('doctor/appointments.html', 
                         pending_appointments=pending_appointments,
                         confirmed_appointments=confirmed_appointments,
                         doctor=user)


@app.route('/doctor/dashboard')
def doctor_dashboard():
    if 'user_id' not in session:
        flash('Please log in to access the dashboard!', 'error')
        return redirect(url_for('login'))
    user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
    if user['role'] != 'doctor':
        flash('Access denied!', 'error')
        return redirect(url_for('user_dashboard'))

    return render_template('doctor/dashboard.html')


@app.route('/doctor/dashboard/data')
def doctor_dashboard_data():
    """Return JSON with data for Plotly charts for the logged-in doctor."""
    if 'user_id' not in session:
        return jsonify({'error': 'Unauthorized'}), 401

    user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
    if not user or user.get('role') != 'doctor':
        return jsonify({'error': 'Forbidden'}), 403

    # specialization keywords (reuse mapping)
    specialization_map = {
        'Cardiologist': ['heart', 'cardio', 'cardiologist'],
        'Endocrinologist': ['diabetes', 'endocrine', 'endocrinologist'],
        "Neurologist": ['parkinson', 'neuro', 'neurologist'],
        'General Practitioner': []
    }

    spec = user.get('specialization', '') or ''
    keywords = []
    for key, vals in specialization_map.items():
        if spec.lower() == key.lower():
            keywords = vals
            break

    # build base filter for appointments relevant to this doctor
    if keywords:
        regex_parts = '|'.join([f"{kw}" for kw in keywords])
        base_filter = {'disease_type': {'$regex': regex_parts, '$options': 'i'}}
    else:
        base_filter = {}

    # 1) Appointment status counts (for this specialization or assigned to this doctor)
    status_pipeline = [
        {'$match': {'$or': [base_filter, {'doctor_id': session['user_id']}]}},
        {'$group': {'_id': '$status', 'count': {'$sum': 1}}}
    ]
    status_counts = { 'pending':0, 'confirmed':0, 'rejected':0, 'cancelled':0 }
    for doc in mongo.db.appointments.aggregate(status_pipeline):
        # normalize status key and guard against unexpected values
        raw_key = doc.get('_id')
        if raw_key is None:
            key = 'unknown'
        else:
            key = str(raw_key).lower()
        # assign into known buckets if present, otherwise keep as-is under its key
        if key in status_counts:
            status_counts[key] = doc.get('count', 0)
        else:
            # for unexpected keys, add them to the dict to avoid key errors downstream
            status_counts[key] = doc.get('count', 0)

    # 2) Trend: appointments per day for last 30 days
    from datetime import timedelta
    today = datetime.now()
    start_date = today - timedelta(days=29)
    match_trend = {'date': {'$gte': start_date}}
    if keywords:
        match_trend['$or'] = [base_filter, {'doctor_id': session['user_id']}]
    else:
        base_filter = {}

    trend_pipeline = [
        {'$match': match_trend},
        {'$group': {'_id': {'$dateToString': {'format':'%Y-%m-%d', 'date':'$date'}}, 'count': {'$sum':1}}},
        {'$sort': {'_id': 1}}
    ]
    trend_docs = list(mongo.db.appointments.aggregate(trend_pipeline))
    # prepare arrays for the last 30 days
    dates = []
    counts = []
    for i in range(30):
        d = (start_date + timedelta(days=i)).strftime('%Y-%m-%d')
        dates.append(d)
        counts.append(0)
    date_index = {dates[i]: i for i in range(len(dates))}
    for doc in trend_docs:
        idx = date_index.get(doc['_id'])
        if idx is not None:
            counts[idx] = doc['count']

    # 3) Upcoming schedule: next 10 confirmed appointments for this doctor
    # use start of today to include today's appointments (date stored as date with 00:00 time)
    start_of_today = datetime(today.year, today.month, today.day)
    upcoming_docs = list(mongo.db.appointments.find({'doctor_id': session['user_id'], 'status':'confirmed', 'date': {'$gte': start_of_today}}).sort([('date',1),('time',1)]).limit(10))
    schedule_times = []
    schedule_labels = []
    for a in upcoming_docs:
        schedule_times.append(a['date'].strftime('%Y-%m-%d') + ' ' + a['time'])
        # patient name
        patient = mongo.db.users.find_one({'_id': ObjectId(a['user_id'])})
        schedule_labels.append(patient['name'] if patient else 'Unknown')

    # 4) Patient distribution: unique patients per month (last 6 months)
    six_months_ago = today - timedelta(days=180)
    patient_pipeline = [
        {'$match': {'doctor_id': session['user_id'], 'status':'confirmed', 'date': {'$gte': six_months_ago}}},
        {'$group': {'_id': {'month': {'$month':'$date'}, 'year': {'$year':'$date'}}, 'patients': {'$addToSet': '$user_id'}}},
        {'$project': {'month':'$_id.month','year':'$_id.year','count': {'$size':'$patients'}}},
        {'$sort': {'year':1, 'month':1}}
    ]
    patient_docs = list(mongo.db.appointments.aggregate(patient_pipeline))
    months = [f"{d['month']}-{d['year']}" for d in patient_docs]
    patient_counts = [d['count'] for d in patient_docs]

    # 5) Details frequency (checkboxes)
    # Build a details match that limits to either the specialization OR appointments assigned to this doctor
    if keywords:
        details_match = {'$or': [base_filter, {'doctor_id': session['user_id']} ]}
    else:
        details_match = {'doctor_id': session['user_id']}

    details_pipeline = [
        {'$match': details_match},
        {'$unwind': '$details_selected'},
        {'$group': {'_id': '$details_selected', 'count': {'$sum': 1}}},
        {'$sort': {'count': -1}}
    ]
    details_docs = list(mongo.db.appointments.aggregate(details_pipeline))
    details_labels = [d['_id'] for d in details_docs]
    details_counts = [d['count'] for d in details_docs]

    return jsonify({
        'status': status_counts,
        'trend': {'dates': dates, 'counts': counts},
        'schedule': {'times': schedule_times, 'labels': schedule_labels},
        'patient': {'months': months, 'counts': patient_counts},
        'details': {'labels': details_labels, 'counts': details_counts}
    })

# Confirm Appointment
@app.route('/doctor/appointments/<appointment_id>/confirm', methods=['POST'])
def doctor_confirm_appointment(appointment_id):
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    # Check if user is doctor
    user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
    if user['role'] != 'doctor':
        flash('Access denied!', 'error')
        return redirect(url_for('user_dashboard'))
    
    # Update appointment status to confirmed
    # Check that the doctor doesn't already have a confirmed appointment at same date/time
    appointment = mongo.db.appointments.find_one({'_id': ObjectId(appointment_id)})
    if not appointment:
        flash('Appointment not found!', 'error')
        return redirect(url_for('doctor_appointments'))

    # If appointment already has a doctor assigned and it's not this doctor, deny
    if appointment.get('doctor_id') and appointment.get('doctor_id') != session['user_id']:
        flash('This appointment has already been assigned to another doctor.', 'error')
        return redirect(url_for('doctor_appointments'))

    # Check for conflicting confirmed appointments for this doctor
    conflict = mongo.db.appointments.find_one({
        'doctor_id': session['user_id'],
        'date': appointment['date'],
        'time': appointment['time'],
        'status': 'confirmed'
    })

    if conflict:
        flash('You already have a confirmed appointment at this date and time.', 'error')
        return redirect(url_for('doctor_appointments'))

    # Mark appointment as confirmed and assign to this doctor
    result = mongo.db.appointments.update_one(
        {'_id': ObjectId(appointment_id)},
        {'$set': {
            'status': 'confirmed',
            'doctor_id': session['user_id'],
            'doctor': user['name']
        }}
    )

    if result.modified_count > 0:
        flash('Appointment confirmed successfully!', 'success')
    else:
        flash('Failed to confirm appointment. It may have been updated by someone else.', 'error')
    
    return redirect(url_for('doctor_appointments'))

# Reject Appointment
@app.route('/doctor/appointments/<appointment_id>/reject', methods=['POST'])
def doctor_reject_appointment(appointment_id):
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    # Check if user is doctor
    user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
    if user['role'] != 'doctor':
        flash('Access denied!', 'error')
        return redirect(url_for('user_dashboard'))
    
    # Update appointment status to rejected
    result = mongo.db.appointments.update_one(
        {'_id': ObjectId(appointment_id)},
        {'$set': {
            'status': 'rejected',
            'doctor_id': session['user_id'],
            'doctor': user['name']
        }}
    )
    
    if result.modified_count > 0:
        flash('Appointment rejected successfully!', 'success')
    else:
        flash('Appointment not found!', 'error')
    
    return redirect(url_for('doctor_appointments'))

# Chat functionality
@app.route('/user/chat/<appointment_id>')
def user_chat(appointment_id):
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    # Check if appointment exists and is confirmed
    appointment = mongo.db.appointments.find_one({
        '_id': ObjectId(appointment_id),
        'user_id': session['user_id'],
        'status': 'confirmed'
    })
    
    if not appointment:
        flash('Appointment not found or not confirmed!', 'error')
        return redirect(url_for('user_appointments'))
    
    # Get messages for this appointment
    messages = list(mongo.db.messages.find(
        {'appointment_id': appointment_id}
    ).sort('timestamp', 1))
    
    # Get doctor info
    doctor = mongo.db.users.find_one({'_id': ObjectId(appointment['doctor_id'])})
    
    return render_template('user/chat.html', 
                         appointment=appointment,
                         messages=messages,
                         doctor=doctor)

@app.route('/doctor/chat/<appointment_id>')
def doctor_chat(appointment_id):
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    # Check if user is doctor
    user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
    if user['role'] != 'doctor':
        flash('Access denied!', 'error')
        return redirect(url_for('user_dashboard'))
    
    # Check if appointment exists and is confirmed
    appointment = mongo.db.appointments.find_one({
        '_id': ObjectId(appointment_id),
        'doctor_id': session['user_id'],
        'status': 'confirmed'
    })
    
    if not appointment:
        flash('Appointment not found or not confirmed!', 'error')
        return redirect(url_for('doctor_appointments'))
    
    # Get messages for this appointment
    messages = list(mongo.db.messages.find(
        {'appointment_id': appointment_id}
    ).sort('timestamp', 1))
    
    # Get patient info
    patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])})
    
    return render_template('doctor/chat.html', 
                         appointment=appointment,
                         messages=messages,
                         patient=patient)

# Send message
@app.route('/send_message', methods=['POST'])
def send_message():
    if 'user_id' not in session:
        flash('Please log in to access this page!', 'error')
        return redirect(url_for('login'))
    
    appointment_id = request.form['appointment_id']
    message_text = request.form['message']
    
    # Check if appointment exists and is confirmed
    appointment = mongo.db.appointments.find_one({
        '_id': ObjectId(appointment_id),
        'status': 'confirmed'
    })
    
    if not appointment:
        flash('Appointment not found or not confirmed!', 'error')
        return redirect(url_for('user_dashboard'))
    
    # Check if user is authorized to send message (patient or doctor)
    if session['user_id'] not in [str(appointment['user_id']), str(appointment.get('doctor_id', ''))]:
        flash('Access denied!', 'error')
        return redirect(url_for('user_dashboard'))
    
    # Create message
    message_data = {
        'appointment_id': appointment_id,
        'sender_id': session['user_id'],
        'message_text': message_text,
        'timestamp': datetime.now()
    }
    
    # Insert message into database
    mongo.db.messages.insert_one(message_data)
    
    # Redirect based on user role
    user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
    if user['role'] == 'doctor':
        return redirect(url_for('doctor_chat', appointment_id=appointment_id))
    else:
        return redirect(url_for('user_chat', appointment_id=appointment_id))

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