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 
 
 
 
 
 
 
 
 
 
 
7df3ccc
2c3d17b
 
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
import streamlit as st
import requests
import json
from PIL import Image
import pandas as pd
from datetime import datetime
import os
import time
import base64
import io
import re
import html

# Must be the first Streamlit command
st.set_page_config(
    page_title="MediVision - Radiology Report System",
    page_icon="๐Ÿ”ฌ",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Configuration
FASTAPI_BASE_URL = "http://localhost:8001"
UPLOAD_ENDPOINT = f"{FASTAPI_BASE_URL}/upload/"
REPORTS_ENDPOINT = f"{FASTAPI_BASE_URL}/reports"

# ============================================================================
# CUSTOM STYLING (Based on Hospital System)
# ============================================================================

st.markdown("""
<style>
    /* Hide Streamlit default elements */
    .stDeployButton {display:none;}
    .stDecoration {display:none;}
    #MainMenu {visibility: hidden;}
    footer {visibility: hidden;}
    header {visibility: hidden;}
    
    /* Hide sidebar */
    .css-1d391kg {display: none;}
    .css-1rs6os {display: none;}
    .st-emotion-cache-16idsys {display: none;}
    
    /* Navigation Bar Styling */
    .nav-bar {
        background: linear-gradient(135deg, #1e3c72, #2a5298);
        padding: 1rem 2rem;
        border-radius: 15px;
        margin-bottom: 2rem;
        box-shadow: 0 4px 20px rgba(0,0,0,0.15);
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
    }
    
    .nav-brand {
        color: white;
        font-size: 1.8rem;
        font-weight: 700;
        text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        margin: 0;
    }
    
    .nav-subtitle {
        color: rgba(255,255,255,0.9);
        font-size: 0.9rem;
        margin: 0;
        font-weight: 300;
    }
    
    .nav-menu {
        display: flex;
        gap: 1rem;
        align-items: center;
        flex-wrap: wrap;
    }
    
    .nav-item {
        background: rgba(255,255,255,0.1);
        color: white;
        padding: 0.6rem 1.2rem;
        border-radius: 25px;
        text-decoration: none;
        font-weight: 500;
        font-size: 0.9rem;
        border: 2px solid transparent;
        transition: all 0.3s ease;
        cursor: pointer;
        backdrop-filter: blur(10px);
    }
    
    .nav-item:hover {
        background: rgba(255,255,255,0.2);
        border-color: rgba(255,255,255,0.3);
        transform: translateY(-2px);
        color: white;
        text-decoration: none;
    }
    
    .nav-item.active {
        background: rgba(255,255,255,0.3);
        border-color: rgba(255,255,255,0.5);
        font-weight: 600;
    }
    
    @media (max-width: 768px) {
        .nav-bar {
            flex-direction: column;
            text-align: center;
            gap: 1rem;
        }
        
        .nav-menu {
            justify-content: center;
            width: 100%;
        }
        
        .nav-item {
            font-size: 0.8rem;
            padding: 0.5rem 1rem;
        }
    }
    
    /* Background image */
    .stApp {
        background-image: linear-gradient(rgba(255,255,255,0.85), rgba(255,255,255,0.85)), 
                          url("https://www.servereworldsystem.com/include/blog/1464/14640320083m.jpeg");
        background-size: cover;
        background-position: center;
        background-attachment: fixed;
        background-repeat: no-repeat;
    }
    
    /* Main container styling */
    .main .block-container {
        padding-top: 1rem;
        padding-bottom: 1rem;
        max-width: 1200px;
        background: rgba(255, 255, 255, 0.95);
        border-radius: 20px;
        margin-top: 2rem;
        margin-bottom: 2rem;
        box-shadow: 0 8px 32px rgba(0,0,0,0.1);
        backdrop-filter: blur(10px);
    }
    
    /* Header styling */
    .medivision-header {
        background: linear-gradient(135deg, #1e3c72, #2a5298);
        color: white;
        padding: 2rem;
        border-radius: 15px;
        text-align: center;
        margin-bottom: 2rem;
        box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    }
    
    .medivision-header h1 {
        margin: 0;
        font-size: 2.5rem;
        font-weight: 700;
        text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        color: white !important;
    }
    
    .medivision-header p {
        margin: 0.5rem 0 0 0;
        opacity: 0.95;
        font-size: 1.2rem;
        font-weight: 300;
    }
    
    /* Section headers */
    .section-header {
        background: linear-gradient(135deg, #f8f9fa, #e9ecef);
        color: #2c5aa0;
        padding: 1rem 1.5rem;
        border-radius: 10px;
        border-left: 5px solid #4a90e2;
        margin: 2rem 0 1rem 0;
        font-size: 1.5rem;
        font-weight: 600;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    
    /* Cards and containers */
    .info-card {
        background: white;
        border-radius: 15px;
        padding: 2rem;
        margin: 1.5rem 0;
        box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        border: 1px solid #e0e6ed;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }
    
    .info-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 30px rgba(0,0,0,0.15);
    }
    
    .upload-area {
        background: linear-gradient(135deg, #f8f9fa, #ffffff);
        border: 2px dashed #2c5aa0;
        border-radius: 15px;
        padding: 2rem;
        text-align: center;
        margin: 1rem 0;
        transition: all 0.3s ease;
    }
    
    .upload-area:hover {
        border-color: #4a90e2;
        background: linear-gradient(135deg, #ffffff, #f8f9fa);
    }
    
    /* Buttons */
    .stButton > button {
        background: linear-gradient(135deg, #2c5aa0, #4a90e2);
        color: white;
        border: none;
        border-radius: 25px;
        padding: 0.75rem 2rem;
        font-weight: 600;
        font-size: 1rem;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(44, 90, 160, 0.3);
    }
    
    .stButton > button:hover {
        background: linear-gradient(135deg, #4a90e2, #6ab7ff);
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(44, 90, 160, 0.4);
    }
    
    /* Success/Error messages */
    .stSuccess {
        background: linear-gradient(135deg, #4caf50, #66bb6a);
        color: white;
        border-radius: 10px;
        padding: 1rem;
        border: none;
    }
    
    .stError {
        background: linear-gradient(135deg, #f44336, #ef5350);
        color: white;
        border-radius: 10px;
        padding: 1rem;
        border: none;
    }
    
    .stWarning {
        background: linear-gradient(135deg, #ff9800, #ffb74d);
        color: white;
        border-radius: 10px;
        padding: 1rem;
        border: none;
    }
    
    .stInfo {
        background: linear-gradient(135deg, #2196f3, #42a5f5);
        color: white;
        border-radius: 10px;
        padding: 1rem;
        border: none;
    }
    
    /* Form inputs */
    .stTextInput > div > div > input {
        border-radius: 10px;
        border: 2px solid #e0e6ed;
        padding: 0.75rem;
        font-size: 1rem;
        transition: border-color 0.3s ease;
    }
    
    .stTextInput > div > div > input:focus {
        border-color: #2c5aa0;
        box-shadow: 0 0 0 3px rgba(44, 90, 160, 0.1);
    }
    
    .stSelectbox > div > div > select {
        border-radius: 10px;
        border: 2px solid #e0e6ed;
        padding: 0.75rem;
        font-size: 1rem;
    }
    
    /* File uploader */
    .stFileUploader > div {
        border-radius: 15px;
        border: 2px solid #e0e6ed;
        background: linear-gradient(135deg, #f8f9fa, #ffffff);
        padding: 1rem;
    }
    
    .stFileUploader > div:hover {
        border-color: #2c5aa0;
    }
    
    /* Sidebar */
    .css-1d391kg {
        background: linear-gradient(180deg, #2c5aa0, #4a90e2);
    }
    
    .css-1d391kg .css-17eq0hr {
        color: white;
    }
    
    /* Progress bars */
    .stProgress > div > div > div > div {
        background: linear-gradient(90deg, #2c5aa0, #4a90e2);
    }
    
    /* Metrics */
    .metric-card {
        background: white;
        border-radius: 15px;
        padding: 1.5rem;
        text-align: center;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        border: 1px solid #e0e6ed;
        margin: 1rem 0;
    }
    
    .metric-value {
        font-size: 2rem;
        font-weight: 700;
        color: #2c5aa0;
        margin: 0.5rem 0;
    }
    
    .metric-label {
        font-size: 1rem;
        color: #666;
        font-weight: 500;
    }
    
    /* Status indicators */
    .status-online {
        display: inline-block;
        width: 12px;
        height: 12px;
        background: #4caf50;
        border-radius: 50%;
        margin-left: 8px;
        animation: pulse 2s infinite;
    }
    
    @keyframes pulse {
        0% { opacity: 0.4; }
        50% { opacity: 0.8; }
        100% { opacity: 0.4; }
    }
    
    /* Report cards */
    .report-card {
        background: white;
        border-radius: 15px;
        padding: 1.5rem;
        margin: 1rem 0;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        border-left: 5px solid #4a90e2;
        transition: all 0.3s ease;
    }
    
    .report-card:hover {
        transform: translateX(5px);
        box-shadow: 0 6px 25px rgba(0,0,0,0.15);
    }
    
    /* Data tables */
    .dataframe {
        border-radius: 10px;
        overflow: hidden;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }
    
    /* Mobile responsive */
    @media (max-width: 768px) {
        .medivision-header h1 {
            font-size: 2rem;
        }
        
        .medivision-header p {
            font-size: 1rem;
        }
        
        .main .block-container {
            padding: 1rem 0.5rem;
        }
        
        .info-card {
            padding: 1rem;
        }
    }
    
    /* RTL support for Arabic */
    .rtl {
        direction: rtl;
        text-align: right;
    }
    
    /* Loading animations */
    .loading-spinner {
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 3px solid rgba(255,255,255,.3);
        border-radius: 50%;
        border-top-color: #fff;
        animation: spin 1s ease-in-out infinite;
    }
    
    @keyframes spin {
        to { transform: rotate(360deg); }
    }

    /* FIXED THINKING INDICATOR - Larger font size and consistent spacing */
    .thinking-indicator {
        display: flex;
        align-items: center;
        margin: 15px 0;
        padding: 15px 20px;
        border-radius: 10px;
        background: #f8f9fa;
        color: #666;
        font-style: italic;
        font-size: 1.1em;  /* Increased from 0.9em */
        line-height: 1.5;
        font-weight: 500;
        border-left: 4px solid #2c5aa0;
    }

    .thinking-dot {
        width: 10px;  /* Increased from 8px */
        height: 10px;
        background: #2c5aa0;  /* Changed from #999 to match theme */
        border-radius: 50%;
        margin: 0 3px;  /* Increased spacing */
        animation: pulse 1.5s infinite;
    }

    .thinking-dot:nth-child(2) {
        animation-delay: 0.2s;
    }

    .thinking-dot:nth-child(3) {
        animation-delay: 0.4s;
    }

    /* FIXED AI THINKING - Larger font and better spacing */
    .ai-thinking {
        color: #555;  /* Darker for better readability */
        font-style: italic;
        background: #f8f9fa;
        padding: 20px 24px;  /* Increased padding */
        border-radius: 10px;
        margin: 15px 0;  /* Consistent spacing */
        border-left: 4px solid #2c5aa0;
        font-size: 1.0em;  /* Increased from 0.85em */
        line-height: 1.6;  /* Increased line height */
        max-height: 200px;  /* Slightly taller */
        overflow-y: auto;
        font-weight: 400;
    }

    .ai-thinking pre {
        margin: 8px 0;  /* Added margin */
        padding: 0;
        white-space: pre-wrap;
        font-size: 1.0em;  /* Increased from 0.85em */
        font-family: 'Consolas', 'Monaco', monospace;
    }

    .ai-thinking p {
        margin: 10px 0;  /* Increased from 4px */
        font-size: 1.0em;  /* Increased from 0.85em */
    }

    .ai-thinking ul, .ai-thinking ol {
        margin: 10px 0;  /* Increased from 4px */
        padding-left: 20px;  /* Slightly increased */
    }

    .ai-thinking li {
        margin: 6px 0;  /* Increased from 2px */
        font-size: 1.0em;  /* Increased from 0.85em */
    }

    .stream-text {
        white-space: pre-wrap;
        font-family: 'Segoe UI', Arial, sans-serif;  /* Better font */
        line-height: 1.5;  /* Increased */
        font-size: 1.0em;  /* Added explicit size */
    }

    /* FIXED AI RESPONSE - Better rendering */
    .ai-response {
        color: #333;
        background: white;
        padding: 24px;  /* Increased padding */
        border-radius: 12px;
        margin: 20px 0;  /* Increased margin */
        border-left: 4px solid #2c5aa0;
        box-shadow: 0 4px 20px rgba(0,0,0,0.12);
        font-size: 1.0em;  /* Increased from 0.95em */
        line-height: 1.7;  /* Increased line height */
        font-family: 'Segoe UI', -apple-system, sans-serif;
    }

    /* FIXED REPORT HEADER - Better rendering */
    .report-header {
        border-bottom: 2px solid #2c5aa0;
        margin-bottom: 25px;  /* Increased */
        padding-bottom: 20px;
        background: linear-gradient(135deg, #f8f9fa, #ffffff);
        padding: 25px;  /* Increased */
        border-radius: 10px;
        margin: -24px -24px 25px -24px;  /* Adjusted for new padding */
        box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    }

    .report-header h2 {
        color: #2c5aa0;
        margin: 0 0 20px 0;  /* Increased margin */
        font-size: 1.5em;  /* Increased */
        font-weight: 700;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12px;  /* Increased gap */
    }

    .report-header .hospital-info {
        text-align: center;
        margin-bottom: 20px;  /* Increased */
        padding-bottom: 15px;  /* Increased */
        border-bottom: 1px solid #e0e0e0;
    }

    .report-header .hospital-name {
        font-size: 1.2em;  /* Increased */
        font-weight: 600;
        color: #2c5aa0;
        margin-bottom: 8px;  /* Increased */
    }

    .report-header .patient-details {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 12px;  /* Increased */
        margin-top: 20px;  /* Increased */
    }

    .report-header .patient-detail-item {
        background: rgba(44, 90, 160, 0.05);
        padding: 12px 16px;  /* Increased */
        border-radius: 8px;
        font-size: 0.95em;  /* Slightly increased */
        border: 1px solid rgba(44, 90, 160, 0.1);
    }

    .report-header .detail-label {
        font-weight: 600;
        color: #2c5aa0;
        display: inline-block;
        min-width: 80px;
    }

    .report-header .detail-value {
        color: #333;
        margin-left: 8px;  /* Increased */
    }

    /* FIXED REPORT CONTENT - Better rendering */
    .report-content {
        margin-top: 25px;  /* Increased */
        white-space: pre-wrap;
        font-family: 'Segoe UI', -apple-system, sans-serif;
        line-height: 1.7;  /* Increased */
        font-size: 1.0em;  /* Added explicit size */
        color: #333;
    }

    /* Styling for bullet points in report content */
    .report-content ul {
        margin: 15px 0;
        padding-left: 25px;
        list-style-type: disc;
    }

    .report-content ol {
        margin: 15px 0;
        padding-left: 25px;
        list-style-type: decimal;
    }

    .report-content li {
        margin: 8px 0;
        color: #333;
        line-height: 1.6;
        padding-left: 5px;
    }

    .report-content ul li::marker {
        color: #2c5aa0;
        font-size: 1.1em;
    }

    .report-content ol li::marker {
        color: #2c5aa0;
        font-weight: 600;
    }

    /* Section headers within report content */
    .report-content p strong {
        color: #333;
        font-size: 1.0em;
        font-weight: 400;
        display: block;
        margin: 15px 0 8px 0;
        padding-bottom: 0px;
        border-bottom: none;
    }

    .report-content p {
        margin: 10px 0;
        line-height: 1.6;
    }

    .report-section {
        margin: 25px 0;  /* Increased */
    }

    .report-section h3 {
        color: #2c5aa0;
        font-size: 1.2em;  /* Increased */
        margin: 20px 0 12px 0;  /* Increased */
        font-weight: 600;
        border-bottom: 2px solid #e0e0e0;  /* Thicker border */
        padding-bottom: 8px;  /* Increased */
    }

    .report-section h4 {
        color: #2c5aa0;
        font-size: 1.1em;  /* Increased */
        margin: 15px 0 10px 0;  /* Increased */
        font-weight: 600;
    }

    .report-section p {
        margin: 12px 0;  /* Increased */
        color: #333;
        text-align: justify;
        line-height: 1.7;
    }

    .report-section ul, .report-section ol {
        margin: 15px 0;  /* Increased */
        padding-left: 30px;  /* Increased */
    }

    .report-section li {
        margin: 8px 0;  /* Increased */
        color: #333;
        line-height: 1.6;
    }

    /* FIXED REPORT FOOTER */
    .report-footer {
        margin-top: 30px;  /* Increased */
        padding-top: 20px;  /* Increased */
        border-top: 2px solid #eee;  /* Thicker border */
        font-size: 0.95em;  /* Slightly increased */
        color: #666;
        text-align: center;
        background: #f9f9f9;
        padding: 20px;  /* Increased */
        border-radius: 8px;
        margin-left: -24px;  /* Adjusted */
        margin-right: -24px;
        margin-bottom: -24px;
    }
</style>
""", unsafe_allow_html=True)
# ============================================================================
def main():
    # Modern header with MediVision branding
    st.markdown("""
    <div class="medivision-header">
        <h1>๐Ÿ”ฌ MediVision</h1>
        <p>Advanced Radiology Report System - Powered by AI Technology</p>
    </div>
    """, unsafe_allow_html=True)
    
    # Sidebar navigation
    st.sidebar.markdown("## ๐Ÿ“‹ Navigation")
    page = st.sidebar.selectbox("Choose Page", [
        "๐Ÿ“ค Upload & Generate Report",
        "๐Ÿ“Š View Reports", 
        "โš™๏ธ System Status"
    ])
    
    if "Upload" in page:
        upload_page()
    elif "View Reports" in page:
        view_reports_page()
    elif "System Status" in page:
        system_status_page()

def upload_page():
    st.markdown('<div class="section-header">๐Ÿ“ค Upload Medical Images & Generate Reports</div>', unsafe_allow_html=True)
    
    # Create two columns for better layout
    col1, col2 = st.columns([2, 1])
    
    with col1:
        st.markdown('<div class="info-card">', unsafe_allow_html=True)
        st.markdown("### ๐Ÿ‘ค Patient Information")
        
        # Patient form with modern styling
        with st.form("patient_form"):
            name = st.text_input("Patient Name *", placeholder="Enter full name")
            date_of_birth = st.date_input("Date of Birth *")
            gender = st.selectbox("Gender *", ["Male", "Female", "Other"])
            
            # MRN field (auto-generated, but allow manual override)
            col1, col2 = st.columns([3, 1])
            with col1:
                medical_record_number = st.text_input(
                    "Medical Record Number (MRN)", 
                    placeholder="Auto-generated if left empty",
                    help="Leave empty to auto-generate MRN based on patient name and DOB"
                )
            with col2:
                st.markdown("<br>", unsafe_allow_html=True)  # Add spacing
                if st.form_submit_button("๐Ÿ”ข Generate MRN", use_container_width=True):
                    if name and date_of_birth:
                        try:
                            response = requests.get(
                                f"{FASTAPI_BASE_URL}/generate-mrn/",
                                params={"patient_name": name, "date_of_birth": str(date_of_birth)},
                                timeout=10
                            )
                            if response.status_code == 200:
                                data = response.json()
                                if data.get("success"):
                                    st.session_state.generated_mrn = data.get("mrn")
                                    st.success(f"โœ… Generated MRN: {data.get('mrn')}")
                                    st.rerun()
                        except Exception as e:
                            st.error(f"โŒ Error generating MRN: {str(e)}")
                    else:
                        st.error("โš ๏ธ Please enter patient name and date of birth first")
            
            # Show generated MRN if available
            if hasattr(st.session_state, 'generated_mrn') and st.session_state.generated_mrn:
                medical_record_number = st.text_input(
                    "Generated MRN", 
                    value=st.session_state.generated_mrn,
                    disabled=True,
                    help="Auto-generated MRN - you can edit the field above to override"
                )
            
            referring_physician = st.text_input("Referring Physician *", placeholder="Enter physician name")
            date_of_study = st.date_input("Date of Study *", value=datetime.now().date())
            
            st.markdown("### ๐Ÿ–ผ๏ธ Medical Image")
            st.markdown('<div class="upload-area">', unsafe_allow_html=True)
            uploaded_file = st.file_uploader(
                "Choose medical image", 
                type=['png', 'jpg', 'jpeg', 'dcm'],
                help="Upload X-ray, CT, MRI, (Max 10MB)",
                key="medical_image_upload"
            )
            st.markdown('</div>', unsafe_allow_html=True)
            
            # Display uploaded image with modern styling (NO API CALLS)
            if uploaded_file is not None:
                try:
                    # Validate file size only (no API calls)
                    file_size = uploaded_file.size
                    if file_size > 10 * 1024 * 1024:  # 10MB
                        st.error("โš ๏ธ File size too large. Please upload an image smaller than 10MB.")
                    else:
                        # Display success message and file info
                        st.success(f"โœ… File uploaded successfully: {uploaded_file.name}")
                        st.info(f"๐Ÿ“ File size: {file_size/1024:.1f} KB")
                        
                        # Display image preview (local only, no backend calls)
                        if uploaded_file.type.startswith('image/'):
                            image = Image.open(uploaded_file)
                            st.image(image, caption="Uploaded Medical Image", use_column_width=True)
                        else:
                            st.info("๐Ÿ“„ DICOM file uploaded successfully")
                        
                        # Reset file pointer for later use
                        uploaded_file.seek(0)
                        
                except Exception as e:
                    st.error(f"โŒ Error processing image: {str(e)}")
                    st.info("๐Ÿ’ก Please ensure the file is a valid image format (PNG, JPG, JPEG, DCM)")
            else:
                st.info("๐Ÿ‘† Please upload a medical image to begin analysis")
            
            submit_button = st.form_submit_button("๐Ÿ” Generate Report", use_container_width=True)
            
            if submit_button:
                # Get the MRN (either generated or manually entered)
                final_mrn = medical_record_number
                if hasattr(st.session_state, 'generated_mrn') and st.session_state.generated_mrn and not medical_record_number:
                    final_mrn = st.session_state.generated_mrn
                
                # Validation (MRN is now optional as it can be auto-generated)
                if not all([name, date_of_birth, gender, referring_physician, uploaded_file]):
                    st.error("โš ๏ธ Please fill all required fields and upload an image")
                else:
                    generate_report(name, str(date_of_birth), gender, final_mrn, 
                                  referring_physician, str(date_of_study), uploaded_file)
        
        st.markdown('</div>', unsafe_allow_html=True)

def generate_report(name, date_of_birth, gender, medical_record_number, 
                   referring_physician, date_of_study, uploaded_file):
    """Generate report by sending data to backend and displaying the result"""
    try:
        if uploaded_file is not None:
            with st.spinner("๐Ÿ”„ Analyzing medical image..."):
                # Validate file before sending
                if uploaded_file.size > 10 * 1024 * 1024:  # 10MB limit
                    st.error("โš ๏ธ File size too large. Please upload an image smaller than 10MB.")
                    return
                
                # Reset file pointer to beginning
                uploaded_file.seek(0)
                
                # Prepare file for upload
                files = {"file": (uploaded_file.name, uploaded_file.getvalue(), uploaded_file.type)}
                
                try:
                    # Call analyze endpoint
                    analyze_response = requests.post(
                        f"{FASTAPI_BASE_URL}/analyze",
                        files=files,
                        timeout=60  # 60 second timeout
                    )
                    
                    if analyze_response.status_code == 200:
                        response_data = analyze_response.json()
                        
                        # Handle successful response
                        if response_data.get("success"):
                            findings = response_data.get("analysis", "Analysis completed")
                            
                            # Parse thinking and answer sections
                            thinking_text = ""
                            report_text = findings
                            
                            if "thinking:" in findings and "answer:" in findings:
                                parts = findings.split("answer:", 1)
                                thinking_text = parts[0].replace("thinking:", "").strip()
                                report_text = parts[1].strip()
                            
                            st.success("โœ… Analysis completed successfully!")
                            stream_response(thinking_text, report_text, {
                                "name": name,
                                "medical_record_number": medical_record_number,
                                "referring_physician": referring_physician,
                                "date_of_study": date_of_study
                            })
                            
                        else:
                            # Handle failed analysis with fallback
                            st.warning("โš ๏ธ AI analysis encountered issues, using fallback analysis")
                            fallback_findings = response_data.get("analysis", "Medical image processed. Professional review recommended.")
                            stream_response("Fallback analysis used", fallback_findings, {
                                "name": name,
                                "medical_record_number": medical_record_number,
                                "referring_physician": referring_physician,
                                "date_of_study": date_of_study
                            })
                            findings = fallback_findings
                            
                    else:
                        st.error(f"โŒ Backend Error (Status {analyze_response.status_code})")
                        st.error(f"Response: {analyze_response.text}")
                        return
                    
                    
                except requests.exceptions.Timeout:
                    st.error("โฑ๏ธ Request timed out. The analysis is taking too long. Please try again.")
                    return
                except requests.exceptions.ConnectionError:
                    st.error("๐Ÿ”Œ Cannot connect to backend service.")
                    st.error("Please ensure the backend is running at: http://localhost:8001")
                    st.info("๐Ÿ’ก To start the backend, run: `cd backend && python service.py`")
                    return
                except requests.exceptions.RequestException as e:
                    st.error(f"โŒ Request failed: {str(e)}")
                    return
                
                # Generate PDF report
                with st.spinner("๐Ÿ“„ Generating PDF report..."):
                    try:
                        pdf_response = requests.post(
                            f"{FASTAPI_BASE_URL}/generate-report/",
                            data={
                                "patient_name": name,
                                "medical_record_number": medical_record_number or "AUTO-GENERATED",
                                "date_of_birth": date_of_birth,
                                "gender": gender,
                                "referring_physician": referring_physician,
                                "study_date": date_of_study,
                                "findings": findings
                            },
                            timeout=30
                        )
                        
                        if pdf_response.status_code == 200:
                            pdf_data = pdf_response.json()
                            if pdf_data.get("success"):
                                pdf_url = f"{FASTAPI_BASE_URL}/reports/{name.replace(' ', '_')}/pdf" 
                                st.markdown(f'''
                                <div style="margin-top: 1rem; padding: 1rem; background: linear-gradient(135deg, #4caf50, #66bb6a); border-radius: 10px;">
                                    <p style="color: white; margin: 0; font-weight: 600;">โœ… PDF Report Generated Successfully!</p>
                                    <a href="{pdf_url}" target="_blank" style="display:inline-block;margin-top:0.5em;padding:0.5em 1.5em;background:rgba(255,255,255,0.2);color:white;border-radius:20px;text-decoration:none;font-weight:600;border: 2px solid rgba(255,255,255,0.3);">
                                        ๐Ÿ“„ Download PDF Report
                                    </a>
                                </div>
                                ''', unsafe_allow_html=True)
                            else:
                                st.error(f"โŒ Failed to generate PDF: {pdf_data.get('message', 'Unknown error')}")
                        else:
                            st.error(f"โŒ PDF generation failed with status {pdf_response.status_code}")
                            
                    except requests.exceptions.Timeout:
                        st.error("โฑ๏ธ PDF generation timed out. Please try again.")
                    except Exception as e:
                        st.error(f"โŒ Error generating PDF: {str(e)}")
                
    except Exception as e:
        st.error(f"โŒ Unexpected error: {str(e)}")
        st.info("๐Ÿ’ก Troubleshooting tips:")
        st.info("   โ€ข Ensure backend service is running on port 8001")
        st.info("   โ€ข Check that the uploaded file is a valid image")
        st.info("   โ€ข Try refreshing the page and uploading again")

def view_reports_page():
    st.markdown('<div class="section-header">๐Ÿ“Š View Patient Reports - Search by MRN</div>', unsafe_allow_html=True)
    
    # Search section with modern styling
    st.markdown('<div class="info-card">', unsafe_allow_html=True)
    col1, col2 = st.columns([3, 1])
    
    with col1:
        patient_mrn = st.text_input("๐Ÿ” Search by MRN", 
                                   placeholder="Enter Medical Record Number (e.g., MV-20250618-A1B2)")
    
    with col2:
        st.markdown("<br>", unsafe_allow_html=True)  # Add spacing
        search_button = st.button("๐Ÿ” Search", use_container_width=True)
    
    st.markdown('</div>', unsafe_allow_html=True)
    
    # Action buttons
    col1, col2 = st.columns(2)
    with col1:
        if search_button and patient_mrn:
            search_reports_by_mrn(patient_mrn)
    
    with col2:
        if st.button("๐Ÿ“‹ Show All Patients", use_container_width=True):
            show_all_patients()

def search_reports_by_mrn(mrn):
    """Search for reports by MRN with modern styling"""
    
    with st.spinner(f"๐Ÿ” Searching for patient with MRN: {mrn}..."):
        try:
            response = requests.get(f"{FASTAPI_BASE_URL}/patient/{mrn}", timeout=10)
            
            if response.status_code == 200:
                patient_data = response.json()
                
                st.markdown(f"""
                <div class="info-card" style="background: linear-gradient(135deg, #4caf50, #66bb6a); color: white;">
                    <h4>โœ… Patient Found: {patient_data.get('patient_name', 'N/A')}</h4>
                    <p><b>MRN:</b> {patient_data.get('mrn', 'N/A')}</p>
                </div>
                """, unsafe_allow_html=True)
                
                # Display patient details
                display_patient_details(patient_data)
                
            elif response.status_code == 404:
                st.markdown(f"""
                <div class="info-card" style="background: linear-gradient(135deg, #ff9800, #ffb74d); color: white;">
                    <h4>โš ๏ธ No Patient Found</h4>
                    <p>No patient record found with MRN: <b>{mrn}</b></p>
                    <p>Please check the MRN and try again.</p>
                </div>
                """, unsafe_allow_html=True)
            else:
                st.error(f"โŒ Error searching patient: HTTP {response.status_code}")
                
        except requests.exceptions.ConnectionError:
            st.error("โŒ Cannot connect to the backend server. Please make sure the FastAPI server is running.")
        except requests.exceptions.Timeout:
            st.error("โŒ Search request timed out. Please try again.")
        except Exception as e:
            st.error(f"โŒ An error occurred: {str(e)}")

def show_all_patients():
    """Show all patients in the system"""
    
    with st.spinner("๐Ÿ“‹ Loading all patient records..."):
        try:
            response = requests.get(f"{FASTAPI_BASE_URL}/patients", timeout=15)
            
            if response.status_code == 200:
                data = response.json()
                patients = data.get('patients', [])
                
                if patients:
                    st.markdown(f"""
                    <div class="info-card" style="background: linear-gradient(135deg, #2196f3, #42a5f5); color: white;">
                        <h4>๐Ÿ“Š Found {len(patients)} Patient Records</h4>
                    </div>
                    """, unsafe_allow_html=True)
                    
                    # Display patients in a table format
                    for patient in patients:
                        display_patient_summary(patient)
                        
                else:
                    st.info("๐Ÿ“‹ No patient records found in the system yet.")
                    
            else:
                st.error(f"โŒ Error retrieving patients: {response.text}")
                
        except requests.exceptions.ConnectionError:
            st.error("โŒ Cannot connect to the backend server. Please make sure the FastAPI server is running.")
        except Exception as e:
            st.error(f"โŒ An error occurred: {str(e)}")

def display_patient_details(patient_data):
    """Display detailed patient information"""
    st.markdown('<div class="info-card">', unsafe_allow_html=True)
    st.markdown("### ๐Ÿ‘ค Patient Details")
    
    col1, col2 = st.columns(2)
    
    with col1:
        st.markdown(f"**Name:** {patient_data.get('patient_name', 'N/A')}")
        st.markdown(f"**MRN:** {patient_data.get('mrn', 'N/A')}")
        st.markdown(f"**Date of Birth:** {patient_data.get('date_of_birth', 'N/A')}")
        st.markdown(f"**Gender:** {patient_data.get('gender', 'N/A')}")
    
    with col2:
        st.markdown(f"**Referring Physician:** Dr. {patient_data.get('referring_physician', 'N/A')}")
        st.markdown(f"**Study Date:** {patient_data.get('date_of_study', 'N/A')}")
        st.markdown(f"**Report Date:** {patient_data.get('report_date', 'N/A')}")
        st.markdown(f"**Status:** {patient_data.get('status', 'N/A').title()}")
    
    # Display findings
    if patient_data.get('findings'):
        st.markdown("### ๐Ÿ” Findings")
        findings = patient_data.get('findings', '')
        
        # Process findings to show only the answer part
        if "answer:" in findings.lower():
            parts = findings.split("answer:", 1)
            if len(parts) == 2:
                findings_display = parts[1].strip()
            else:
                findings_display = findings
        else:
            findings_display = findings
            
        st.markdown(findings_display)
    
    # PDF download link
    patient_name = patient_data.get('patient_name', 'Unknown')
    pdf_url = f"{FASTAPI_BASE_URL}/reports/{patient_name}/pdf"
    st.markdown(f"""
    <a href="{pdf_url}" target="_blank" style="display:inline-block;margin-top:1em;padding:0.5em 1.5em;background:linear-gradient(135deg,#2c5aa0,#4a90e2);color:white;border-radius:20px;text-decoration:none;font-weight:600;">
        ๐Ÿ“„ Download PDF Report
    </a>
    """, unsafe_allow_html=True)
    
    st.markdown('</div>', unsafe_allow_html=True)

def display_patient_summary(patient_data):
    """Display patient summary in a card format"""
    st.markdown('<div class="info-card">', unsafe_allow_html=True)
    
    col1, col2, col3 = st.columns([2, 2, 1])
    
    with col1:
        st.markdown(f"**{patient_data.get('patient_name', 'N/A')}**")
        st.markdown(f"MRN: {patient_data.get('mrn', 'N/A')}")
    
    with col2:
        st.markdown(f"Study: {patient_data.get('date_of_study', 'N/A')}")
        st.markdown(f"Physician: Dr. {patient_data.get('referring_physician', 'N/A')}")
    
    with col3:
        # Search button for this specific patient
        if st.button(f"๐Ÿ” View", key=f"view_{patient_data.get('mrn', 'unknown')}"):
            search_reports_by_mrn(patient_data.get('mrn', ''))
    
    st.markdown('</div>', unsafe_allow_html=True)

# Remove old search functions - they are replaced by MRN-based search functions above

def display_report_details(report):
    """Display detailed report information with modern cards"""
    st.markdown('<div class="report-card">', unsafe_allow_html=True)
    col1, col2 = st.columns(2)
    with col1:
        st.markdown("**๐Ÿ‘ค ู…ุนู„ูˆู…ุงุช ุงู„ู…ุฑูŠุถ - Patient Information:**")
        st.markdown(f"""
        - **ุงู„ุงุณู… - Name:** {report.get('name', 'ุบูŠุฑ ู…ุชุงุญ - N/A')}
        - **ุชุงุฑูŠุฎ ุงู„ู…ูŠู„ุงุฏ - DOB:** {report.get('date_of_birth', 'ุบูŠุฑ ู…ุชุงุญ - N/A')}
        - **ุงู„ุฌู†ุณ - Gender:** {report.get('gender', 'ุบูŠุฑ ู…ุชุงุญ - N/A')}
        - **ุฑู‚ู… ุงู„ุณุฌู„ - MRN:** {report.get('medical_record_number', 'ุบูŠุฑ ู…ุชุงุญ - N/A')}
        """)
    with col2:
        st.markdown("**๐Ÿฅ ู…ุนู„ูˆู…ุงุช ุงู„ูุญุต - Study Information:**")
        st.markdown(f"""
        - **ุงู„ุทุจูŠุจ ุงู„ู…ุญูŠู„ - Physician:** {report.get('referring_physician', 'ุบูŠุฑ ู…ุชุงุญ - N/A')}
        - **ุชุงุฑูŠุฎ ุงู„ูุญุต - Study Date:** {report.get('date_of_study', 'ุบูŠุฑ ู…ุชุงุญ - N/A')}
        - **ุงู„ู†ุชุงุฆุฌ - Findings:** {report.get('findings', 'ุบูŠุฑ ู…ุชุงุญ - N/A')}
        """)
    # PDF download button with modern styling (always use backend endpoint)
    if 'name' in report:
        pdf_url = f"{FASTAPI_BASE_URL}/reports/{report.get('name')}/pdf"
        st.markdown(f"""
        <div style="text-align: center; margin-top: 1rem;">
            <a href="{pdf_url}" target="_blank" style="
                display: inline-block;
                background: linear-gradient(135deg, #2c5aa0, #4a90e2);
                color: white;
                padding: 0.5rem 1.5rem;
                border-radius: 20px;
                text-decoration: none;
                font-weight: 600;
                box-shadow: 0 4px 15px rgba(44, 90, 160, 0.3);
            ">๐Ÿ“„ ุชุญู…ูŠู„ ุงู„ุชู‚ุฑูŠุฑ - Download PDF Report</a>
        </div>
        """, unsafe_allow_html=True)
    st.markdown('</div>', unsafe_allow_html=True)

def show_all_reports():
    """Show all reports using the FastAPI backend"""
    
    with st.spinner("๐Ÿ“‹ Loading all reports..."):
        try:
            response = requests.get(f"{REPORTS_ENDPOINT}/")
            
            if response.status_code == 200:
                data = response.json()
                reports = data.get('reports', [])
                count = data.get('count', 0)
                
                if reports:
                    st.success(f"โœ… Found {count} total report(s) in the system")
                    
                    # Create a summary table
                    if reports:
                        df_data = []
                        for report in reports:
                            df_data.append({
                                'Patient Name': report.get('name', 'N/A'),
                                'Date of Birth': report.get('date_of_birth', 'N/A'),
                                'Gender': report.get('gender', 'N/A'),
                                'Study Date': report.get('date_of_study', 'N/A'),
                                'Physician': report.get('referring_physician', 'N/A')
                            })
                        
                        df = pd.DataFrame(df_data)
                        st.dataframe(df, use_container_width=True)
                    
                    # Show detailed reports
                    st.subheader("Detailed Reports")
                    for i, report in enumerate(reports):
                        with st.expander(f"{report.get('name', 'Unknown')} - {report.get('date_of_study', 'Unknown Date')}"):
                            display_report_details(report)
                else:
                    st.info("๐Ÿ“‹ No reports found in the system yet.")
                    
            else:
                st.error(f"โŒ Error retrieving reports: {response.text}")
                
        except requests.exceptions.ConnectionError:
            st.error("โŒ Cannot connect to the backend server. Please make sure the FastAPI server is running.")
        except Exception as e:
            st.error(f"โŒ An error occurred: {str(e)}")

def system_status_page():
    """System status and connectivity check page"""
    st.markdown('<div class="section-header">โš™๏ธ System Status & Diagnostics</div>', unsafe_allow_html=True)
    
    st.markdown('<div class="info-card">', unsafe_allow_html=True)
    st.markdown("### ๐Ÿ” Backend Service Status")
    
    col1, col2 = st.columns([3, 1])
    
    with col2:
        if st.button("๐Ÿ”„ Check Status", use_container_width=True):
            check_backend_status()
    
    with col1:
        st.info("Click 'Check Status' to test backend connectivity")
    
    st.markdown('</div>', unsafe_allow_html=True)
    
    # Show system information
    st.markdown('<div class="info-card">', unsafe_allow_html=True)
    st.markdown("### ๐Ÿ“Š System Information")
    
    col1, col2 = st.columns(2)
    
    with col1:
        st.metric("Frontend", "Streamlit", "Running โœ…")
        st.metric("Backend URL", FASTAPI_BASE_URL, "Configured")
    
    with col2:
        st.metric("Upload Endpoint", "/analyze/", "Ready")
        st.metric("Reports Endpoint", "/reports", "Ready")
    
    st.markdown('</div>', unsafe_allow_html=True)

def check_backend_status():
    """Check if backend service is running and accessible"""
    try:
        with st.spinner("Checking backend connectivity..."):
            # Test health endpoint
            response = requests.get(f"{FASTAPI_BASE_URL}/health", timeout=10)
            
            if response.status_code == 200:
                data = response.json()
                st.success(f"โœ… Backend service is healthy!")
                st.json(data)
            else:
                st.error(f"โŒ Backend returned status {response.status_code}")
                
    except requests.exceptions.ConnectionError:
        st.error("โŒ Cannot connect to backend service")
        st.info("๐Ÿ’ก Make sure the backend is running:")
        st.code("cd backend && python service.py --serve")
        
    except requests.exceptions.Timeout:
        st.error("โŒ Backend request timed out")
        
    except Exception as e:
        st.error(f"โŒ Unexpected error: {str(e)}")

def stream_response(thinking_text, response_text, patient_info):
    """
    Streams the AI response with proper formatting and bullet points.
    """
    # --- Helper function for formatting ---
    def format_text_to_html(text):
        """Converts plain text with newlines and list-like structures to HTML, keeping section headers as normal text."""
        section_headers = [
            "Initial Assessment:",
            "Key Findings:",
            "Clinical Significance:",
            "Impression:",
            "Conclusion:",
            "Recommendations:",
            "Technical Details:",
            "Comparison:",
            "History:",
            "Exam Type:",
            "Findings:",
            "Clinical History:",
            "Technique:",
            "Indication:",
            "Result:",
            "Results:",
            "Summary:",
            "Assessment:",
            "Plan:",
            "Follow-up:",
            "Brief Structured Report:",
            "Report:",
            "Diagnosis:",
            "Opinion:"
        ]
        
        text = html.escape(text)
        lines = text.split('\n')
        html_lines = []
        in_list = False
        
        for line in lines:
            stripped_line = line.strip()
            
            # Remove leading bullets/numbers for header checking
            clean_line = re.sub(r'^[\d+\.]*[\-\*\โ€ข]?\s*', '', stripped_line)
            
            # Also try removing just the number prefix for numbered headers
            clean_line_no_number = re.sub(r'^\d+\.?\s*', '', stripped_line)
            
            # Check if this is a section header (case-insensitive, flexible matching)
            is_section_header = any(
                clean_line.lower().startswith(header.lower()) or 
                clean_line.lower() == header.lower().rstrip(':') or
                clean_line_no_number.lower().startswith(header.lower()) or
                clean_line_no_number.lower() == header.lower().rstrip(':') or
                # Handle cases like "EXAM TYPE:" matching "Exam Type:"
                clean_line.lower().replace(' ', '').startswith(header.lower().replace(' ', '').rstrip(':')) or
                clean_line_no_number.lower().replace(' ', '').startswith(header.lower().replace(' ', '').rstrip(':'))
                for header in section_headers
            )
            
            if is_section_header:
                # Close any open list
                if in_list:
                    html_lines.append('</ol>' if 'ol>' in str(html_lines[-3:]) else '</ul>')
                    in_list = False
                # Use the version without numbers/bullets for display
                display_text = clean_line_no_number if clean_line_no_number.lower().endswith(':') else clean_line
                html_lines.append(f'<p><strong>{display_text}</strong></p>')
                
            elif re.match(r'^[\-\*\โ€ข]\s', stripped_line) and not is_section_header:
                # This is a bullet point (not a section header)
                if not in_list:
                    html_lines.append('<ul>')
                    in_list = True
                item_text = re.sub(r'^[\-\*\โ€ข]\s*', '', stripped_line)
                html_lines.append(f'<li>{item_text}</li>')
                
            elif re.match(r'^\d+\.?\s', stripped_line) and not is_section_header:
                # This is a numbered list item (not a section header)
                if not in_list:
                    html_lines.append('<ul>')  # Convert numbered lists to bullet lists for consistency
                    in_list = True
                item_text = re.sub(r'^\d+\.?\s*', '', stripped_line)
                html_lines.append(f'<li>{item_text}</li>')
                
            else:
                # Regular text line
                if in_list:
                    html_lines.append('</ul>')
                    in_list = False
                if stripped_line:
                    html_lines.append(f'<p>{line}</p>')
                else:
                    html_lines.append('<br>')  # Preserve empty lines as breaks
                    
        # Close any remaining open list
        if in_list:
            html_lines.append('</ul>')
            
        return ''.join(html_lines)

    # --- Thinking Process ---
    thinking_container = st.empty()
    thinking_container.markdown("""
        <div class="thinking-indicator">
            <span>AI is analyzing</span>
            <div class="thinking-dot"></div><div class="thinking-dot"></div><div class="thinking-dot"></div>
        </div>
    """, unsafe_allow_html=True)
    
    st.markdown('<div style="font-size: 0.8em; color: #666; margin: 10px 0 5px 0; font-weight: 500;">๐Ÿค” AI Analysis Process:</div>', unsafe_allow_html=True)
    thinking_output = st.empty()
    thinking_text_container = ""
    for char in thinking_text:
        thinking_text_container += char
        formatted_thinking = format_text_to_html(thinking_text_container)
        thinking_output.markdown(f'<div class="ai-thinking">{formatted_thinking}</div>', unsafe_allow_html=True)
        time.sleep(0.005)
    
    thinking_container.empty()
    
    # --- Define Report Components ---
    current_date = datetime.now().strftime("%B %d, %Y")
    current_time = datetime.now().strftime("%I:%M %p")
    
    report_header = (
        '<div class="report-header">'
            '<div class="hospital-info">'
                '<div class="hospital-name">๐Ÿ”ฌ MediVision Radiology Center</div>'
                '<div style="font-size: 0.85em; color: #666;">Advanced AI-Powered Medical Imaging Analysis</div>'
            '</div>'
            '<h2><span>๐Ÿ“‹ RADIOLOGY REPORT</span></h2>'
            '<div class="patient-details">'
                f'<div class="patient-detail-item"><span class="detail-label">Patient Name:</span><span class="detail-value">{patient_info["name"]}</span></div>'
                f'<div class="patient-detail-item"><span class="detail-label">MRN:</span><span class="detail-value">{patient_info["medical_record_number"]}</span></div>'
                f'<div class="patient-detail-item"><span class="detail-label">Study Date:</span><span class="detail-value">{patient_info.get("date_of_study", current_date)}</span></div>'
                f'<div class="patient-detail-item"><span class="detail-label">Report Date:</span><span class="detail-value">{current_date} at {current_time}</span></div>'
                f'<div class="patient-detail-item"><span class="detail-label">Referring Physician:</span><span class="detail-value">Dr. {patient_info["referring_physician"]}</span></div>'
                f'<div class="patient-detail-item"><span class="detail-label">Radiologist:</span><span class="detail-value">MediVision AI Assistant</span></div>'
            '</div>'
        '</div>'
    )

    report_footer = (
        '<div class="report-footer" style="background: #f9f9f9; padding: 15px; border-radius: 5px; margin-top: 20px; text-align: center; font-size: 0.85em; color: #666;">'
            f'<strong>Report Generated by:</strong> MediVision AI Assistant<br>'
            f'<strong>Supervising Physician:</strong> Dr. {patient_info["referring_physician"]}<br>'
            '<strong>Institution:</strong> MediVision Radiology Center<br>'
            f'<strong>Generated on:</strong> {current_date} at {current_time}<br>'
            '<em>This report has been generated using advanced AI technology and should be reviewed by a qualified radiologist.</em>'
        '</div>'
    )

    # --- Stream the response ---
    report_container = st.empty()
    response_text_accumulated = ""
    
    for char in response_text:
        response_text_accumulated += char
        formatted_content = format_text_to_html(response_text_accumulated)
        content_html = (
            '<div class="report-content" style="background: white; padding: 20px; border-radius: 10px; margin-top: 10px; border-left: 4px solid #2c5aa0; box-shadow: 0 3px 15px rgba(0,0,0,0.1);">'
                f'{formatted_content}'
            '</div>'
        )
        full_report_so_far = f'<div class="ai-response">{report_header}{content_html}</div>'
        report_container.markdown(full_report_so_far, unsafe_allow_html=True)
        time.sleep(0.01)
            
    # Final report with footer
    final_formatted_content = format_text_to_html(response_text_accumulated)
    final_content_html = (
         '<div class="report-content" style="background: white; padding: 20px; border-radius: 10px; margin-top: 10px; border-left: 4px solid #2c5aa0; box-shadow: 0 3px 15px rgba(0,0,0,0.1);">'
            f'{final_formatted_content}'
        '</div>'
    )
    final_full_report = f'<div class="ai-response">{report_header}{final_content_html}{report_footer}</div>'
    report_container.markdown(final_full_report, unsafe_allow_html=True)

if __name__ == "__main__":
    main()