File size: 84,978 Bytes
b2e192e
 
 
 
 
 
 
3776079
b2e192e
 
 
fe88653
 
 
e93f833
 
3776079
 
 
c8da835
3776079
 
fe88653
3776079
b2e192e
c8da835
b2e192e
 
 
 
fe88653
5190a0b
b2e192e
fe88653
 
c8da835
5190a0b
 
fe88653
 
5190a0b
fe88653
c8da835
fe88653
 
 
 
 
 
c8da835
fe88653
 
 
5190a0b
fe88653
 
 
 
 
 
b2e192e
5190a0b
 
fe88653
 
 
 
 
 
 
 
 
 
5190a0b
 
c8da835
5190a0b
fe88653
 
5190a0b
fe88653
 
 
 
 
 
3776079
 
5190a0b
 
fe88653
 
 
 
3776079
 
5190a0b
 
fe88653
 
 
 
3776079
 
5190a0b
 
fe88653
 
 
 
b2e192e
 
c8da835
fe88653
 
 
5190a0b
fe88653
3776079
 
 
c8da835
3776079
 
 
fe88653
 
 
5190a0b
c8da835
b2e192e
5190a0b
fe88653
c8da835
 
5190a0b
 
fe88653
 
 
 
5190a0b
fe88653
c8da835
5190a0b
 
fe88653
5190a0b
fe88653
 
5190a0b
 
dc2c50b
fe88653
 
 
 
 
 
c8da835
 
 
 
 
 
 
 
e93f833
 
 
 
 
 
 
b2e192e
 
 
 
 
 
 
 
 
5190a0b
 
fe88653
 
 
 
e93f833
 
86ca02b
 
0e31758
 
b2e192e
fe88653
 
 
c8da835
 
 
fe88653
 
c8da835
 
 
fe88653
 
c8da835
 
 
fe88653
 
c8da835
 
 
fe88653
 
c8da835
 
 
fe88653
 
2923fbe
e93f833
 
 
 
 
 
 
 
 
0e31758
e93f833
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe88653
e93f833
 
0e31758
b2e192e
fe88653
0e31758
 
e93f833
 
 
0e31758
 
e93f833
0e31758
 
e93f833
 
10d9062
0e31758
 
10d9062
0e31758
 
 
 
 
 
 
 
 
 
 
e93f833
 
0e31758
e93f833
0e31758
e93f833
 
 
 
 
 
 
 
 
0e31758
e93f833
 
 
 
 
0e31758
e93f833
0e31758
e93f833
0e31758
e93f833
 
 
0e31758
 
10d9062
c8da835
0e31758
10d9062
0e31758
1f2ecec
0e31758
 
 
fe88653
0e31758
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe88653
0e31758
c8da835
0e31758
c8da835
0e31758
10d9062
0e31758
c8da835
0e31758
c8da835
0e31758
10d9062
0e31758
10d9062
0e31758
10d9062
0e31758
10d9062
0e31758
10d9062
0e31758
 
 
 
 
 
 
 
 
10d9062
0e31758
c8da835
0e31758
fe88653
0e31758
fe88653
0e31758
fe88653
0e31758
 
 
 
 
fe88653
0e31758
fe88653
0e31758
 
 
fe88653
0e31758
 
 
fe88653
0e31758
fe88653
0e31758
fe88653
0e31758
fe88653
0e31758
fe88653
0e31758
fe88653
0e31758
10d9062
0e31758
fe88653
0e31758
fe88653
0e31758
fe88653
0e31758
 
 
fe88653
0e31758
fe88653
0e31758
c8da835
0e31758
fe88653
0e31758
 
 
 
 
fe88653
0e31758
fe88653
0e31758
 
 
 
 
fe88653
0e31758
fe88653
0e31758
fe88653
0e31758
10d9062
0e31758
fe88653
0e31758
fe88653
0e31758
fe88653
0e31758
fe88653
0e31758
fe88653
0e31758
c8da835
0e31758
fe88653
0e31758
fe88653
0e31758
fe88653
0e31758
fe88653
0e31758
c8da835
0e31758
c8da835
0e31758
 
 
 
 
 
 
c8da835
0e31758
 
 
 
 
 
 
fe88653
0e31758
fe88653
0e31758
 
 
 
 
 
 
 
 
1f2ecec
0e31758
 
 
 
 
 
 
 
 
1f2ecec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10d9062
1f2ecec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e31758
1f2ecec
 
0e31758
1f2ecec
 
 
 
 
0e31758
 
 
1f2ecec
 
0e31758
 
1f2ecec
 
0e31758
 
1f2ecec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e31758
1f2ecec
0e31758
1f2ecec
 
 
 
 
 
0e31758
1f2ecec
0e31758
1f2ecec
 
 
 
 
 
0e31758
1f2ecec
0e31758
1f2ecec
 
 
 
 
 
0e31758
1f2ecec
0e31758
1f2ecec
 
2fd7766
 
 
 
0e31758
2fd7766
 
0e31758
2fd7766
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e31758
2fd7766
0e31758
2fd7766
 
1f2ecec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
import numpy as np
import joblib
import pickle
from PIL import Image
import io
import os
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime
import base64
from fpdf import FPDF
import tempfile
import requests
import json

# Set page config first
st.set_page_config(
    page_title="SehatAI - Smart Healthcare Triage",
    page_icon="🏥",
    layout="wide",
    initial_sidebar_state="collapsed"
)

# Professional CSS Styling with Pakistan theme colors
def local_css():
    st.markdown("""
    <style>
    .main-header {
        font-size: 3.5rem;
        color: #1f77b4;
        text-align: center;
        margin-bottom: 0.5rem;
        font-weight: 800;
        background: linear-gradient(135deg, #00401A, #00612A, #008000);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        text-shadow: 0px 4px 8px rgba(0,0,0,0.2);
        font-family: 'Arial', sans-serif;
    }
    .quote-section {
        background: linear-gradient(135deg, #00401A 0%, #00612A 100%);
        color: white;
        padding: 25px;
        border-radius: 20px;
        text-align: center;
        margin: 20px 0;
        box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        border: 3px solid #008000;
    }
    .quote-text {
        font-size: 1.4rem;
        font-weight: 600;
        margin-bottom: 10px;
        font-style: italic;
    }
    .quote-author {
        font-size: 1.1rem;
        opacity: 0.9;
    }
    .section-container {
        background: white;
        padding: 30px;
        border-radius: 20px;
        box-shadow: 0 8px 25px rgba(0,0,0,0.1);
        margin-bottom: 30px;
        border: 2px solid #e0e0e0;
        transition: all 0.3s ease;
    }
    .section-container:hover {
        box-shadow: 0 12px 35px rgba(0,0,0,0.15);
        transform: translateY(-2px);
    }
    .metric-card {
        background: linear-gradient(135deg, #00401A 0%, #00612A 100%);
        color: white;
        padding: 25px;
        border-radius: 15px;
        text-align: center;
        box-shadow: 0 6px 15px rgba(0,0,0,0.2);
        transition: all 0.3s ease;
    }
    .metric-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 10px 25px rgba(0,0,0,0.3);
    }
    .risk-high { 
        background: linear-gradient(135deg, #ff6b6b, #ee5a52);
        color: white;
        padding: 25px;
        border-radius: 15px;
        border-left: 8px solid #dc3545;
        box-shadow: 0 6px 15px rgba(220,53,69,0.4);
    }
    .risk-medium { 
        background: linear-gradient(135deg, #ffd93d, #ffcd3c);
        color: #333;
        padding: 25px;
        border-radius: 15px;
        border-left: 8px solid #ffc107;
        box-shadow: 0 6px 15px rgba(255,193,7,0.4);
    }
    .risk-low { 
        background: linear-gradient(135deg, #6bcf7f, #28a745);
        color: white;
        padding: 25px;
        border-radius: 15px;
        border-left: 8px solid #20c997;
        box-shadow: 0 6px 15px rgba(40,167,69,0.4);
    }
    .priority-box { 
        border: 4px solid #00612A; 
        padding: 30px; 
        border-radius: 20px; 
        margin: 20px 0;
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        box-shadow: 0 8px 25px rgba(0,0,0,0.15);
    }
    .stButton button {
        width: 100%;
        background: linear-gradient(45deg, #00401A, #00612A);
        color: white;
        font-weight: bold;
        border: none;
        padding: 16px 32px;
        border-radius: 12px;
        font-size: 1.2rem;
        transition: all 0.3s ease;
        box-shadow: 0 6px 15px rgba(0,64,26,0.4);
    }
    .stButton button:hover {
        transform: translateY(-3px);
        box-shadow: 0 10px 25px rgba(0,64,26,0.5);
        background: linear-gradient(45deg, #00612A, #00401A);
    }
    .chat-message {
        padding: 15px;
        border-radius: 15px;
        margin: 10px 0;
        border: 2px solid #e0e0e0;
    }
    .user-message {
        background: linear-gradient(135deg, #00401A, #00612A);
        color: white;
        margin-left: 20%;
        text-align: right;
    }
    .bot-message {
        background: linear-gradient(135deg, #f8f9fa, #e9ecef);
        color: #333;
        margin-right: 20%;
    }
    .language-selector {
        position: absolute;
        top: 20px;
        right: 20px;
        z-index: 1000;
    }
    .pakistan-flag {
        background: linear-gradient(135deg, #00401A, #00612A, #FFFFFF);
        padding: 5px 15px;
        border-radius: 20px;
        color: white;
        font-weight: bold;
        margin: 0 10px;
    }
    .api-key-section {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        padding: 15px;
        border-radius: 10px;
        margin: 10px 0;
        color: white;
    }
    </style>
    """, unsafe_allow_html=True)

# Initialize session state
def init_session_state():
    if 'patient_data' not in st.session_state:
        st.session_state.patient_data = {}
    if 'risk_scores' not in st.session_state:
        st.session_state.risk_scores = {}
    if 'assessment_history' not in st.session_state:
        st.session_state.assessment_history = []
    if 'chat_history' not in st.session_state:
        st.session_state.chat_history = []
    if 'current_language' not in st.session_state:
        st.session_state.current_language = 'English'
    if 'groq_api_key' not in st.session_state:
        st.session_state.groq_api_key = ''
    if 'models_loaded' not in st.session_state:
        st.session_state.models_loaded = False
    if 'api_available' not in st.session_state:
        st.session_state.api_available = False

# Healthcare quotes database
HEALTHCARE_QUOTES = [
    {
        'english': "Health is the crown on the well person's head that only the ill can see.",
        'urdu': "صحت ایک تاج ہے جو تندرست انسان کے سر پر ہوتا ہے جسے صرف بیمار ہی دیکھ سکتے ہیں۔",
        'author': "Robin Sharma"
    },
    {
        'english': "The first wealth is health. Take care of your body, it's the only place you have to live.",
        'urdu': "پہلی دولت صحت ہے۔ اپنے جسم کا خیال رکھیں، یہ وہ واحد جگہ ہے جہاں آپ کو رہنا ہے۔",
        'author': "Ralph Waldo Emerson"
    },
    {
        'english': "A healthy outside starts from the inside. Prevention is better than cure.",
        'urdu': "ایک صحت مند باہر کی طرف اندر سے شروع ہوتی ہے۔ بچاؤ علاج سے بہتر ہے۔",
        'author': "Robert Urich"
    },
    {
        'english': "Your body hears everything your mind says. Stay positive for better health.",
        'urdu': "آپ کا جسم وہ سب کچھ سنتا ہے جو آپ کا دماغ کہتا ہے۔ بہتر صحت کے لیے مثبت رہیں۔",
        'author': "Naomi Judd"
    },
    {
        'english': "The greatest of follies is to sacrifice health for any other kind of happiness.",
        'urdu': "سب سے بڑی بیوقوفی صحت کو کسی دوسری قسم کی خوشی کے لیے قربان کرنا ہے۔",
        'author': "Arthur Schopenhauer"
    }
]

class GroqClient:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.groq.com/openai/v1"
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
    
    def chat_completions_create(self, messages, model="llama3-8b-8192", temperature=0.7, max_tokens=1024):
        try:
            url = f"{self.base_url}/chat/completions"
            data = {
                "messages": messages,
                "model": model,
                "temperature": temperature,
                "max_tokens": max_tokens,
                "top_p": 0.9
            }
            
            response = requests.post(url, headers=self.headers, json=data, timeout=30)
            response.raise_for_status()
            
            result = response.json()
            return result
            
        except Exception as e:
            raise Exception(f"Groq API error: {str(e)}")

class HealthcareChatbot:
    def __init__(self, groq_client=None):
        self.groq_client = groq_client
        self.api_available = groq_client is not None and groq_client.api_key
    
    def get_response(self, user_input, language='English'):
        # Always try API first if available
        if self.api_available:
            try:
                return self._get_groq_response(user_input, language)
            except Exception as e:
                st.error(f"⚠️ API temporarily unavailable. Using enhanced response system.")
                return self._get_enhanced_response(user_input, language)
        
        # If no API, use enhanced responses
        return self._get_enhanced_response(user_input, language)
    
    def _get_groq_response(self, user_input, language):
        system_prompt = """You are Dr. SehatAI, a professional medical AI assistant for Pakistani patients. 
        Provide accurate, compassionate medical guidance in a natural, conversational tone.

        CRITICAL GUIDELINES:
        1. NEVER use structured lists with bullet points or markdown formatting
        2. ALWAYS respond in natural, flowing paragraphs like a real doctor
        3. Be specific and directly address the patient's concern
        4. Provide practical, actionable medical advice
        5. Include when to seek emergency care when relevant
        6. Be empathetic but professional
        7. Use plain text without any special formatting
        8. Keep responses concise but comprehensive
        9. For Pakistani context, consider local healthcare accessibility

        Format your response as a doctor would speak to a patient in a consultation."""
        
        if language == 'Urdu':
            system_prompt += " Respond in Urdu with natural, flowing text. Use professional medical terminology but make it accessible. Avoid any structured lists or bullet points."
        else:
            system_prompt += " Respond in English with natural, flowing text. Use professional medical terminology but make it accessible. Avoid any structured lists or bullet points."
        
        messages = [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_input}
        ]
        
        response = self.groq_client.chat_completions_create(
            messages=messages,
            model="llama3-8b-8192",
            temperature=0.7,
            max_tokens=1024
        )
        
        bot_response = response['choices'][0]['message']['content']
        
        # Add disclaimer in natural language
        if language == 'Urdu':
            bot_response += "\n\nیہ ایک AI اسسٹنٹ کی طرف سے فراہم کردہ عمومی طبی معلومات ہیں۔ سنگین طبی حالات کے لیے ہمیشہ کوالیفائیڈ ڈاکٹر سے مشورہ کریں۔"
        else:
            bot_response += "\n\nThis is general medical information provided by an AI assistant. Always consult qualified doctors for serious medical conditions."
        
        return bot_response
    
    def _get_enhanced_response(self, user_input, language):
        """Enhanced natural language responses without structured formatting"""
        user_input_lower = user_input.lower().strip()
        
        # For greetings
        if any(word in user_input_lower for word in ['hello', 'hi', 'hey', 'salam', 'السلام علیکم']):
            return self._format_natural_greeting(language)
        
        # Medical topics with natural responses
        if any(word in user_input_lower for word in ['heart', 'cardiac', 'chest pain', 'cholesterol', 'دل', 'سینے میں درد']):
            return self._format_natural_heart_response(language)
        
        elif any(word in user_input_lower for word in ['diabetes', 'sugar', 'glucose', 'insulin', 'ذیابیطس', 'شوگر']):
            return self._format_natural_diabetes_response(language)
        
        elif any(word in user_input_lower for word in ['blood pressure', 'hypertension', 'bp', 'بلڈ پریشر', 'ہائی بلڈ پریشر']):
            return self._format_natural_hypertension_response(language)
        
        elif any(word in user_input_lower for word in ['diet', 'nutrition', 'food', 'eating', 'غذا', 'کھانا']):
            return self._format_natural_nutrition_response(language)
        
        elif any(word in user_input_lower for word in ['emergency', 'urgent', 'help', 'ہنگامی', 'فوری']):
            return self._format_natural_emergency_response(language)
        
        elif any(word in user_input_lower for word in ['symptom', 'pain', 'fever', 'headache', 'علامت', 'درد']):
            return self._format_natural_symptoms_response(language)
        
        # Default professional response
        return self._format_natural_default_response(user_input, language)
    
    def _format_natural_greeting(self, language):
        if language == 'English':
            return """Thank you for reaching out to SehatAI. I'm here to provide you with professional medical guidance and support. 

I understand you might have health concerns or questions. Please feel free to share your specific health issue, whether it's about symptoms you're experiencing, medication questions, preventive care, or any other medical concern.

I can help with cardiovascular health, diabetes management, blood pressure control, and general wellness advice. What would you like to discuss today?

Please note: I'm an AI assistant providing general medical information. For serious conditions, always consult a healthcare professional."""
        else:
            return """سیحت اے آئی سے رابطہ کرنے کا شکریہ۔ میں آپ کو پیشہ ورانہ طبی رہنمائی اور مدد فراہم کرنے کے لیے یہاں ہوں۔

میں سمجھتا ہوں کہ آپ کے صحت کے بارے میں خدشات یا سوالات ہو سکتے ہیں۔ براہ کرم اپنا مخصوص صحت کا مسئلہ شیئر کریں، چاہے وہ علامات ہوں جو آپ محسوس کر رہے ہیں، دوائیوں کے سوالات، احتیاطی دیکھ بھال، یا کوئی اور طبی تشویش ہو۔

میں قلبی صحت، ذیابیطس کا انتظام، بلڈ پریشر کنٹرول، اور عام صحت کے مشوروں میں مدد کر سکتا ہوں۔ آج آپ کیا زیر بحث لانا چاہیں گے؟

براہ کرم نوٹ کریں: میں ایک AI اسسٹنٹ ہوں جو عمومی طبی معلومات فراہم کرتا ہوں۔ سنگین حالات کے لیے، ہمیشہ ہیلتھ کیئر پروفیشنل سے مشورہ کریں۔"""
    
    def _format_natural_heart_response(self, language):
        if language == 'English':
            return """When it comes to heart health, it's important to be proactive about monitoring your cardiovascular system. Common symptoms that warrant attention include chest discomfort or pain, shortness of breath especially during physical activity, pain that radiates to your arms, neck, or jaw, unexplained nausea, persistent fatigue, and feelings of dizziness.

Several factors can increase your risk of heart issues, including elevated blood pressure, high cholesterol levels, tobacco use, diabetes, excess weight, family history of heart disease, and sedentary lifestyle habits.

For prevention, I recommend focusing on a heart-healthy diet that's low in saturated fats, engaging in regular physical activity for about 30 minutes daily, completely avoiding tobacco products, maintaining a healthy weight through balanced nutrition, developing effective stress management techniques, and scheduling regular health check-ups.

It's crucial to recognize emergency warning signs such as severe crushing chest pain, significant difficulty breathing, fainting episodes, rapid or irregular heartbeat, and pain that spreads to your shoulders or arms. If you experience any of these symptoms, seek immediate medical attention.

For ongoing monitoring, I suggest regular blood pressure checks, comprehensive lipid profiles every 6 to 12 months, electrocardiograms when symptoms are present, and stress testing as recommended by your healthcare provider based on your individual risk factors."""
        else:
            return """دل کی صحت کے معاملے میں، اپنے قلبی نظام کی نگرانی کے بارے میں پیشگی اقدامات کرنا بہت ضروری ہے۔ عام علامات جن پر توجہ دینے کی ضرورت ہوتی ہے ان میں سینے میں بے چینی یا درد، خاص طور پر جسمانی سرگرمی کے دوران سانس لینے میں دشواری، آپ کے بازوؤں، گردن یا جبڑے میں پھیلنے والا درد، بے وجہ متلی، مسلسل تھکاوٹ، اور چکر آنے کے احساسات شامل ہیں۔

کئی عوامل دل کے مسائل کے خطرے کو بڑھا سکتے ہیں، جن میں بلند بلڈ پریشر، ہائی کولیسٹرول کی سطح، تمباکو کا استعمال، ذیابیطس، زیادہ وزن، دل کی بیماری کی خاندانی تاریخ، اور بیٹھے رہنے کی عادات شامل ہیں۔

روک تھام کے لیے، میں سیر شدہ چکنائیوں سے پاک دل کے لیے صحت مند غذا پر توجہ مرکوز کرنے، روزانہ تقریباً 30 منٹ تک باقاعدہ جسمانی سرگرمی میں مشغول رہنے، تمباکو کی مصنوعات سے مکمل پرہیز کرنے، متوازن غذائیت کے ذریعے صحت مند وزن برقرار رکھنے، مؤثر تناؤ انتظام کی تکنیکیں تیار کرنے، اور باقاعدہ صحت کی جانچ پڑتال کی سفارش کرتا ہوں۔

ہنگامی انتباہی علامات کو پہچاننا بہت ضروری ہے جیسے کہ شدید کچلنے والا سینے کا درد، سانس لینے میں نمایاں دشواری، بیہوشی کے دورے، تیز یا بے ترتیب دل کی دھڑکن، اور درد جو آپ کے کندھوں یا بازوؤں میں پھیل جاتا ہو۔ اگر آپ ان میں سے کوئی بھی علامت محسوس کرتے ہیں، تو فوری طبی امداد حاصل کریں۔

جاری نگرانی کے لیے، میں باقاعدہ بلڈ پریشر چیک، ہر 6 سے 12 ماہ میں جامع لپڈ پروفائل، علامات موجود ہونے پر الیکٹروکارڈیوگرام، اور آپ کے ہیلتھ کیئر فراہم کنندہ کی طرف سے آپ کے انفرادی خطرے کے عوامل کی بنیاد پر سفارش کردہ اسٹریس ٹیسٹنگ کی تجویز کرتا ہوں۔"""
    
    def _format_natural_diabetes_response(self, language):
        if language == 'English':
            return """Diabetes management requires careful attention to both lifestyle factors and medical monitoring. Common symptoms that might indicate diabetes include increased thirst and hunger, frequent urination especially at night, persistent fatigue that doesn't improve with rest, blurred vision that comes and goes, slow healing of cuts and wounds, and unexplained weight loss despite normal eating habits.

Key risk factors to be aware of include family history of diabetes, being overweight particularly with a BMI over 25, existing high blood pressure, physical inactivity, age over 45 years, and history of gestational diabetes during pregnancy.

For effective diabetes management, I recommend adopting a balanced diet with controlled carbohydrate intake, engaging in regular physical activity that combines both aerobic and resistance training, maintaining a healthy weight through proper nutrition, regular blood sugar monitoring to track patterns, and comprehensive health screenings including eye and foot examinations.

It's essential to recognize diabetic emergencies such as blood sugar levels above 300 mg/dL or below 70 mg/dL, confusion or disorientation, fruity-smelling breath indicating ketoacidosis, rapid deep breathing, and loss of consciousness. These situations require immediate medical attention.

For optimal diabetes control, aim for fasting glucose levels between 80-130 mg/dL, post-meal readings below 180 mg/dL, and individualized HbA1c targets typically below 7%. Regular ophthalmologic exams and annual foot assessments are crucial for preventing complications."""
        else:
            return """ذیابیطس کے انتظام کے لیے طرز زندگی کے عوامل اور طبی نگرانی دونوں پر احتیاط سے توجہ دینے کی ضرورت ہوتی ہے۔ عام علامات جو ذیابیطس کی نشاندہی کر سکتی ہیں ان میں پیاس اور بھوک میں اضافہ، خاص طور پر رات کے وقت بار بار پیشاب آنا، مسلسل تھکاوٹ جو آرام سے بہتر نہ ہو، آتی جاتی دھندلی نظر، کٹوں اور زخموں کا دیر سے بھرنا، اور عام کھانے کی عادات کے باوجود بے وجہ وزن میں کمی شامل ہیں۔

ذیابیطس کے اہم خطرے کے عوامل جن سے آگاہ رہنا ضروری ہے ان میں ذیابیطس کی خاندانی تاریخ، زیادہ وزن خاص طور پر 25 سے زیادہ BMI والے، موجودہ ہائی بلڈ پریشر، جسمانی غیر فعالیت، 45 سال سے زیادہ عمر، اور حمل کے دوران gestational ذیابیطس کی تاریخ شامل ہیں۔

ذیابیطس کے مؤثر انتظام کے لیے، میں کنٹرول کاربوہائیڈریٹ انٹیک کے ساتھ متوازن غذا اپنانے، باقاعدہ جسمانی سرگرمی میں مشغول ہونے کی سفارش کرتا ہوں جو ایروبک اور مزاحمتی تربیت دونوں کو یکجا کرتی ہے، مناسب غذائیت کے ذریعے صحت مند وزن برقرار رکھتی ہے، پیٹرن کو ٹریک کرنے کے لیے باقاعدہ بلڈ شوگر مانیٹرنگ، اور آنکھوں اور پاؤں کی جانچ سمیت جامع صحت کی اسکریننگ۔

ذیابیطس کی ایمرجنسیز کو پہچاننا ضروری ہے جیسے کہ 300 mg/dL سے اوپر یا 70 mg/dL سے نیچے بلڈ شوگر کی سطح، الجھن یا بے ترتیبی، ketosis کی نشاندہی کرنے والی پھل کی سی بو والی سانس، تیز گہری سانس لینا، اور ہوش کا ضیاع۔ ان حالات میں فوری طبی توجہ کی ضرورت ہوتی ہے۔

ذیابیطس کے بہترین کنٹرول کے لیے، فاسٹنگ گلوکوز کی سطح 80-130 mg/dL، کھانے کے بعد کی ریڈنگ 180 mg/dL سے نیچے، اور انفرادی HbA1c کے ہدف کی کوشش کریں جو عام طور پر 7% سے کم ہوں۔ پیچیدگیوں کو روکنے کے لیے باقاعدہ ophthalmologic امتحانات اور سالانہ پاؤں کے جائزے بہت ضروری ہیں۔"""
    
    def _format_natural_hypertension_response(self, language):
        if language == 'English':
            return """High blood pressure often develops silently without obvious symptoms, which is why regular monitoring is crucial. When symptoms do occur, they might include persistent headaches particularly in the morning, episodes of dizziness or lightheadedness, blurred vision that comes and goes, shortness of breath during routine activities, chest discomfort or tightness, and occasional nosebleeds in some individuals.

Several factors can increase your risk of developing hypertension, including family history of high blood pressure, age over 65 years, excess body weight, high sodium intake in your diet, chronic stress, regular alcohol consumption, and tobacco use.

For effective blood pressure management, I recommend following the DASH diet which emphasizes low sodium intake, engaging in regular aerobic exercise like brisk walking or swimming, maintaining a healthy weight through balanced nutrition, practicing stress reduction techniques such as meditation or deep breathing, limiting alcohol consumption to moderate levels, and completely avoiding tobacco products.

It's vital to recognize hypertensive crisis symptoms including severe pounding headaches, chest pain or pressure, significant breathing difficulties, vision changes like blurriness or spots, confusion or difficulty thinking clearly, and seizure activity. These require immediate emergency medical care.

Understanding blood pressure classifications can help you monitor your health: normal is below 120/80 mmHg, elevated ranges from 120-129/<80 mmHg, stage 1 hypertension is 130-139/80-89 mmHg, stage 2 hypertension is 140/90 mmHg or higher, and hypertensive crisis occurs above 180/120 mmHg."""
        else:
            return """ہائی بلڈ پریشر اکثر واضح علامات کے بغیر خاموشی سے نشوونما پاتا ہے، یہی وجہ ہے کہ باقاعدہ نگرانی بہت ضروری ہے۔ جب علامات واقع ہوتی ہیں، تو ان میں مسلسل سر درد خاص طور پر صبح کے وقت، چکر آنے یا سر ہلکا ہونے کے واقعات، آتی جاتی دھندلی نظر، روزمرہ کی سرگرمیوں کے دوران سانس لینے میں دشواری، سینے میں بے چینی یا تنگی، اور کچھ افراد میں occasional نکسیر شامل ہو سکتی ہیں۔

کئی عوامل آپ کے ہائی بلڈ پریشر کے خطرے کو بڑھا سکتے ہیں، جن میں ہائی بلڈ پریشر کی خاندانی تاریخ، 65 سال سے زیادہ عمر، جسمانی وزن میں اضافہ، آپ کی غذا میں high سوڈیم انٹیک، دائمی تناؤ، باقاعدہ شراب کا استعمال، اور تمباکو کا استعمال شامل ہیں۔

بلڈ پریشر کے مؤثر انتظام کے لیے، میں ڈیش ڈائٹ کی پیروی کرنے کی سفارش کرتا ہوں جو low سوڈیم انٹیک پر زور دیتی ہے، تیز چہل قدمی یا تیراکی جیسی باقاعدہ ایروبک ورزش میں مشغول ہونا، متوازن غذائیت کے ذریعے صحت مند وزن برقرار رکھنا، مراقبہ یا گہری سانس لینے جیسی تناؤ میں کمی کی تکنیکوں پر عمل کرنا، اعتدال پسندی تک شراب کے استعمال کو محدود کرنا، اور تمباکو کی مصنوعات سے مکمل پرہیز کرنا۔

ہائی بلڈ پریشر کے بحران کی علامات کو پہچاننا بہت ضروری ہے جن میں شدید تھپتھپانے والا سر درد، سینے میں درد یا دباؤ، سانس لینے میں نمایاں دشواری، دھندلاپن یا داغوں جیسی بینائی میں تبدیلی، الجھن یا واضح طور پر سوچنے میں دشواری، اور دورے کی سرگرمی شامل ہیں۔ ان کے لیے فوری ہنگامی طبی دیکھ بھال کی ضرورت ہوتی ہے۔

بلڈ پریشر کی درجہ بندی کو سمجھنا آپ کو اپنی صحت کی نگرانی میں مدد کر سکتا ہے: نارمل 120/80 mmHg سے کم ہے، elevated 120-129/<80 mmHg کے درمیان ہوتی ہے، stage 1 ہائی بلڈ پریشر 130-139/80-89 mmHg ہے، stage 2 ہائی بلڈ پریشر 140/90 mmHg یا اس سے زیادہ ہے، اور ہائی بلڈ پریشر کا بحران 180/120 mmHg سے اوپر ہوتا ہے۔"""
    
    def _format_natural_nutrition_response(self, language):
        if language == 'English':
            return """Good nutrition forms the foundation of overall health and disease prevention. For optimal health, focus on consuming 5 to 9 servings of fruits and vegetables daily, choosing whole grains over refined carbohydrates, including lean protein sources like poultry, fish, and legumes in your meals, maintaining proper hydration with 2-3 liters of water daily, and minimizing processed foods and added sugars in your diet.

For specific health conditions, dietary adjustments can be particularly beneficial. For heart health, the Mediterranean diet rich in omega-3 fatty acids has shown excellent results. For diabetes management, controlled carbohydrate intake combined with high fiber foods helps maintain stable blood sugar levels. For hypertension, the DASH diet with less than 2300mg of sodium daily along with potassium-rich foods can significantly improve blood pressure control.

Considering cultural dietary patterns in Pakistan, I recommend choosing whole wheat chapati instead of refined flour, regularly incorporating lentils and legumes into your meals, using healthier cooking oils like canola, olive, or mustard oil, and limiting the consumption of ghee and saturated fats. These simple adjustments can make a significant difference in your long-term health outcomes."""
        else:
            return """اچھی غذائیت مجموعی صحت اور بیماریوں کی روک تھام کی بنیاد بنتی ہے۔ بہترین صحت کے لیے، روزانہ 5 سے 9 سرونگ پھل اور سبزیاں کھانے، refined کاربوہائیڈریٹس پر سارا اناج منتخب کرنے، اپنے کھانوں میں پولٹری، مچھلی، اور پھلیاں جیسے lean پروٹین کے ذرائع شامل کرنے، روزانہ 2-3 لیٹر پانی کے ساتھ مناسب ہائیڈریشن برقرار رکھنے، اور اپنی غذا میں پراسیسڈ فوڈز اور اضافی شکر کو کم سے کم کرنے پر توجہ مرکوز کریں۔

مخصوص صحت کی حالتوں کے لیے، غذائی ایڈجسٹمنٹ خاص طور پر فائدہ مند ہو سکتی ہیں۔ دل کی صحت کے لیے، اومیگا 3 فیٹی ایسڈ سے بھرپور بحیرہ روم کی غذا نے شاندار نتائج دکھائے ہیں۔ ذیابیطس کے انتظام کے لیے، کنٹرول کاربوہائیڈریٹ انٹیک high فائبر والی غذاؤں کے ساتھ مل کر stable بلڈ شوگر کی سطح برقرار رکھنے میں مدد کرتا ہے۔ ہائی بلڈ پریشر کے لیے، روزانہ 2300mg سے کم سوڈیم کے ساتھ ڈیش ڈائٹ اور پوٹاشیم سے بھرپور غذائیں بلڈ پریشر کنٹرول کو نمایاں طور پر بہتر بنا سکتی ہیں۔

پاکستان میں ثقافتی غذائی نمونوں کو مدنظر رکھتے ہوئے، میں refined آٹے کے بجائے whole wheat چپاتی منتخب کرنے، اپنے کھانوں میں باقاعدگی سے دالوں اور پھلیوں کو شامل کرنے، کینولا، زیتون، یا سرسوں کے تیل جیسے صحت مند کھانا پکانے کے تیل استعمال کرنے، اور گھی اور سیر شدہ چربی کے استعمال کو محدود کرنے کی سفارش کرتا ہوں۔ یہ سادہ ایڈجسٹمنٹ آپ کی طویل مدتی صحت کے نتائج میں نمایاں فرق لا سکتی ہیں۔"""
    
    def _format_natural_emergency_response(self, language):
        if language == 'English':
            return """IMMEDIATE MEDICAL ATTENTION REQUIRED

If you or someone you're with is experiencing a medical emergency, please act quickly and decisively. First, activate emergency medical services immediately by calling 1122 in Pakistan. Do not attempt to transport the patient to the hospital yourself, as emergency personnel can begin life-saving treatments en route.

Keep the patient in a comfortable position, preferably lying down if possible. Gather any relevant medical information such as current medications, known allergies, and existing medical conditions. Withhold all oral intake including food and water until medical professionals can assess the situation.

Emergency situations that require immediate hospital attention include acute chest pain or pressure, respiratory distress or difficulty breathing, uncontrolled bleeding, acute neurological changes like weakness or confusion, major trauma or burns, suspected poisoning or overdose, and seizure activity.

While waiting for emergency services, ensure the scene is safe for both the patient and responders. If you're trained in basic life support, provide assistance as needed. Continuously monitor vital signs like breathing and pulse. Prepare to provide emergency personnel with a clear timeline of events when they arrive.

This guidance is for emergency situations only and should not replace professional medical evaluation. Please seek immediate medical attention for any serious health concerns."""
        else:
            return """فوری طبی توجہ درکار

اگر آپ یا کوئی شخص جس کے ساتھ آپ ہیں طبی ایمرجنسی کا سامنا کر رہا ہے، تو براہ کرم فوری اور فیصلہ کن طور پر عمل کریں۔ سب سے پہلے، پاکستان میں 1122 پر فون کر کے فوری طور پر ہنگامی طبی خدمات کو چالو کریں۔ مریض کو خود ہسپتال لے جانے کی کوشش نہ کریں، کیونکہ ہنگامی عملہ راستے میں زندگی بچانے والے علاج شروع کر سکتا ہے۔

مریض کو آرام دہ پوزیشن میں رکھیں، ترجیحاً اگر ممکن ہو تو لیٹا ہوا۔ کوئی بھی متعلقہ طبی معلومات اکٹھی کریں جیسے کہ موجودہ دوائیں، معلوم الرجی، اور موجودہ طبی حالات۔ طبی پیشہ ورانہ حالات کا جائزہ لینے تک کھانے اور پانی سمیت تمام زبانی انٹیک کو روکیں۔

فوری ہسپتال کی توجہ کی ضرورت والی ہنگامی صورتحال میں شدید سینے میں درد یا دباؤ، سانس کی تکلیف یا سانس لینے میں دشواری، غیر کنٹرول خون بہنا، کمزوری یا الجھن جیسی شدید اعصابی تبدیلیاں، بڑی چوٹ یا جلنے، مشتبہ زہر یا اوور ڈوز، اور دورے کی سرگرمی شامل ہیں۔

ہنگامی خدمات کے انتظار کے دوران، یقینی بنائیں کہ منظر مریض اور رسپانڈرز دونوں کے لیے محفوظ ہے۔ اگر آپ بنیادی زندگی کی حمایت میں تربیت یافتہ ہیں، تو ضرورت کے مطابق مدد فراہم کریں۔ سانس اور نبض جیسی اہم علامات کی مسلسل نگرانی کریں۔ جب وہ آئیں گے تو ہنگامی عملہ کو واقعات کی واضح ٹائم لائن فراہم کرنے کے لیے تیار رہیں۔

یہ رہنمائی صرف ہنگامی حالات کے لیے ہے اور اسے پیشہ ورانہ طبی تشخیص کی جگہ نہیں لینی چاہیے۔ براہ کرم کسی بھی سنگین صحت کے خدشات کے لیے فوری طبی امداد حاصل کریں۔"""
    
    def _format_natural_symptoms_response(self, language):
        if language == 'English':
            return """When evaluating symptoms, it's important to understand when professional medical assessment is necessary. You should seek medical evaluation for persistent fever above 103°F that doesn't respond to fever-reducing medications, any respiratory distress or chest pain, severe abdominal pain or significant trauma, acute neurological changes like sudden weakness, confusion, or vision changes, unexplained weight loss exceeding 10% of body weight within six months, or any symptoms that persist beyond two weeks without improvement.

Certain situations require immediate emergency department attention. These include acute respiratory distress with stridor sounds, chest pain that radiates to other areas accompanied by sweating or nausea, uncontrolled bleeding from any site, sudden severe pain anywhere in the body, altered mental status or fainting episodes, and any seizure activity.

A proper clinical assessment should include comprehensive history taking to understand the symptom pattern, thorough vital signs assessment including temperature and blood pressure, systematic physical examination of affected areas, appropriate diagnostic testing based on clinical findings, and specialist referral when the condition warrants more specialized care.

Remember that symptom assessment requires professional medical evaluation for accurate diagnosis and treatment planning. While I can provide general guidance, specific symptoms should always be evaluated by a healthcare professional who can perform hands-on assessment and order appropriate tests."""
        else:
            return """علامات کا جائزہ لیتے وقت، یہ سمجھنا ضروری ہے کہ پیشہ ورانہ طبی تشخیص کب ضروری ہے۔ آپ کو طبی تشخیص کے لیے رابطہ کرنا چاہیے اگر آپ کو 103°F سے اوپر مستقل بخار ہے جو بخار کم کرنے والی دوائیوں کا جواب نہیں دیتا، کوئی بھی سانس کی تکلیف یا سینے میں درد، شدید پیٹ میں درد یا نمایاں چوٹ، اچانک کمزوری، الجھن، یا بینائی میں تبدیلی جیسی شدید اعصابی تبدیلیاں، چھ ماہ کے اندر جسمانی وزن کے 10% سے زیادہ بے وجہ وزن میں کمی، یا کوئی بھی علامات جو دو ہفتوں سے زیادہ بغیر بہتری کے برقرار رہتی ہیں۔

کچھ حالات فوری ایمرجنسی ڈیپارٹمنٹ کی توجہ کی ضرورت ہوتی ہے۔ ان میں سٹرائیڈر آوازوں کے ساتھ شدید سانس کی تکلیف، سینے میں درد جو پسینہ آنا یا متلی کے ساتھ دوسرے علاقوں میں پھیلتا ہے، کسی بھی جگہ سے غیر کنٹرول خون بہنا، جسم میں کہیں بھی اچانک شدید درد، تبدیل ذہنی حیثیت یا بیہوشی کے واقعات، اور کوئی بھی دورے کی سرگرمی شامل ہیں۔

ایک مناسب کلینیکل تشخیص میں علامت کے پیٹرن کو سمجھنے کے لیے جامع تاریخ لینا، درجہ حرارت اور بلڈ پریشر سمیت اہم علامات کی مکمل تشخیص، متاثرہ علاقوں کا نظامی جسمانی معائنہ، کلینیکل نتائج کی بنیاد پر مناسب تشخیصی ٹیسٹنگ، اور ماہر کی رجوع کرنا شامل ہونا چاہیے جب حالت زیادہ خصوصی دیکھ بھال کی warrent کرتی ہے۔

یاد رکھیں کہ علامات کی تشخیص کے لیے درست تشخیص اور علاج کی منصوبہ بندی کے لیے پیشہ ورانہ طبی تشخیص کی ضرورت ہوتی ہے۔ اگرچہ میں عمومی رہنمائی فراہم کر سکتا ہوں، مخصوص علامات کی ہمیشہ ہیلتھ کیئر پروفیشنل کے ذریعے تشخیص کی جانی چاہیے جو hands-on تشخیص کر سکتا ہے اور مناسب ٹیسٹوں کا حکم دے سکتا ہے۔"""
    
    def _format_natural_default_response(self, user_input, language):
        if language == 'English':
            return f"""I understand you're asking about: "{user_input}"

As your medical AI assistant, I'm here to provide professional healthcare guidance across various medical domains. I can help you with cardiovascular health assessments, diabetes management strategies, blood pressure monitoring, symptom evaluation, medication questions, and general wellness advice.

Could you please provide more specific details about your health concern? The more information you share about your symptoms, medical history, or specific questions, the better I can assist you with tailored medical guidance.

I specialize in providing evidence-based information about heart conditions, diabetes care, hypertension management, nutrition, exercise recommendations, and when to seek emergency care. Please feel free to ask me any specific health-related questions you might have.

Remember that while I can provide comprehensive medical information, serious health concerns should always be evaluated by qualified healthcare professionals who can provide personalized care based on direct examination."""
        else:
            return f"""میں سمجھتا ہوں کہ آپ پوچھ رہے ہیں: "{user_input}"

آپ کے میڈیکل AI اسسٹنٹ کے طور پر، میں مختلف طبی شعبوں میں پیشہ ورانہ ہیلتھ کیئر رہنمائی فراہم کرنے کے لیے یہاں ہوں۔ میں آپ کی قلبی صحت کی تشخیص، ذیابیطس مینجمنٹ کی حکمت عملی، بلڈ پریشر مانیٹرنگ، علامات کی تشخیص، دوائیوں کے سوالات، اور عام صحت کے مشوروں میں مدد کر سکتا ہوں۔

کیا آپ براہ کرم اپنے صحت کے مسئلے کے بارے میں مزید مخصوص تفصیلات فراہم کر سکتے ہیں؟ آپ اپنی علامات، طبی تاریخ، یا مخصوص سوالات کے بارے میں جتنی زیادہ معلومات شیئر کریں گے، میں آپ کی حسب ضرورت طبی رہنمائی کے ساتھ اتنی ہی بہتر مدد کر سکتا ہوں۔

میں دل کی حالتوں، ذیابیطس کی دیکھ بھال، ہائی بلڈ پریشر مینجمنٹ، غذائیت، ورزش کی سفارشات، اور ہنگامی دیکھ بھال کے وقت کے بارے میں evidence-based معلومات فراہم کرنے میں مہارت رکھتا ہوں۔ براہ کرم مجھ سے اپنے کسی بھی مخصوص صحت سے متعلق سوالات پوچھنے میں آزاد محسوس کریں۔

یاد رکھیں کہ اگرچہ میں جامع طبی معلومات فراہم کر سکتا ہوں، سنگین صحت کے خدشات کی ہمیشہ کوالیفائیڈ ہیلتھ کیئر پروفیشنلز کے ذریعے تشخیص کی جانی چاہیے جو براہ راست معائنہ کی بنیاد پر ذاتی نوعیت کی دیکھ بھال فراہم کر سکتے ہیں۔"""

class PDFReportGenerator:
    def __init__(self):
        self.pdf = FPDF()
        self.pdf.set_auto_page_break(auto=True, margin=15)
        
    def generate_report(self, patient_data, risk_scores, language='English'):
        self.pdf.add_page()
        
        # Title
        self.pdf.set_font('Arial', 'B', 16)
        if language == 'English':
            self.pdf.cell(0, 10, 'SEHATAI MEDICAL ASSESSMENT REPORT', 0, 1, 'C')
        else:
            self.pdf.cell(0, 10, 'SEHATAI MEDICAL ASSESSMENT REPORT', 0, 1, 'C')
        
        self.pdf.ln(10)
        
        # Patient Information
        self.pdf.set_font('Arial', 'B', 12)
        self.pdf.cell(0, 10, 'Patient Information:', 0, 1)
        
        self.pdf.set_font('Arial', '', 10)
        patient_info = [
            f"Name: {self._safe_encode(patient_data.get('name', 'Not provided'))}",
            f"Age: {patient_data.get('age', 'Not provided')} years",
            f"Gender: {self._safe_encode(patient_data.get('gender', 'Not provided'))}",
            f"Contact: {self._safe_encode(patient_data.get('contact', 'Not provided'))}"
        ]
        
        for info in patient_info:
            self.pdf.cell(0, 8, info, 0, 1)
        
        self.pdf.ln(5)
        
        # Clinical Parameters
        self.pdf.set_font('Arial', 'B', 12)
        self.pdf.cell(0, 10, 'Clinical Parameters:', 0, 1)
        
        self.pdf.set_font('Arial', '', 10)
        clinical_info = [
            f"Blood Pressure: {patient_data.get('bp_systolic', 'N/A')}/{patient_data.get('bp_diastolic', 'N/A')} mmHg",
            f"Heart Rate: {patient_data.get('heart_rate', 'N/A')} bpm",
            f"Cholesterol: {patient_data.get('cholesterol', 'N/A')} mg/dL",
            f"Glucose: {patient_data.get('glucose', 'N/A')} mg/dL",
            f"BMI: {patient_data.get('bmi', 'N/A')}"
        ]
        
        for info in clinical_info:
            self.pdf.cell(0, 8, info, 0, 1)
        
        self.pdf.ln(5)
        
        # Symptoms
        self.pdf.set_font('Arial', 'B', 12)
        self.pdf.cell(0, 10, 'Reported Symptoms:', 0, 1)
        
        self.pdf.set_font('Arial', '', 10)
        symptoms = patient_data.get('symptoms', {})
        symptom_list = [
            f"Chest Pain: {'Yes' if symptoms.get('chest_pain') else 'No'}",
            f"Shortness of Breath: {'Yes' if symptoms.get('shortness_breath') else 'No'}",
            f"Palpitations: {'Yes' if symptoms.get('palpitations') else 'No'}",
            f"Fatigue: {'Yes' if symptoms.get('fatigue') else 'No'}",
            f"Dizziness: {'Yes' if symptoms.get('dizziness') else 'No'}",
            f"Blurred Vision: {'Yes' if symptoms.get('blurred_vision') else 'No'}"
        ]
        
        for symptom in symptom_list:
            self.pdf.cell(0, 8, symptom, 0, 1)
        
        self.pdf.ln(5)
        
        # Risk Assessment
        self.pdf.set_font('Arial', 'B', 12)
        self.pdf.cell(0, 10, 'Risk Assessment Results:', 0, 1)
        
        self.pdf.set_font('Arial', '', 10)
        risk_info = [
            f"Heart Disease Risk: {risk_scores.get('heart', 0):.1%}",
            f"Diabetes Risk: {risk_scores.get('diabetes', 0):.1%}",
            f"Hypertension Risk: {risk_scores.get('hypertension', 0):.1%}",
            f"Overall Priority Score: {risk_scores.get('priority', 0):.1%}"
        ]
        
        for info in risk_info:
            self.pdf.cell(0, 8, info, 0, 1)
        
        self.pdf.ln(5)
        
        # Recommendation
        self.pdf.set_font('Arial', 'B', 12)
        self.pdf.cell(0, 10, 'Clinical Recommendation:', 0, 1)
        
        self.pdf.set_font('Arial', '', 10)
        recommendation = self._safe_encode(risk_scores.get('recommendation', 'No recommendation available'))
        self.pdf.multi_cell(0, 8, recommendation)
        
        self.pdf.ln(10)
        
        # Footer
        self.pdf.set_font('Arial', 'I', 8)
        self.pdf.cell(0, 10, f'Generated by SehatAI on: {datetime.now().strftime("%Y-%m-%d %H:%M")}', 0, 1, 'C')
        
        # Return the PDF as bytes
        return self.pdf.output()
    
    def _safe_encode(self, text):
        """Safely encode text for PDF generation"""
        if text is None:
            return ""
        try:
            return str(text)
        except:
            return "Encoding error"

# Load ML models with enhanced error handling
@st.cache_resource(show_spinner=False)
def load_models():
    models = {}
    
    # Try multiple approaches to load models
    model_files = {
        'heart': ['heart_model.pkl', 'heart_disease_model.pkl', 'models/heart_model.pkl'],
        'diabetes': ['diabetes_model.pkl', 'diabetes_model.pkl', 'models/diabetes_model.pkl'],
        'hypertension': ['hypertension_model.pkl', 'models/hypertension_model.pkl']
    }
    
    def try_load_model(model_name, file_list):
        for file_path in file_list:
            if os.path.exists(file_path):
                try:
                    model = joblib.load(file_path)
                    return model
                except Exception as e:
                    continue
        return None
    
    models['heart'] = try_load_model("Heart Disease", model_files['heart'])
    models['diabetes'] = try_load_model("Diabetes", model_files['diabetes'])
    models['hypertension'] = try_load_model("Hypertension", model_files['hypertension'])
    
    return models

def calculate_priority_score(heart_risk, diabetes_risk, hypertension_risk):
    """Calculate integrated priority score with clinical weighting"""
    # Clinical severity weighting
    priority = (
        heart_risk * 0.45 +      # Highest weight for cardiac issues
        diabetes_risk * 0.25 +   # Medium weight for diabetes
        hypertension_risk * 0.30 # Medium weight for hypertension
    )
    
    return min(1.0, priority)  # Cap at 1.0

def get_priority_recommendation(priority_score, language='English'):
    """Get priority-based recommendation with clinical thresholds"""
    if priority_score >= 0.75:
        if language == 'Urdu':
            return "EMERGENCY_CARE", "اعلی ترجیح - فوری ہنگامی علاج کی ضرورت", "risk-high"
        else:
            return "EMERGENCY_CARE", "High Priority - Immediate Emergency Care Required", "risk-high"
    elif priority_score >= 0.55:
        if language == 'Urdu':
            return "SAME_DAY_CONSULT", "درمیانی ترجیح - اسی دن مشورہ ضروری", "risk-medium"
        else:
            return "SAME_DAY_CONSULT", "Medium Priority - Same Day Consultation Required", "risk-medium"
    else:
        if language == 'Urdu':
            return "ROUTINE_APPOINTMENT", "کم ترجیح - روٹین اپائنٹمنٹ", "risk-low"
        else:
            return "ROUTINE_APPOINTMENT", "Low Priority - Routine Appointment", "risk-low"

def validate_patient_data(age, bp_systolic, bp_diastolic, heart_rate):
    """Validate patient data for realistic clinical values"""
    errors = []
    
    if age < 1 or age > 120:
        errors.append("Age must be between 1 and 120 years")
    if bp_systolic < 70 or bp_systolic > 250:
        errors.append("Systolic BP must be between 70 and 250 mmHg")
    if bp_diastolic < 40 or bp_diastolic > 150:
        errors.append("Diastolic BP must be between 40 and 150 mmHg")
    if heart_rate < 30 or heart_rate > 200:
        errors.append("Heart rate must be between 30 and 200 bpm")
    
    return errors

def predict_with_models(age, bp_systolic, bp_diastolic, heart_rate, cholesterol, glucose, bmi, symptoms, models):
    """Predict risks using loaded ML models with fallback to rule-based"""
    heart_risk, diabetes_risk, hypertension_risk = 0.0, 0.0, 0.0
    
    # Heart disease prediction
    if models.get('heart') is not None:
        try:
            heart_features = np.array([[
                age, bp_systolic, cholesterol, heart_rate,
                symptoms['chest_pain'], symptoms['shortness_breath'], 
                symptoms['palpitations'], bmi, glucose
            ]])
            heart_risk = models['heart'].predict_proba(heart_features)[0][1]
        except Exception as e:
            heart_risk = predict_risk_rule_based_heart(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
    else:
        heart_risk = predict_risk_rule_based_heart(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
    
    # Diabetes prediction
    if models.get('diabetes') is not None:
        try:
            diabetes_features = np.array([[
                age, glucose, bmi, cholesterol,
                symptoms['fatigue'], symptoms['blurred_vision'],
                bp_systolic, heart_rate
            ]])
            diabetes_risk = models['diabetes'].predict_proba(diabetes_features)[0][1]
        except Exception as e:
            diabetes_risk = predict_risk_rule_based_diabetes(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
    else:
        diabetes_risk = predict_risk_rule_based_diabetes(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
    
    # Hypertension prediction
    if models.get('hypertension') is not None:
        try:
            hypertension_features = np.array([[
                age, bp_systolic, bp_diastolic, bmi,
                symptoms['dizziness'], symptoms['palpitations'],
                heart_rate, cholesterol
            ]])
            hypertension_risk = models['hypertension'].predict_proba(hypertension_features)[0][1]
        except Exception as e:
            hypertension_risk = predict_risk_rule_based_hypertension(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
    else:
        hypertension_risk = predict_risk_rule_based_hypertension(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
    
    return heart_risk, diabetes_risk, hypertension_risk

def predict_risk_rule_based_heart(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms):
    """Advanced rule-based heart risk prediction"""
    risk = 0.0
    
    # Age factor
    if age > 60: risk += 0.25
    elif age > 45: risk += 0.15
    elif age > 30: risk += 0.05
    
    # Blood pressure factor
    if bp_systolic > 180 or bp_diastolic > 120: risk += 0.30
    elif bp_systolic > 140 or bp_diastolic > 90: risk += 0.20
    elif bp_systolic > 130 or bp_diastolic > 85: risk += 0.10
    
    # Cholesterol factor
    if cholesterol > 240: risk += 0.20
    elif cholesterol > 200: risk += 0.10
    
    # BMI factor
    if bmi > 35: risk += 0.15
    elif bmi > 30: risk += 0.10
    elif bmi > 25: risk += 0.05
    
    # Glucose factor
    if glucose > 200: risk += 0.10
    elif glucose > 126: risk += 0.05
    
    # Symptom factors
    if symptoms['chest_pain']: risk += 0.25
    if symptoms['shortness_breath']: risk += 0.15
    if symptoms['palpitations']: risk += 0.10
    
    return min(0.95, max(0.05, risk))

def predict_risk_rule_based_diabetes(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms):
    """Advanced rule-based diabetes risk prediction"""
    risk = 0.0
    
    # Age factor
    if age > 50: risk += 0.20
    elif age > 40: risk += 0.10
    elif age > 30: risk += 0.05
    
    # Glucose factor (most important)
    if glucose > 200: risk += 0.40
    elif glucose > 126: risk += 0.30
    elif glucose > 100: risk += 0.15
    
    # BMI factor
    if bmi > 35: risk += 0.25
    elif bmi > 30: risk += 0.15
    elif bmi > 25: risk += 0.08
    
    # Blood pressure factor
    if bp_systolic > 140 or bp_diastolic > 90: risk += 0.10
    
    # Symptom factors
    if symptoms['fatigue']: risk += 0.10
    if symptoms['blurred_vision']: risk += 0.08
    
    return min(0.95, max(0.05, risk))

def predict_risk_rule_based_hypertension(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms):
    """Advanced rule-based hypertension risk prediction"""
    risk = 0.0
    
    # Blood pressure factor (most important)
    if bp_systolic > 180 or bp_diastolic > 120: risk += 0.50
    elif bp_systolic > 140 or bp_diastolic > 90: risk += 0.35
    elif bp_systolic > 130 or bp_diastolic > 85: risk += 0.20
    
    # Age factor
    if age > 60: risk += 0.15
    elif age > 45: risk += 0.08
    
    # BMI factor
    if bmi > 30: risk += 0.15
    elif bmi > 25: risk += 0.08
    
    # Symptom factors
    if symptoms['dizziness']: risk += 0.10
    if symptoms['palpitations']: risk += 0.08
    
    return min(0.95, max(0.05, risk))

def create_download_link(pdf_bytes, filename, text):
    """Create a download link for PDF"""
    b64 = base64.b64encode(pdf_bytes).decode()
    href = f'<a href="data:application/octet-stream;base64,{b64}" download="{filename}">{text}</a>'
    return href

def main():
    # Load custom CSS
    local_css()
    init_session_state()
    
    # Load ML models in background without showing messages
    if not st.session_state.models_loaded:
        with st.spinner("🔄 Loading AI models..."):
            models = load_models()
            st.session_state.models = models
            st.session_state.models_loaded = True
    
    models = st.session_state.models
    
    # Language selector at top right with Pakistan flag colors
    col_lang, col_space = st.columns([1, 5])
    with col_lang:
        st.markdown('<div class="pakistan-flag">🇵🇰</div>', unsafe_allow_html=True)
        language = st.selectbox("Language", ["English", "Urdu"], key="language_selector", label_visibility="collapsed")
        st.session_state.current_language = language
    
    # Main header with new name
    st.markdown('<h1 class="main-header">🏥 SehatAI</h1>', unsafe_allow_html=True)
    if language == "English":
        st.markdown('<h3 style="text-align: center; color: #00612A; margin-bottom: 20px;">Smart Healthcare Triage & Risk Assessment System</h3>', unsafe_allow_html=True)
    else:
        st.markdown('<h3 style="text-align: center; color: #00612A; margin-bottom: 20px;">ذہین ہیلتھ کیئر ٹریج اور خطرے کی تشخیص کا نظام</h3>', unsafe_allow_html=True)
    
    # Display random healthcare quote
    import random
    quote = random.choice(HEALTHCARE_QUOTES)
    
    st.markdown(f'''
    <div class="quote-section">
        <div class="quote-text">"{quote['english']}"</div>
        <div class="quote-text">"{quote['urdu']}"</div>
        <div class="quote-author">- {quote['author']}</div>
    </div>
    ''', unsafe_allow_html=True)
    
    # Create tabs
    if language == "English":
        tab_names = ["Patient Assessment", "Health Assistant", "Medical Reports"]
    else:
        tab_names = ["مریض تشخیص", "ہیلتھ اسسٹنٹ", "طبی رپورٹس"]
    
    tab1, tab2, tab3 = st.tabs(tab_names)
    
    with tab1:
        # Patient Assessment Form
        st.markdown('<div class="section-container">', unsafe_allow_html=True)
        
        if language == "English":
            st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">👨‍⚕️ Comprehensive Patient Assessment</h2>', unsafe_allow_html=True)
            st.write("Complete the following form for comprehensive patient risk assessment and priority scoring")
        else:
            st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">👨‍⚕️ جامع مریض تشخیص</h2>', unsafe_allow_html=True)
            st.write("جامع مریض کے خطرے کی تشخیص اور ترجیحی اسکورنگ کے لیے درج ذیل فارم کو مکمل کریں")
        
        with st.form("patient_assessment_form"):
            col1, col2 = st.columns(2)
            
            with col1:
                # Basic Information
                if language == "English":
                    st.subheader("Personal Information")
                    name = st.text_input("Full Name", placeholder="Enter patient's full name")
                    age = st.number_input("Age", min_value=1, max_value=120, value=45, 
                                        help="Patient's age in years")
                    gender = st.selectbox("Gender", ["Male", "Female", "Other"])
                    contact = st.text_input("Contact Number", placeholder="03XX-XXXXXXX")
                else:
                    st.subheader("ذاتی معلومات")
                    name = st.text_input("مکمل نام", placeholder="مریض کا مکمل نام درج کریں")
                    age = st.number_input("عمر", min_value=1, max_value=120, value=45,
                                        help="مریض کی عمر سالوں میں")
                    gender = st.selectbox("جنس", ["مرد", "عورت", 'دیگر'])
                    contact = st.text_input("رابطہ نمبر", placeholder="03XX-XXXXXXX")
            
            with col2:
                # Vital Signs
                if language == "English":
                    st.subheader("Clinical Parameters")
                    bp_systolic = st.slider("Blood Pressure (systolic)", 
                                          min_value=70, max_value=250, value=120,
                                          help="Systolic blood pressure in mmHg")
                    bp_diastolic = st.slider("Blood Pressure (diastolic)", 
                                           min_value=40, max_value=150, value=80,
                                          help="Diastolic blood pressure in mmHg")
                    heart_rate = st.slider("Heart Rate (bpm)", 
                                         min_value=30, max_value=200, value=72,
                                         help="Heart beats per minute")
                    cholesterol = st.slider("Cholesterol Level (mg/dL)", 
                                          min_value=100, max_value=400, value=180)
                    glucose = st.slider("Blood Glucose (mg/dL)", 
                                      min_value=50, max_value=500, value=95)
                    bmi = st.slider("BMI", min_value=15.0, max_value=40.0, value=23.5, step=0.1)
                else:
                    st.subheader("کلینیکل پیرامیٹرز")
                    bp_systolic = st.slider("بلڈ پریشر (سسٹولک)", 
                                          min_value=70, max_value=250, value=120,
                                          help="سسٹولک بلڈ پریشر mmHg میں")
                    bp_diastolic = st.slider("بلڈ پریشر (ڈائیسٹولک)", 
                                           min_value=40, max_value=150, value=80,
                                          help="ڈائیسٹولک بلڈ پریشر mmHg میں")
                    heart_rate = st.slider("دل کی دھڑکن (bpm)", 
                                         min_value=30, max_value=200, value=72,
                                         help="دل کی دھڑکن فی منٹ")
                    cholesterol = st.slider("کولیسٹرول کی سطح (mg/dL)", 
                                          min_value=100, max_value=400, value=180)
                    glucose = st.slider("خون میں گلوکوز (mg/dL)", 
                                      min_value=50, max_value=500, value=95)
                    bmi = st.slider("باڈی ماس انڈیکس", min_value=15.0, max_value=40.0, value=23.5, step=0.1)
            
            # Symptoms Section
            if language == "English":
                st.subheader("Reported Symptoms")
                col3, col4 = st.columns(2)
                with col3:
                    chest_pain = st.checkbox("Chest Pain or Discomfort")
                    shortness_breath = st.checkbox("Shortness of Breath")
                    palpitations = st.checkbox("Heart Palpitations")
                with col4:
                    fatigue = st.checkbox("Persistent Fatigue")
                    dizziness = st.checkbox("Dizziness or Lightheadedness")
                    blurred_vision = st.checkbox("Blurred Vision")
            else:
                st.subheader("رپورٹ کردہ علامات")
                col3, col4 = st.columns(2)
                with col3:
                    chest_pain = st.checkbox("سینے میں درد یا بے چینی")
                    shortness_breath = st.checkbox("سانس لینے میں دشواری")
                    palpitations = st.checkbox("دل کی دھڑکن میں اضافہ")
                with col4:
                    fatigue = st.checkbox("مسلسل تھکاوٹ")
                    dizziness = st.checkbox("چکر آنا یا سر ہلکا محسوس ہونا")
                    blurred_vision = st.checkbox("دھندلا نظر آنا")
            
            # Assessment Button
            if language == "English":
                assess_button = st.form_submit_button("🚀 Calculate Risk Score & Priority", 
                                                    use_container_width=True)
            else:
                assess_button = st.form_submit_button("🚀 خطرے کا اسکور اور ترجیح معلوم کریں", 
                                                    use_container_width=True)
            
            if assess_button:
                # Validate inputs
                validation_errors = validate_patient_data(age, bp_systolic, bp_diastolic, heart_rate)
                
                if validation_errors:
                    for error in validation_errors:
                        st.error(f"❌ {error}")
                else:
                    try:
                        with st.spinner("🔍 Analyzing patient data and calculating risks..."):
                            # Prepare symptoms dictionary
                            symptoms_dict = {
                                'chest_pain': chest_pain,
                                'shortness_breath': shortness_breath,
                                'palpitations': palpitations,
                                'fatigue': fatigue,
                                'dizziness': dizziness,
                                'blurred_vision': blurred_vision
                            }
                            
                            # Store patient data
                            st.session_state.patient_data = {
                                'name': name,
                                'age': age,
                                'gender': gender,
                                'contact': contact,
                                'bp_systolic': bp_systolic,
                                'bp_diastolic': bp_diastolic,
                                'heart_rate': heart_rate,
                                'cholesterol': cholesterol,
                                'glucose': glucose,
                                'bmi': bmi,
                                'symptoms': symptoms_dict
                            }
                            
                            # Predict risks using ML models
                            heart_risk, diabetes_risk, hypertension_risk = predict_with_models(
                                age, bp_systolic, bp_diastolic, heart_rate, 
                                cholesterol, glucose, bmi, symptoms_dict, models
                            )
                            
                            # Calculate integrated priority score
                            priority_score = calculate_priority_score(
                                heart_risk, diabetes_risk, hypertension_risk
                            )
                            
                            priority_level, recommendation, risk_class = get_priority_recommendation(
                                priority_score, language
                            )
                            
                            # Store results
                            st.session_state.risk_scores = {
                                'heart': heart_risk,
                                'diabetes': diabetes_risk,
                                'hypertension': hypertension_risk,
                                'priority': priority_score,
                                'recommendation': recommendation,
                                'level': priority_level
                            }
                            
                            # Add to assessment history
                            st.session_state.assessment_history.append({
                                'timestamp': datetime.now(),
                                'patient_data': st.session_state.patient_data.copy(),
                                'risk_scores': st.session_state.risk_scores.copy()
                            })
                        
                        # Display results
                        st.markdown("---")
                        st.success("✅ Risk assessment completed successfully!")
                        
                        # Risk Scores Visualization
                        if language == "English":
                            st.subheader("📊 Disease Risk Assessment Dashboard")
                        else:
                            st.subheader("📊 بیماری کے خطرے کی تشخیص ڈیش بورڈ")
                        
                        col5, col6, col7, col8 = st.columns(4)
                        
                        risk_metrics = [
                            (heart_risk, "Heart Disease", "❤️", "#FF6B6B"),
                            (diabetes_risk, "Diabetes", "🩺", "#4ECDC4"),
                            (hypertension_risk, "Hypertension", "💓", "#45B7D1"),
                            (priority_score, "Priority Score", "🎯", "#96CEB4")
                        ]
                        
                        for (value, title, emoji, color), col in zip(risk_metrics, [col5, col6, col7, col8]):
                            with col:
                                fig = go.Figure(go.Indicator(
                                    mode = "gauge+number+delta",
                                    value = value,
                                    domain = {'x': [0, 1], 'y': [0, 1]},
                                    title = {'text': f"{emoji} {title}", 'font': {'size': 14}},
                                    gauge = {
                                        'axis': {'range': [0, 1], 'tickwidth': 1},
                                        'bar': {'color': color},
                                        'steps': [
                                            {'range': [0, 0.3], 'color': "lightgreen"},
                                            {'range': [0.3, 0.7], 'color': "yellow"},
                                            {'range': [0.7, 1], 'color': "red"}
                                        ],
                                        'threshold': {
                                            'line': {'color': "black", 'width': 4},
                                            'thickness': 0.75,
                                            'value': 0.7
                                        }
                                    }
                                ))
                                fig.update_layout(height=250, margin=dict(l=10, r=10, t=50, b=10))
                                st.plotly_chart(fig, use_container_width=True)
                        
                        # Priority Recommendation
                        st.markdown(f'<div class="priority-box {risk_class}">', unsafe_allow_html=True)
                        if language == "English":
                            st.markdown(f"## 🎯 Clinical Priority Recommendation")
                            st.markdown(f"### {recommendation}")
                            st.markdown(f"**Overall Risk Score:** `{priority_score:.3f}`")
                            st.markdown(f"**Recommended Action:** `{priority_level.replace('_', ' ').title()}`")
                            
                            # Additional clinical guidance
                            if priority_level == "EMERGENCY_CARE":
                                st.warning("🚨 **Immediate Action Required:** Patient should be directed to emergency department without delay.")
                            elif priority_level == "SAME_DAY_CONSULT":
                                st.info("ℹ️ **Urgent Consultation:** Schedule appointment within 24 hours.")
                            else:
                                st.success("✅ **Routine Care:** Schedule within regular appointment system.")
                                
                        else:
                            st.markdown(f"## 🎯 کلینیکل ترجیحی سفارش")
                            st.markdown(f"### {recommendation}")
                            st.markdown(f"**کل خطرے کا اسکور:** `{priority_score:.3f}`")
                            st.markdown(f"**سفارش کردہ عمل:** `{priority_level.replace('_', ' ').title()}`")
                            
                            if priority_level == "EMERGENCY_CARE":
                                st.warning("🚨 **فوری کارروائی ضروری:** مریض کو بغیر کسی تاخیر کے ایمرجنسی ڈیپارٹمنٹ بھیجا جائے۔")
                            elif priority_level == "SAME_DAY_CONSULT":
                                st.info("ℹ️ **فوری مشاورت:** 24 گھنٹے کے اندر اپائنٹمنٹ شیڈول کریں۔")
                            else:
                                st.success("✅ **روٹین کیئر:** معمول کی اپائنٹمنٹ سسٹم کے اندر شیڈول کریں۔")
                                
                        st.markdown('</div>', unsafe_allow_html=True)
                            
                    except Exception as e:
                        st.error(f"❌ Error in risk assessment: {str(e)}")
        
        st.markdown('</div>', unsafe_allow_html=True)
    
    with tab2:
        # Healthcare Chatbot
        st.markdown('<div class="section-container">', unsafe_allow_html=True)
        
        if language == "English":
            st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">💬 SehatAI Health Assistant</h2>', unsafe_allow_html=True)
            st.write("Ask health-related questions and get instant, reliable medical information")
        else:
            st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">💬 سیحت اے آئی ہیلتھ اسسٹنٹ</h2>', unsafe_allow_html=True)
            st.write("صحت سے متعلق سوالات پوچھیں اور فوری، قابل اعتماد طبی معلومات حاصل کریں")
        
        # Groq API Configuration
        groq_api_key = st.secrets.get("GROQ_API_KEY", "") if hasattr(st, 'secrets') else ""
        
        # Initialize chatbot with API if available
        if groq_api_key:
            st.session_state.groq_api_key = groq_api_key
            try:
                groq_client = GroqClient(groq_api_key)
                chatbot = HealthcareChatbot(groq_client)
                st.session_state.api_available = True
                # Show API status
                st.success("✅ AI Assistant is using advanced language model for responses")
            except Exception as e:
                chatbot = HealthcareChatbot()
                st.session_state.api_available = False
                st.info("ℹ️ Using enhanced response system (API temporarily unavailable)")
        else:
            chatbot = HealthcareChatbot()
            st.session_state.api_available = False
            st.info("ℹ️ Using enhanced natural language response system")
        
        # Display chat history
        for message in st.session_state.chat_history:
            if message["role"] == "user":
                st.markdown(f'<div class="chat-message user-message"><strong>You:</strong> {message["content"]}</div>', unsafe_allow_html=True)
            else:
                st.markdown(f'<div class="chat-message bot-message"><strong>🤖 Health Assistant:</strong> {message["content"]}</div>', unsafe_allow_html=True)
        
        # Chat input
        if prompt := st.chat_input(
            "Type your health question here..." if language == "English" 
            else "اپنا صحت کا سوال یہاں ٹائپ کریں..."
        ):
            # Add user message to chat history
            st.session_state.chat_history.append({"role": "user", "content": prompt})
            
            # Generate bot response
            with st.spinner("💭 Analyzing your question..." if language == "English" else "💭 آپ کا سوال تجزیہ ہو رہا ہے..."):
                response = chatbot.get_response(prompt, language)
                st.session_state.chat_history.append({"role": "assistant", "content": response})
            
            # Limit chat history to last 10 messages
            if len(st.session_state.chat_history) > 10:
                st.session_state.chat_history = st.session_state.chat_history[-10:]
            
            st.rerun()
        
        # Quick action buttons
        if language == "English":
            st.subheader("Quick Health Topics")
        else:
            st.subheader("فوری صحت کے موضوعات")
        
        col_qa1, col_qa2, col_qa3, col_qa4 = st.columns(4)
        
        with col_qa1:
            if st.button("❤️ Heart Health", use_container_width=True):
                if language == "English":
                    query = "What should I know about heart disease prevention and symptoms?"
                else:
                    query = "دل کی بیماری کی روک تھام اور علامات کے بارے میں مجھے کیا جاننا چاہیے؟"
                st.session_state.chat_history.append({"role": "user", "content": query})
                st.rerun()
        
        with col_qa2:
            if st.button("🩺 Diabetes", use_container_width=True):
                if language == "English":
                    query = "Can you explain diabetes management and early warning signs?"
                else:
                    query = "کیا آپ ذیابیطس کے انتظام اور ابتدائی انتباہی علامات کی وضاحت کر سکتے ہیں؟"
                st.session_state.chat_history.append({"role": "user", "content": query})
                st.rerun()
        
        with col_qa3:
            if st.button("💓 Blood Pressure", use_container_width=True):
                if language == "English":
                    query = "What are effective ways to manage high blood pressure naturally?"
                else:
                    query = "ہائی بلڈ پریشر کو قدرتی طور پر کنٹرول کرنے کے مؤثر طریقے کیا ہیں؟"
                st.session_state.chat_history.append({"role": "user", "content": query})
                st.rerun()
        
        with col_qa4:
            if st.button("🍎 Nutrition", use_container_width=True):
                if language == "English":
                    query = "What dietary recommendations do you have for overall health?"
                else:
                    query = "مجموعی صحت کے لیے آپ کے پاس غذائی سفارشات کیا ہیں؟"
                st.session_state.chat_history.append({"role": "user", "content": query})
                st.rerun()

        # Test Medical Queries Section
        if language == "English":
            st.subheader("Test Medical Queries")
            st.write("Quickly test the assistant with these sample medical questions:")
        else:
            st.subheader("طبی سوالات کی جانچ")
            st.write("ان نمونہ طبی سوالات کے ساتھ اسسٹنٹ کو فوری طور پر آزمائیں:")
        
        test_col1, test_col2 = st.columns(2)
        
        with test_col1:
            if st.button("Test Heart Query", use_container_width=True):
                if language == "English":
                    test_query = "I have chest pain and high cholesterol, what should I do?"
                else:
                    test_query = "مجھے سینے میں درد اور ہائی کولیسٹرول ہے، میں کیا کروں؟"
                st.session_state.chat_history.append({"role": "user", "content": test_query})
                st.rerun()
        
        with test_col2:
            if st.button("Test Diabetes Query", use_container_width=True):
                if language == "English":
                    test_query = "What are the early symptoms of diabetes I should watch for?"
                else:
                    test_query = "ذیابیطس کی ابتدائی علامات کیا ہیں جن پر مجھے نظر رکھنی چاہیے؟"
                st.session_state.chat_history.append({"role": "user", "content": test_query})
                st.rerun()
        
        st.markdown('</div>', unsafe_allow_html=True)
    
    with tab3:
        # Medical Reports
        st.markdown('<div class="section-container">', unsafe_allow_html=True)
        
        if language == "English":
            st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">📋 Medical Reports & Analytics</h2>', unsafe_allow_html=True)
            st.write("Download comprehensive medical reports and view assessment analytics")
        else:
            st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">📋 طبی رپورٹس اور تجزیات</h2>', unsafe_allow_html=True)
            st.write("جامع طبی رپورٹس ڈاؤن لوڈ کریں اور تشخیص کے تجزیات دیکھیں")
        
        if st.session_state.assessment_history:
            # Latest assessment
            latest_assessment = st.session_state.assessment_history[-1]
            
            # Download PDF report
            if language == "English":
                st.subheader("Download Patient Report")
            else:
                st.subheader("مریض رپورٹ ڈاؤن لوڈ کریں")
            
            pdf_generator = PDFReportGenerator()
            pdf_bytes = pdf_generator.generate_report(
                latest_assessment['patient_data'], 
                latest_assessment['risk_scores'], 
                language
            )
            
            if language == "English":
                st.markdown(create_download_link(pdf_bytes, "sehatai_medical_report.pdf", "📥 Download Medical Report (PDF)"), unsafe_allow_html=True)
            else:
                st.markdown(create_download_link(pdf_bytes, "sehatai_medical_report.pdf", "📥 طبی رپورٹ ڈاؤن لوڈ کریں (PDF)"), unsafe_allow_html=True)
            
            # Analytics Section
            if language == "English":
                st.subheader("Assessment Analytics")
            else:
                st.subheader("تشخیص کے تجزیات")
            
            col_anal1, col_anal2, col_anal3 = st.columns(3)
            
            with col_anal1:
                st.metric(
                    "Total Assessments" if language == "English" else "کل تشخیص",
                    len(st.session_state.assessment_history)
                )
            
            with col_anal2:
                latest_priority = latest_assessment['risk_scores']['priority']
                st.metric(
                    "Current Priority Score" if language == "English" else "موجودہ ترجیحی اسکور",
                    f"{latest_priority:.1%}"
                )
            
            with col_anal3:
                high_risk_count = sum(1 for assess in st.session_state.assessment_history 
                                    if assess['risk_scores']['priority'] > 0.7)
                st.metric(
                    "High Risk Cases" if language == "English" else "اعلی خطرہ والے معاملات",
                    high_risk_count
                )
            
            # Risk distribution chart
            if len(st.session_state.assessment_history) > 1:
                risk_data = pd.DataFrame([
                    {
                        'Heart Risk': assess['risk_scores']['heart'],
                        'Diabetes Risk': assess['risk_scores']['diabetes'],
                        'Hypertension Risk': assess['risk_scores']['hypertension'],
                        'Assessment': i+1
                    } for i, assess in enumerate(st.session_state.assessment_history[-5:])
                ])
                
                fig = px.line(risk_data, x='Assessment', y=['Heart Risk', 'Diabetes Risk', 'Hypertension Risk'],
                            title="Risk Trend Analysis" if language == "English" else "خطرے کے رجحان کا تجزیہ",
                            color_discrete_map={
                                'Heart Risk': '#FF6B6B',
                                'Diabetes Risk': '#4ECDC4', 
                                'Hypertension Risk': '#45B7D1'
                            })
                st.plotly_chart(fig, use_container_width=True)
        
        else:
            if language == "English":
                st.info("👆 Complete a patient assessment to generate reports and view analytics")
            else:
                st.info("👆 رپورٹس تیار کرنے اور تجزیات دیکھنے کے لیے مریض کی تشخیص مکمل کریں")
        
        st.markdown('</div>', unsafe_allow_html=True)

if __name__ == "__main__":
    main()