File size: 39,256 Bytes
41a320c
 
 
 
3a338e5
 
41a320c
 
3a338e5
 
 
41a320c
 
 
a4126ee
3a338e5
 
 
 
a4126ee
 
 
 
 
 
 
 
 
 
 
 
 
 
3a338e5
 
 
a4126ee
41a320c
 
3a338e5
 
a4126ee
41a320c
 
 
 
485f265
 
 
 
 
 
41a320c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4126ee
 
41a320c
3a338e5
 
41a320c
 
 
 
3a338e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41a320c
 
 
 
 
 
 
72123d0
 
 
41a320c
 
 
 
 
 
 
 
 
 
 
 
 
3a338e5
 
41a320c
 
3a338e5
 
41a320c
 
 
 
 
 
 
 
 
72123d0
 
 
 
 
 
 
 
 
41a320c
 
 
3a338e5
 
 
 
 
 
 
41a320c
 
 
3a338e5
 
 
 
 
 
41a320c
 
 
 
 
 
 
 
 
 
 
 
 
72123d0
 
 
 
 
 
 
 
 
41a320c
 
 
 
 
 
 
3a338e5
 
 
 
 
 
41a320c
3a338e5
41a320c
3a338e5
 
41a320c
 
3a338e5
 
41a320c
 
3a338e5
41a320c
 
 
3a338e5
 
 
 
 
 
 
41a320c
 
 
3a338e5
 
 
 
 
 
41a320c
 
3a338e5
 
 
 
 
 
41a320c
3a338e5
41a320c
3a338e5
41a320c
 
3a338e5
41a320c
 
 
3a338e5
 
 
 
41a320c
 
 
3a338e5
 
 
 
 
 
41a320c
 
3a338e5
41a320c
3a338e5
41a320c
3a338e5
 
41a320c
3a338e5
 
41a320c
3a338e5
 
41a320c
3a338e5
 
 
 
 
 
41a320c
 
 
3a338e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41a320c
 
 
 
 
 
 
3a338e5
41a320c
3a338e5
 
41a320c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a338e5
 
 
 
 
 
 
 
 
41a320c
3a338e5
41a320c
3a338e5
 
41a320c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
485f265
 
 
 
41a320c
485f265
09ab9b3
41a320c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a338e5
41a320c
 
 
 
3a338e5
41a320c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a338e5
41a320c
 
 
 
 
 
3a338e5
41a320c
 
 
 
3a338e5
 
 
 
41a320c
3a338e5
 
 
 
41a320c
 
 
 
 
 
 
 
 
 
 
 
 
 
485f265
 
 
 
 
 
 
 
 
 
 
 
09ab9b3
 
 
 
 
41a320c
 
 
09ab9b3
41a320c
09ab9b3
 
 
41a320c
 
 
 
 
 
 
 
72123d0
 
 
 
 
 
 
 
 
 
 
 
 
41a320c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a338e5
 
 
 
41a320c
 
 
 
 
 
72123d0
 
 
 
 
 
 
 
 
41a320c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72123d0
 
 
09ab9b3
485f265
 
 
 
 
 
 
72123d0
 
 
 
 
 
 
 
 
 
 
485f265
72123d0
41a320c
72123d0
41a320c
 
 
 
72123d0
41a320c
 
 
 
a4126ee
 
 
 
 
 
 
 
 
 
 
 
 
 
41a320c
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
"""
κ°„ν˜Έ μΈμˆ˜μΈκ³„ ꡐ윑 ν”Œλž«νΌ - Gradio λ©€ν‹°νŽ˜μ΄μ§€ μ• ν”Œλ¦¬μΌ€μ΄μ…˜ (μ±„νŒ… 기반)
"""

import os

import gradio as gr
from services.gemini_service import GeminiEvaluator
from services.supabase_service import SupabaseService

from config.database import supabase_client

# λ°μ΄ν„°λ² μ΄μŠ€ μ΄ˆκΈ°ν™”
try:
    print("πŸ”— λ°μ΄ν„°λ² μ΄μŠ€ μ—°κ²° μ‹œλ„ 쀑...")
    
    # Supabase μ„œλΉ„μŠ€ μ΄ˆκΈ°ν™”
    if supabase_client:
        try:
            supabase_service = SupabaseService()
            print("βœ… Supabase ν΄λΌμ΄μ–ΈνŠΈ μ΄ˆκΈ°ν™” μ™„λ£Œ")
            
            # μ‹œλ‚˜λ¦¬μ˜€ 데이터 λ‘œλ“œ (ν…Œμ΄λΈ”μ΄ μ—†λŠ” 경우 λ¬΄μ‹œ)
            try:
                print("πŸ“₯ μ‹œλ‚˜λ¦¬μ˜€ 데이터 λ‘œλ“œ 쀑...")
                supabase_service.load_scenarios_from_json("data/scenarios.json")
                print("βœ… μ‹œλ‚˜λ¦¬μ˜€ 데이터 λ‘œλ“œ μ™„λ£Œ")
            except Exception as load_error:
                print(f"⚠️  μ‹œλ‚˜λ¦¬μ˜€ 데이터 λ‘œλ“œ μ‹€νŒ¨: {load_error}")
                print("   (이미 데이터가 μžˆκ±°λ‚˜ ν…Œμ΄λΈ”μ΄ 없을 수 μžˆμŠ΅λ‹ˆλ‹€)")
        except Exception as service_error:
            print(f"⚠️  Supabase μ„œλΉ„μŠ€ μ΄ˆκΈ°ν™” μ‹€νŒ¨: {service_error}")
            supabase_service = None
    else:
        print("⚠️  Supabase ν΄λΌμ΄μ–ΈνŠΈκ°€ μ΄ˆκΈ°ν™”λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
        print("   ν™˜κ²½ λ³€μˆ˜ SUPABASE_URLκ³Ό SUPABASE_ANON_KEYλ₯Ό ν™•μΈν•˜μ„Έμš”.")
        supabase_service = None
except Exception as e:
    print(f"⚠️  λ°μ΄ν„°λ² μ΄μŠ€ μ΄ˆκΈ°ν™” 쀑 였λ₯˜: {e}")
    import traceback
    traceback.print_exc()
    supabase_service = None

# Gemini 평가기 μ΄ˆκΈ°ν™”
evaluator = GeminiEvaluator()

# 초기 학생 ID 생성 (TSID 기반)
from tsidpy import TSID

tsid = TSID.create()
initial_student_id = f"student_{tsid.to_string()}"


# ===== EMR HTML 생성 ν•¨μˆ˜λ“€ (κΈ°μ‘΄ 둜직 μž¬μ‚¬μš©) =====

def create_emr_html(patient, scenario):
    """μ‹€μ œ 병원 EMRκ³Ό μœ μ‚¬ν•œ HTML 생성"""
    vitals = scenario.vitals or {}
    labs = scenario.labs or {}
    orders = scenario.orders or []
    nursing_notes = scenario.nursing_notes or []

    # EMR 헀더
    emr_html = f"""
    <div style="font-family: 'Malgun Gothic', sans-serif; background: #f5f5f5; padding: 15px; border-radius: 8px;">
        <!-- ν™˜μž κΈ°λ³Έ 정보 헀더 -->
        <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px; border-radius: 8px; margin-bottom: 15px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
            <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px;">
                <div>
                    <div style="font-size: 11px; opacity: 0.9;">ν™˜μžλͺ… / λ“±λ‘λ²ˆν˜Έ</div>
                    <div style="font-size: 16px; font-weight: bold; margin-top: 5px;">{patient.name} / {patient.id}</div>
                </div>
                <div>
                    <div style="font-size: 11px; opacity: 0.9;">λ‚˜μ΄/성별 / 병싀</div>
                    <div style="font-size: 16px; font-weight: bold; margin-top: 5px;">{patient.age}μ„Έ / {patient.gender} / {patient.room_number}</div>
                </div>
                <div>
                    <div style="font-size: 11px; opacity: 0.9;">μž…μ›μΌ / μž¬μ›μΌμˆ˜</div>
                    <div style="font-size: 16px; font-weight: bold; margin-top: 5px;">{patient.admission_date} / D+{scenario.hospital_day}</div>
                </div>
            </div>
            <div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid rgba(255,255,255,0.3);">
                <div style="font-size: 11px; opacity: 0.9;">진단λͺ…</div>
                <div style="font-size: 14px; font-weight: bold; margin-top: 5px;">{patient.diagnosis}</div>
            </div>
        </div>
        
        <!-- μ•Œλ ˆλ₯΄κΈ° / κ²½κ³  -->
        <div style="background: {'#fff3cd' if patient.allergies != 'μ—†μŒ' else '#d4edda'}; border-left: 4px solid {'#ffc107' if patient.allergies != 'μ—†μŒ' else '#28a745'}; padding: 12px; margin-bottom: 15px; border-radius: 4px;">
            <strong>⚠️ μ•Œλ ˆλ₯΄κΈ°:</strong> {patient.allergies} &nbsp;&nbsp;|&nbsp;&nbsp; 
            <strong>πŸ“‹ κ³Όκ±°λ ₯:</strong> {patient.comorbidities} &nbsp;&nbsp;|&nbsp;&nbsp;
            <strong>πŸ‘¨β€βš•οΈ λ‹΄λ‹Ήμ˜:</strong> {patient.attending_physician}
        </div>
        
        <!-- ν™œλ ₯μ§•ν›„ νŒ¨λ„ -->
        <div style="background: white; padding: 15px; border-radius: 8px; margin-bottom: 15px; box-shadow: 0 1px 4px rgba(0,0,0,0.1);">
            <div style="font-size: 14px; font-weight: bold; color: #333; margin-bottom: 12px; padding-bottom: 8px; border-bottom: 2px solid #667eea;">
                πŸ“Š ν™œλ ₯μ§•ν›„ <span style="font-size: 12px; color: #666; font-weight: normal;">({vitals.get('time', 'N/A')})</span>
            </div>
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px;">
                {create_vital_card('ν˜ˆμ••', 'BP', vitals.get('BP', 'N/A'), '100-140/60-90', vitals.get('BP', ''))}
                {create_vital_card('λ§₯λ°•', 'HR', vitals.get('HR', 'N/A'), '60-100', vitals.get('HR', ''))}
                {create_vital_card('호흑', 'RR', vitals.get('RR', 'N/A'), '12-20', vitals.get('RR', ''))}
                {create_vital_card('체온', 'BT', vitals.get('BT', 'N/A'), '36.0-37.5', vitals.get('BT', ''))}
                {create_vital_card('μ‚°μ†Œν¬ν™”λ„', 'SpO2', vitals.get('SpO2', 'N/A'), 'β‰₯95%', vitals.get('SpO2', ''))}
                {create_vital_card('톡증', 'Pain', vitals.get('Pain', 'N/A'), '0-3', vitals.get('Pain', ''))}
            </div>
        </div>
        
        <!-- 검사 κ²°κ³Ό νŒ¨λ„ -->
        <div style="background: white; padding: 15px; border-radius: 8px; margin-bottom: 15px; box-shadow: 0 1px 4px rgba(0,0,0,0.1);">
            <div style="font-size: 14px; font-weight: bold; color: #333; margin-bottom: 12px; padding-bottom: 8px; border-bottom: 2px solid #667eea;">
                πŸ§ͺ 검사 κ²°κ³Ό <span style="font-size: 12px; color: #666; font-weight: normal;">({labs.get('time', 'N/A')})</span>
            </div>
            {create_lab_results_table(labs)}
        </div>
        
        <!-- μ˜μ‚¬ 처방 νŒ¨λ„ -->
        <div style="background: white; padding: 15px; border-radius: 8px; margin-bottom: 15px; box-shadow: 0 1px 4px rgba(0,0,0,0.1);">
            <div style="font-size: 14px; font-weight: bold; color: #333; margin-bottom: 12px; padding-bottom: 8px; border-bottom: 2px solid #667eea;">
                πŸ’Š μ˜μ‚¬ 처방
            </div>
            <div style="font-size: 13px; line-height: 1.8;">
                {create_orders_list(orders)}
            </div>
        </div>
        
        <!-- κ°„ν˜Έ 기둝 νŒ¨λ„ -->
        <div style="background: white; padding: 15px; border-radius: 8px; margin-bottom: 15px; box-shadow: 0 1px 4px rgba(0,0,0,0.1);">
            <div style="font-size: 14px; font-weight: bold; color: #333; margin-bottom: 12px; padding-bottom: 8px; border-bottom: 2px solid #667eea;">
                πŸ“ κ°„ν˜Έ 기둝
            </div>
            <div style="font-size: 13px;">
                {create_nursing_notes_timeline(nursing_notes)}
            </div>
        </div>
        
        {create_surgery_info_panel(scenario) if scenario.surgery_info else ''}
        {create_discharge_education_panel(scenario) if scenario.discharge_education else ''}
    </div>
    """
    return emr_html


def create_vital_card(label, code, value, normal_range, raw_value):
    """ν™œλ ₯μ§•ν›„ μΉ΄λ“œ 생성"""
    is_abnormal = check_vital_abnormal(code, raw_value)
    bg_color = "#ffe6e6" if is_abnormal else "#e8f5e9"
    border_color = "#f44336" if is_abnormal else "#4caf50"
    icon = "⚠️" if is_abnormal else "βœ“"

    return f"""
    <div style="background: {bg_color}; border-left: 4px solid {border_color}; padding: 12px; border-radius: 4px; text-align: center;">
        <div style="font-size: 11px; color: #666; margin-bottom: 4px;">{label}</div>
        <div style="font-size: 18px; font-weight: bold; color: #333; margin: 6px 0;">{icon} {value}</div>
        <div style="font-size: 10px; color: #888;">정상: {normal_range}</div>
    </div>
    """


def check_vital_abnormal(code, value_str):
    """ν™œλ ₯μ§•ν›„ 이상 μ—¬λΆ€ 체크"""
    if not value_str or value_str == "N/A":
        return False

    import re
    numbers = re.findall(r"\d+\.?\d*", value_str)
    if not numbers:
        return False

    try:
        if code == "BP":
            bp_values = re.findall(r"(\d+)/(\d+)", value_str)
            if bp_values:
                systolic = int(bp_values[0][0])
                diastolic = int(bp_values[0][1])
                return systolic < 90 or systolic > 140 or diastolic < 60 or diastolic > 90
        elif code == "HR":
            hr = int(numbers[0])
            return hr < 60 or hr > 100
        elif code == "RR":
            rr = int(numbers[0])
            return rr < 12 or rr > 20
        elif code == "BT":
            bt = float(numbers[0])
            return bt < 36.0 or bt > 37.5
        elif code == "SpO2":
            spo2 = int(numbers[0])
            return spo2 < 95
        elif code == "Pain":
            pain = int(numbers[0])
            return pain > 3
    except (ValueError, IndexError):
        pass

    return False


def create_lab_results_table(labs):
    """검사 κ²°κ³Ό ν…Œμ΄λΈ” 생성"""
    if not labs:
        return "<div style='color: #999; text-align: center; padding: 20px;'>검사 κ²°κ³Ό μ—†μŒ</div>"

    html = '<table style="width: 100%; border-collapse: collapse; font-size: 12px;">'
    html += '<thead><tr style="background: #f8f9fa; font-weight: bold;">'
    html += '<th style="padding: 10px; text-align: left; border-bottom: 2px solid #dee2e6;">검사항λͺ©</th>'
    html += '<th style="padding: 10px; text-align: center; border-bottom: 2px solid #dee2e6;">κ²°κ³Ό</th>'
    html += '<th style="padding: 10px; text-align: center; border-bottom: 2px solid #dee2e6;">μ°Έκ³ λ²”μœ„</th>'
    html += '<th style="padding: 10px; text-align: center; border-bottom: 2px solid #dee2e6;">μƒνƒœ</th>'
    html += "</tr></thead><tbody>"

    # CBC κ²°κ³Ό
    if "CBC" in labs:
        cbc = labs["CBC"]
        html += create_lab_row("WBC", cbc.get("WBC", "N/A"), "4.0-10.0 Γ—10Β³/Β΅L", check_lab_abnormal("WBC", cbc.get("WBC", "")))
        html += create_lab_row("Hemoglobin", cbc.get("Hb", "N/A"), "13.0-17.0 g/dL (M)", check_lab_abnormal("Hb", cbc.get("Hb", "")))
        html += create_lab_row("Platelet", cbc.get("Plt", "N/A"), "150-400 Γ—10Β³/Β΅L", False)
        html += create_lab_row("Neutrophil", cbc.get("Neutrophil", "N/A"), "40-70%", False)

    # CRP
    if "CRP" in labs:
        html += create_lab_row("CRP", labs["CRP"], "<0.5 mg/dL", check_lab_abnormal("CRP", labs["CRP"]))

    # μ „ν•΄μ§ˆ
    if "BMP" in labs:
        bmp = labs["BMP"]
        html += create_lab_row("Sodium", f"{bmp.get('Na', 'N/A')} mmol/L", "136-145 mmol/L", False)
        html += create_lab_row("Potassium", f"{bmp.get('K', 'N/A')} mmol/L", "3.5-5.0 mmol/L", False)
        html += create_lab_row("Creatinine", f"{bmp.get('Cr', 'N/A')} mg/dL", "0.7-1.3 mg/dL", False)

    html += "</tbody></table>"
    return html


def create_lab_row(name, value, ref_range, is_abnormal):
    """검사 κ²°κ³Ό ν–‰ 생성"""
    status_icon = "πŸ”΄" if is_abnormal else "🟒"
    status_text = "비정상" if is_abnormal else "정상"
    row_bg = "#fff3f3" if is_abnormal else "white"

    return f"""
    <tr style="background: {row_bg}; border-bottom: 1px solid #f0f0f0;">
        <td style="padding: 10px;">{name}</td>
        <td style="padding: 10px; text-align: center; font-weight: bold;">{value}</td>
        <td style="padding: 10px; text-align: center; color: #666; font-size: 11px;">{ref_range}</td>
        <td style="padding: 10px; text-align: center;">{status_icon} {status_text}</td>
    </tr>
    """


def check_lab_abnormal(lab_name, value_str):
    """검사 κ²°κ³Ό 이상 μ—¬λΆ€ 체크"""
    if "↑" in value_str or "↓" in value_str or "μƒμŠΉ" in value_str or "κ°μ†Œ" in value_str:
        return True
    return False


def create_orders_list(orders):
    """μ˜μ‚¬ 처방 λͺ©λ‘ 생성"""
    if not orders:
        return "<div style='color: #999;'>처방 μ—†μŒ</div>"

    html = '<div style="line-height: 1.9;">'
    for i, order in enumerate(orders, 1):
        if any(keyword in order for keyword in ["IV", "injection", "μ •μ£Ό", "주사"]):
            icon = "πŸ’‰"
        elif any(keyword in order for keyword in ["PO", "oral", "경ꡬ"]):
            icon = "πŸ’Š"
        elif "NPO" in order or "κΈˆμ‹" in order:
            icon = "🚫"
        elif any(keyword in order for keyword in ["수술", "surgery", "operation"]):
            icon = "πŸ”ͺ"
        else:
            icon = "πŸ“‹"

        html += f'<div style="padding: 6px 0; border-bottom: 1px dotted #e0e0e0;">{icon} <strong>{i}.</strong> {order}</div>'
    html += "</div>"
    return html


def create_nursing_notes_timeline(notes):
    """κ°„ν˜Έ 기둝 νƒ€μž„λΌμΈ 생성"""
    if not notes:
        return "<div style='color: #999;'>기둝 μ—†μŒ</div>"

    html = '<div style="position: relative; padding-left: 20px;">'
    for note in notes:
        time = note.get("time", "N/A")
        content = note.get("note", "")
        html += f"""
        <div style="position: relative; margin-bottom: 15px; padding: 12px; background: #f8f9fa; border-left: 3px solid #667eea; border-radius: 4px;">
            <div style="font-size: 11px; color: #667eea; font-weight: bold; margin-bottom: 5px;">πŸ• {time}</div>
            <div style="font-size: 13px; color: #333; line-height: 1.6;">{content}</div>
        </div>
        """
    html += "</div>"
    return html


def create_surgery_info_panel(scenario):
    """수술 정보 νŒ¨λ„ 생성"""
    if not scenario.surgery_info:
        return ""

    surgery = scenario.surgery_info
    return f"""
    <div style="background: #fff8e1; padding: 15px; border-radius: 8px; margin-bottom: 15px; box-shadow: 0 1px 4px rgba(0,0,0,0.1); border-left: 4px solid #ffa726;">
        <div style="font-size: 14px; font-weight: bold; color: #333; margin-bottom: 12px;">
            πŸ₯ 수술 정보
        </div>
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; font-size: 13px;">
            <div><strong>μˆ μ‹:</strong> {surgery.get('procedure', 'N/A')}</div>
            <div><strong>μˆ˜μˆ μ‹œκ°„:</strong> {surgery.get('time', 'N/A')}</div>
            <div><strong>μΆœν˜ˆλŸ‰:</strong> {surgery.get('EBL', 'N/A')}</div>
            <div><strong>μˆ˜μ•‘λŸ‰:</strong> {surgery.get('fluids', 'N/A')}</div>
            <div style="grid-column: 1 / -1;"><strong>μ†Œκ²¬:</strong> {surgery.get('findings', 'N/A')}</div>
            <div style="grid-column: 1 / -1;"><strong>합병증:</strong> {surgery.get('complications', 'μ—†μŒ')}</div>
        </div>
    </div>
    """


def create_discharge_education_panel(scenario):
    """퇴원 ꡐ윑 νŒ¨λ„ 생성"""
    if not scenario.discharge_education:
        return ""

    html = """
    <div style="background: #e8f5e9; padding: 15px; border-radius: 8px; margin-bottom: 15px; box-shadow: 0 1px 4px rgba(0,0,0,0.1); border-left: 4px solid #4caf50;">
        <div style="font-size: 14px; font-weight: bold; color: #333; margin-bottom: 12px;">
            πŸ“š 퇴원 ꡐ윑
        </div>
        <div style="font-size: 13px; line-height: 1.8;">
    """

    for edu in scenario.discharge_education:
        html += f'<div style="padding: 6px 0; border-bottom: 1px dotted #c8e6c9;">βœ“ {edu}</div>'

    html += "</div></div>"
    return html


# ===== 핡심 둜직 ν•¨μˆ˜λ“€ =====

def load_scenario_data(scenario_id: str):
    """μ‹œλ‚˜λ¦¬μ˜€ 선택 μ‹œ EMR 데이터 λ‘œλ“œ"""
    if not scenario_id:
        return None, None, ""

    if not supabase_service:
        return None, None, "Supabase μ„œλΉ„μŠ€κ°€ μ΄ˆκΈ°ν™”λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€."

    scenario = supabase_service.get_scenario(scenario_id)
    patient = supabase_service.get_patient(scenario['patient_id']) if scenario else None

    if not scenario or not patient:
        return None, None, "μ‹œλ‚˜λ¦¬μ˜€λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."

    # Supabase 데이터λ₯Ό 객체처럼 μ‚¬μš©ν•  수 μžˆλ„λ‘ λž˜ν•‘
    class Scenario:
        def __init__(self, data):
            self.id = data['id']
            self.patient_id = data['patient_id']
            self.title = data['title']
            self.hospital_day = data.get('hospital_day')
            self.vitals = data.get('vitals')
            self.labs = data.get('labs')
            self.orders = data.get('orders')
            self.nursing_notes = data.get('nursing_notes')
            self.surgery_info = data.get('surgery_info')
            self.discharge_education = data.get('discharge_education')

    class Patient:
        def __init__(self, data):
            self.id = data['id']
            self.name = data['name']
            self.age = data['age']
            self.gender = data['gender']
            self.diagnosis = data['diagnosis']
            self.admission_date = data['admission_date']
            self.allergies = data['allergies']
            self.comorbidities = data.get('comorbidities', '')
            self.attending_physician = data.get('attending_physician', '')
            self.room_number = data.get('room_number', '')

    scenario_obj = Scenario(scenario)
    patient_obj = Patient(patient)
    emr_display = create_emr_html(patient_obj, scenario_obj)
    return scenario_obj, patient_obj, emr_display


def handle_chat_message(message, chat_history, session_id, student_id, scenario_id):
    """μ±„νŒ… λ©”μ‹œμ§€ 처리"""
    if not message or not message.strip():
        return chat_history, ""
    
    # μ„Έμ…˜ ID 확인
    print(f"πŸ’¬ μ±„νŒ… λ©”μ‹œμ§€ 처리: session_id={session_id}, student_id={student_id}, scenario_id={scenario_id}")
    
    # μ‹œλ‚˜λ¦¬μ˜€κ°€ μ„ νƒλ˜μ§€ μ•Šμ€ 경우
    if not scenario_id or scenario_id == "":
        warning_msg = """
⚠️ **μ‹œλ‚˜λ¦¬μ˜€λ₯Ό λ¨Όμ € μ„ νƒν•΄μ£Όμ„Έμš”!**

1. **EMR 정보 쑰회** νƒ­μœΌλ‘œ μ΄λ™ν•˜μ„Έμš”
2. μ‹œλ‚˜λ¦¬μ˜€ λ“œλ‘­λ‹€μš΄μ—μ„œ μ‹œλ‚˜λ¦¬μ˜€λ₯Ό μ„ νƒν•˜μ„Έμš”
3. EMR 정보λ₯Ό ν™•μΈν•œ ν›„ λ‹€μ‹œ 이 νŽ˜μ΄μ§€λ‘œ λŒμ•„μ™€ μ±„νŒ…μ„ μ‹œμž‘ν•˜μ„Έμš”

ν˜„μž¬ μ„ νƒλœ μ‹œλ‚˜λ¦¬μ˜€: μ—†μŒ
"""
        return chat_history + [[message, warning_msg]], ""

    # Supabase μ„œλΉ„μŠ€ μ—°κ²°
    supabase_service = SupabaseService()

    # μ‹œλ‚˜λ¦¬μ˜€ 및 ν™˜μž 정보 쑰회
    scenario = supabase_service.get_scenario(scenario_id)
    patient = supabase_service.get_patient(scenario['patient_id']) if scenario else None

    if not scenario or not patient:
        error_msg = """
❌ **μ‹œλ‚˜λ¦¬μ˜€ 정보λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.**

EMR 정보 쑰회 νƒ­μ—μ„œ μ‹œλ‚˜λ¦¬μ˜€λ₯Ό λ‹€μ‹œ μ„ νƒν•΄μ£Όμ„Έμš”.
"""
        return chat_history + [[message, error_msg]], ""

    # μ‚¬μš©μž λ©”μ‹œμ§€ μ €μž₯ (session_idκ°€ μžˆλŠ” κ²½μš°μ—λ§Œ)
    if session_id:
        try:
            supabase_service.save_chat_message(session_id, student_id, scenario_id, "user", message)
            print(f"βœ… μ‚¬μš©μž λ©”μ‹œμ§€ μ €μž₯ μ™„λ£Œ: session_id={session_id}")
        except Exception as e:
            print(f"⚠️  μ‚¬μš©μž λ©”μ‹œμ§€ μ €μž₯ μ‹€νŒ¨: {e}")
    else:
        print(f"⚠️  session_idκ°€ λΉ„μ–΄μžˆμ–΄ λ©”μ‹œμ§€ μ €μž₯ μ‹€νŒ¨")

    # μ‹œλ‚˜λ¦¬μ˜€ 및 ν™˜μž 데이터 μ€€λΉ„
    scenario_data = {
        "title": scenario['title'],
        "handoff_situation": scenario.get('handoff_situation'),
        "hospital_day": scenario.get('hospital_day'),
        "vitals": scenario.get('vitals'),
        "labs": scenario.get('labs'),
        "orders": scenario.get('orders'),
        "nursing_notes": scenario.get('nursing_notes'),
    }

    patient_data = {
        "name": patient['name'],
        "age": patient['age'],
        "gender": patient['gender'],
        "diagnosis": patient['diagnosis'],
        "admission_date": str(patient['admission_date']),
        "allergies": patient['allergies'],
    }

    # 이전 μ±„νŒ… 기둝 ν¬λ§·νŒ… (Gemini용)
    history_for_gemini = []
    for user_msg, bot_msg in chat_history:
        if user_msg:
            history_for_gemini.append(("user", user_msg))
        if bot_msg:
            history_for_gemini.append(("assistant", bot_msg))

    # Gemini AI ν”Όλ“œλ°± 생성
    ai_response = evaluator.chat_feedback(message, history_for_gemini, scenario_data, patient_data)

    # AI 응닡 μ €μž₯ (session_idκ°€ μžˆλŠ” κ²½μš°μ—λ§Œ)
    if session_id:
        try:
            supabase_service.save_chat_message(session_id, student_id, scenario_id, "assistant", ai_response)
            print(f"βœ… AI 응닡 μ €μž₯ μ™„λ£Œ: session_id={session_id}")
        except Exception as e:
            print(f"⚠️  AI 응닡 μ €μž₯ μ‹€νŒ¨: {e}")
    else:
        print(f"⚠️  session_idκ°€ λΉ„μ–΄μžˆμ–΄ AI 응닡 μ €μž₯ μ‹€νŒ¨")

    # μ±„νŒ… νžˆμŠ€ν† λ¦¬ μ—…λ°μ΄νŠΈ
    updated_history = chat_history + [[message, ai_response]]

    return updated_history, ""


def finalize_chat_session(chat_history, session_id, student_id, scenario_id):
    """
    μ±„νŒ… μ’…λ£Œ μ‹œ 전체 λŒ€ν™”λ₯Ό λΆ„μ„ν•˜μ—¬ ν”Όλ“œλ°± 제곡
    - 점수 없이 질적 ν”Όλ“œλ°±λ§Œ 제곡
    - 전체 λŒ€ν™” λ‚΄μš©μ„ Geminiμ—κ²Œ 전달
    """
    if not chat_history:
        return chat_history + [[None, "λŒ€ν™”κ°€ μ—†μŠ΅λ‹ˆλ‹€. λ¨Όμ € λŒ€ν™”λ₯Ό μ‹œμž‘ν•΄μ£Όμ„Έμš”."]], ""
    
    # Supabase μ„œλΉ„μŠ€ μ—°κ²°
    supabase_service = SupabaseService()
    
    # μ‹œλ‚˜λ¦¬μ˜€ 및 ν™˜μž 정보 쑰회
    scenario = supabase_service.get_scenario(scenario_id)
    patient = supabase_service.get_patient(scenario['patient_id']) if scenario else None
    
    if not scenario or not patient:
        return chat_history + [[None, "μ‹œλ‚˜λ¦¬μ˜€ 정보λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."]], ""
    
    # μ‹œλ‚˜λ¦¬μ˜€ 및 ν™˜μž 데이터 μ€€λΉ„
    scenario_data = {
        "title": scenario['title'],
        "handoff_situation": scenario.get('handoff_situation'),
        "hospital_day": scenario.get('hospital_day'),
        "vitals": scenario.get('vitals'),
        "labs": scenario.get('labs'),
        "orders": scenario.get('orders'),
        "nursing_notes": scenario.get('nursing_notes'),
    }
    
    patient_data = {
        "name": patient['name'],
        "age": patient['age'],
        "gender": patient['gender'],
        "diagnosis": patient['diagnosis'],
        "admission_date": str(patient['admission_date']),
        "allergies": patient['allergies'],
    }
    
    # 전체 λŒ€ν™”λ₯Ό Geminiμ—κ²Œ μ „λ‹¬ν•˜μ—¬ 평가
    evaluation = evaluator.evaluate_conversation(
        chat_history=chat_history,
        scenario_data=scenario_data,
        patient_data=patient_data
    )
    
    # λ°μ΄ν„°λ² μ΄μŠ€μ— μ €μž₯ (점수 없이)
    try:
        record = supabase_service.create_handoff_record(
            student_id=student_id,
            scenario_id=scenario_id,
            sbar_data={},  # λŒ€ν™” 기반 ν‰κ°€μ΄λ―€λ‘œ SBAR λ°μ΄ν„°λŠ” 비움
            evaluation=evaluation,
            session_id=session_id
        )
        print(f"βœ… μΈμˆ˜μΈκ³„ 기둝 μ €μž₯ μ™„λ£Œ (ID: {record.get('id')})")
        
        # μ„Έμ…˜ μƒνƒœλ₯Ό 'completed'둜 λ³€κ²½
        supabase_service.update_session_status(session_id, 'completed')
    except Exception as e:
        print(f"⚠️  λ°μ΄ν„°λ² μ΄μŠ€ μ €μž₯ 였λ₯˜: {e}")
    
    # ν”Όλ“œλ°± λ©”μ‹œμ§€ ν¬λ§·νŒ… (점수 없이)
    strengths = evaluation.get('strengths', [])
    improvements = evaluation.get('improvements', [])
    detailed_feedback = evaluation.get('detailed_feedback', '')
    missing_info = evaluation.get('missing_critical_info', [])
    safety_concerns = evaluation.get('safety_concerns', [])
    
    result_message = f"""
πŸŽ“ **ν•™μŠ΅ μ’…ν•© ν”Όλ“œλ°±**

{'='*50}

### πŸ’ͺ μž˜ν•œ 점
{chr(10).join([f"- {s}" for s in strengths]) if strengths else "- μ—†μŒ"}

### πŸ“ˆ κ°œμ„ ν•  점
{chr(10).join([f"- {i}" for i in improvements]) if improvements else "- μ—†μŒ"}

### πŸ” μ’…ν•© 의견
{detailed_feedback if detailed_feedback else "μ’…ν•© ν”Όλ“œλ°±μ΄ μ—†μŠ΅λ‹ˆλ‹€."}

"""
    
    if missing_info:
        result_message += f"""
### ⚠️ λˆ„λ½λœ μ€‘μš” 정보
{chr(10).join([f"- {m}" for m in missing_info])}

"""
    
    if safety_concerns:
        result_message += f"""
### πŸ₯ ν™˜μž μ•ˆμ „ κ΄€λ ¨ μ£Όμ˜μ‚¬ν•­
{chr(10).join([f"- {s}" for s in safety_concerns])}

"""
    
    result_message += f"""
{'='*50}

μˆ˜κ³ ν•˜μ…¨μŠ΅λ‹ˆλ‹€! λ‹€λ₯Έ μ‹œλ‚˜λ¦¬μ˜€λ‘œ μ—°μŠ΅μ„ κ³„μ†ν•˜μ‹œλ €λ©΄ 
EMR νŽ˜μ΄μ§€λ‘œ λŒμ•„κ°€ μƒˆλ‘œμš΄ μ‹œλ‚˜λ¦¬μ˜€λ₯Ό μ„ νƒν•˜μ„Έμš”.
"""
    
    return chat_history + [[None, result_message]], ""


def get_student_history(student_id: str):
    """학생 μΈμˆ˜μΈκ³„ 이λ ₯ 쑰회 (κ΄€λ¦¬μžμš©)"""
    if not student_id:
        return "학생 IDλ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”."

    supabase_service = SupabaseService()

    stats = supabase_service.get_student_statistics(student_id)
    records = supabase_service.get_records_by_student(student_id)

    if stats["total_submissions"] == 0:
        return f"학생 ID '{student_id}'의 제좜 기둝이 μ—†μŠ΅λ‹ˆλ‹€."

    history = f"""
# 학생 μΈμˆ˜μΈκ³„ 이λ ₯

**학생 ID**: {student_id}

## 톡계
- **총 제좜 횟수**: {stats['total_submissions']}회
- **평균 점수**: {stats['average_score']:.1f}점
- **졜고 점수**: {stats['highest_score']:.1f}점
- **μ΅œμ € 점수**: {stats['lowest_score']:.1f}점

## 졜근 제좜 기둝
"""

    for i, record in enumerate(records[:10], 1):
        submitted_time = record.get('submitted_at', 'N/A')
        if submitted_time and isinstance(submitted_time, str):
            # ISO ν˜•μ‹μ—μ„œ μ‹œκ°„ μΆ”μΆœ
            try:
                from datetime import datetime
                dt = datetime.fromisoformat(submitted_time.replace('Z', '+00:00'))
                submitted_time = dt.strftime("%Y-%m-%d %H:%M")
            except:
                pass
        history += f"""
### {i}. {record.get('scenario_id', 'N/A')}
- **제좜 μ‹œκ°„**: {submitted_time}
- **점수**: {record.get('total_score', 0):.1f}점
- **강점**: {', '.join(record.get('strengths', [])[:2]) if record.get('strengths') else 'N/A'}
---
"""

    return history


# ===== Gradio UI ꡬ성 =====

with gr.Blocks(title="κ°„ν˜Έ μΈμˆ˜μΈκ³„ ꡐ윑 ν”Œλž«νΌ", theme=gr.themes.Soft()) as app:
    
    # μ „μ—­ μƒνƒœ λ³€μˆ˜
    session_id_state = gr.State(value="")
    student_id_state = gr.State(value="")
    scenario_id_state = gr.State(value="S001_D0_ER_WARD")  # κΈ°λ³Έκ°’ μ„€μ •
    user_role_state = gr.State(value="student")
    
    gr.Markdown("""
    # πŸ₯ κ°„ν˜Έ μΈμˆ˜μΈκ³„ ꡐ윑 ν”Œλž«νΌ (μ±„νŒ… 기반)
    
    SBAR ν˜•μ‹μœΌλ‘œ ν™˜μž μΈμˆ˜μΈκ³„λ₯Ό μ—°μŠ΅ν•˜κ³  AI와 λŒ€ν™”ν•˜λ©° ν”Όλ“œλ°±μ„ λ°›μ•„λ³΄μ„Έμš”.
    """)
    
    # 초기 μ„€μ • μ„Ήμ…˜
    with gr.Row():
        with gr.Column():
            student_id_input = gr.Textbox(
                label="πŸ‘€ 학생 ID (μžλ™ 생성됨)", 
                value=initial_student_id,
                interactive=False,
                info="μžλ™μœΌλ‘œ μƒμ„±λœ 고유 IDμž…λ‹ˆλ‹€. 'μƒˆ ID 생성' λ²„νŠΌμœΌλ‘œ μƒˆ IDλ₯Ό 받을 수 μžˆμŠ΅λ‹ˆλ‹€."
            )
            with gr.Row():
                generate_id_btn = gr.Button("πŸ”„ μƒˆ ID 생성", variant="secondary")
    
    # νƒ­ ꡬ성
    with gr.Tabs() as tabs:
        # νŽ˜μ΄μ§€ 1: EMR 정보 쑰회
        with gr.Tab("πŸ“Š EMR 정보 쑰회", id=0) as tab_emr:
            gr.Markdown("## ν™˜μž μ „μžμ˜λ¬΄κΈ°λ‘ (EMR)")
            
            # μ‚¬μš© 방법과 μ‹œλ‚˜λ¦¬μ˜€ 선택을 ν•œ 행에 2μ—΄λ‘œ 배치
            with gr.Row():
                with gr.Column(scale=2):
                    gr.Markdown("""
                    **πŸ“Œ μ‚¬μš© 방법:**
                    1. μ‹œλ‚˜λ¦¬μ˜€λ₯Ό μ„ νƒν•˜μ„Έμš”
                    2. EMR 정보λ₯Ό μΆ©λΆ„νžˆ ν™•μΈν•˜μ„Έμš”
                    3. μ€€λΉ„κ°€ 되면 "λ‹΅μ•ˆ μž‘μ„±ν•˜λŸ¬ κ°€κΈ°" λ²„νŠΌμ„ ν΄λ¦­ν•˜μ„Έμš”
                    """)
                with gr.Column(scale=3):
                    scenario_dropdown = gr.Dropdown(
                        choices=[
                            ("Day 0 - 응급싀→병동 인계 (수술 μ „)", "S001_D0_ER_WARD"),
                            ("Day 0 - λ³‘λ™β†’μˆ˜μˆ μ‹€ 인계", "S001_D0_WARD_OR"),
                            ("Day 0 - νšŒλ³΅μ‹€β†’λ³‘λ™ 전동 (수술 ν›„)", "S001_D0_RECOVERY"),
                            ("Day 1 - μ•„μΉ¨ 인계 (POD1)", "S001_D1_MORNING"),
                            ("Day 2 - 퇴원 μ „ 인계 (POD2)", "S001_D2_DISCHARGE"),
                        ],
                        label="πŸ“‹ μ‹œλ‚˜λ¦¬μ˜€ 선택",
                        value="S001_D0_ER_WARD",
                        info="μ‹œλ‚˜λ¦¬μ˜€λ₯Ό μ„ νƒν•˜λ©΄ EMR 정보가 ν‘œμ‹œλ©λ‹ˆλ‹€"
                    )
            
            emr_display = gr.HTML(
                value="<div style='text-align: center; padding: 40px; color: #999;'>⬆️ μœ„μ—μ„œ μ‹œλ‚˜λ¦¬μ˜€λ₯Ό μ„ νƒν•˜μ„Έμš”.</div>"
            )
            
            go_to_chat_btn = gr.Button("πŸ’¬ λ‹΅μ•ˆ μž‘μ„±ν•˜λŸ¬ κ°€κΈ°", variant="primary", size="lg")
            gr.Markdown("""
            > πŸ’‘ **Tip**: EMR νŽ˜μ΄μ§€μ—μ„œ μ–Έμ œλ“ μ§€ "λ‹΅μ•ˆ μž‘μ„±" νƒ­μœΌλ‘œ 이동할 수 μžˆμŠ΅λ‹ˆλ‹€.
            """)
        
        # νŽ˜μ΄μ§€ 2: μ±„νŒ… 기반 λ‹΅μ•ˆ μž‘μ„±
        with gr.Tab("πŸ’¬ λ‹΅μ•ˆ μž‘μ„± (μ±„νŒ…)", id=1) as tab_chat:
            gr.Markdown("## AI κ΅μˆ˜μ™€ ν•¨κ»˜ν•˜λŠ” μΈμˆ˜μΈκ³„ μ—°μŠ΅")
            gr.Markdown("""
            **πŸ“Œ μ‹œμž‘ν•˜κΈ°:**
            1. κΈ°λ³Έ μ‹œλ‚˜λ¦¬μ˜€λŠ” **"Day 0 - 응급싀→병동 인계"**μž…λ‹ˆλ‹€ (μƒλ‹¨μ—μ„œ 확인 κ°€λŠ₯)
            2. EMR 정보λ₯Ό ν™•μΈν•˜λ €λ©΄ **"EMR 정보 쑰회"** 탭을 ν΄λ¦­ν•˜μ„Έμš”
            3. μ€€λΉ„κ°€ 되면 AI κ΅μˆ˜μ™€ 자유둭게 λŒ€ν™”ν•˜λ©° μΈμˆ˜μΈκ³„ λ‚΄μš©μ„ μž‘μ„±ν•˜μ„Έμš”
            """)
            
            with gr.Row():
                current_scenario_display = gr.Markdown("**ν˜„μž¬ μ‹œλ‚˜λ¦¬μ˜€**: λ‘œλ”© 쀑...")
                back_to_emr_btn = gr.Button("πŸ“Š EMR λ‹€μ‹œ 보기", size="sm", variant="secondary")
            
            chatbot = gr.Chatbot(
                label="AI κ΅μˆ˜μ™€ λŒ€ν™”",
                height=500,
                show_label=True
            )
            
            with gr.Row():
                msg_input = gr.Textbox(
                    label="λ©”μ‹œμ§€ μž…λ ₯",
                    placeholder="자유둭게 λŒ€ν™”ν•˜λ©° μΈμˆ˜μΈκ³„ λ‚΄μš©μ„ μž‘μ„±ν•˜κ±°λ‚˜, AI κ΅μˆ˜μ—κ²Œ μ§ˆλ¬Έν•˜μ„Έμš”...",
                    lines=3,
                    scale=4
                )
            
            with gr.Row():
                send_btn = gr.Button("전솑", variant="primary")
                finalize_btn = gr.Button("μ±„νŒ… μ’…λ£Œ 및 평가받기", variant="stop")
                clear_btn = gr.Button("λŒ€ν™” μ΄ˆκΈ°ν™”")
            
            gr.Markdown("""
            **μ‚¬μš© 방법:**
            1. 자유둭게 λŒ€ν™”ν•˜λ©° μΈμˆ˜μΈκ³„ λ‚΄μš©μ„ μž‘μ„±ν•˜μ„Έμš”
            2. AI κ΅μˆ˜κ°€ μ¦‰μ‹œ ν”Όλ“œλ°±μ„ μ œκ³΅ν•©λ‹ˆλ‹€
            3. ν”Όλ“œλ°±μ„ λ°”νƒ•μœΌλ‘œ μˆ˜μ •ν•˜κ³  더 λ‚˜μ€ λ‚΄μš©μ„ μž‘μ„±ν•  수 μžˆμŠ΅λ‹ˆλ‹€
            4. μ€€λΉ„κ°€ 되면 **μ±„νŒ… μ’…λ£Œ 및 평가받기** λ²„νŠΌμ„ 눌러 μ’…ν•© ν”Όλ“œλ°±μ„ λ°›μœΌμ„Έμš”
            
            **πŸ’‘ 팁:**
            - μžμ—°μŠ€λŸ¬μš΄ λŒ€ν™”λ‘œ λ°°μš°λŠ” 것이 ν•΅μ‹¬μž…λ‹ˆλ‹€
            - SBAR ν˜•μ‹μ„ κ°•μ œν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€. λŒ€ν™”λ₯Ό 톡해 μžλ™μœΌλ‘œ ν‰κ°€λ©λ‹ˆλ‹€
            - μ–Έμ œλ“ μ§€ AI κ΅μˆ˜μ—κ²Œ μ§ˆλ¬Έν•˜μ„Έμš”
            """)
        
        # νŽ˜μ΄μ§€ 3: κ΄€λ¦¬μž 이λ ₯ 쑰회
        with gr.Tab("πŸ“š 학생 이λ ₯ 쑰회 (κ΄€λ¦¬μž)", id=2, visible=False) as tab_admin:
            gr.Markdown("## 학생 μΈμˆ˜μΈκ³„ 이λ ₯ 쑰회")
            
            with gr.Row():
                history_student_id = gr.Textbox(label="학생 ID", placeholder="student001")
                history_btn = gr.Button("이λ ₯ 쑰회")
            
            history_display = gr.Markdown(value="")
    
    # ===== 이벀트 ν•Έλ“€λŸ¬ =====
    
    def generate_student_id():
        """TSID 기반 학생 ID 생성"""
        from tsidpy import TSID
        tsid = TSID.create()
        student_id = f"student_{tsid.to_string()}"
        return student_id
    
    def update_student_id():
        """μƒˆ 학생 ID 생성"""
        new_id = generate_student_id()
        return new_id
    
    # μƒˆ ID 생성 λ²„νŠΌ (student_id_state도 ν•¨κ»˜ μ—…λ°μ΄νŠΈ)
    def update_student_id_with_state():
        """μƒˆ 학생 ID 생성 및 μƒνƒœ μ—…λ°μ΄νŠΈ"""
        new_id = generate_student_id()
        is_admin = (new_id == "admin")
        role = "admin" if is_admin else "student"
        tab_visibility = gr.update(visible=is_admin)
        
        return new_id, new_id, role, tab_visibility
    
    generate_id_btn.click(
        fn=update_student_id_with_state,
        outputs=[student_id_input, student_id_state, user_role_state, tab_admin]
    )
    
    def select_scenario_and_create_session(scenario_id, student_id):
        """μ‹œλ‚˜λ¦¬μ˜€ 선택 및 μ„Έμ…˜ 생성"""
        scenario, patient, emr_html = load_scenario_data(scenario_id)
        
        if scenario:
            # μƒˆ μ±„νŒ… μ„Έμ…˜ 생성
            try:
                supabase_service = SupabaseService()
                new_session_id = supabase_service.create_chat_session(student_id, scenario_id)
                print(f"πŸ“ μ‹œλ‚˜λ¦¬μ˜€ 선택 μ‹œ μ„Έμ…˜ 생성: session_id={new_session_id}")
                
                scenario_info = f"**ν˜„μž¬ μ‹œλ‚˜λ¦¬μ˜€**: {scenario.title}"
                
                return emr_html, new_session_id, scenario_id, scenario_info
            except Exception as e:
                print(f"⚠️  μ„Έμ…˜ 생성 μ‹€νŒ¨: {e}")
                import traceback
                traceback.print_exc()
                return emr_html, "", scenario_id, "**ν˜„μž¬ μ‹œλ‚˜λ¦¬μ˜€**: μ„ νƒλ˜μ§€ μ•ŠμŒ"
        
        return emr_html, "", scenario_id, "**ν˜„μž¬ μ‹œλ‚˜λ¦¬μ˜€**: μ„ νƒλ˜μ§€ μ•ŠμŒ"
    
    scenario_dropdown.change(
        fn=select_scenario_and_create_session,
        inputs=[scenario_dropdown, student_id_state],
        outputs=[emr_display, session_id_state, scenario_id_state, current_scenario_display]
    )
    
    # μ±„νŒ… λ©”μ‹œμ§€ 전솑 (κ°œμ„ λœ 버전)
    send_btn.click(
        fn=handle_chat_message,
        inputs=[msg_input, chatbot, session_id_state, student_id_state, scenario_id_state],
        outputs=[chatbot, msg_input],
        show_progress="minimal"
    )
    
    msg_input.submit(
        fn=handle_chat_message,
        inputs=[msg_input, chatbot, session_id_state, student_id_state, scenario_id_state],
        outputs=[chatbot, msg_input],
        show_progress="minimal"
    )
    
    # μ±„νŒ… μ’…λ£Œ 및 평가
    finalize_btn.click(
        fn=finalize_chat_session,
        inputs=[chatbot, session_id_state, student_id_state, scenario_id_state],
        outputs=[chatbot, msg_input]
    )
    
    # λŒ€ν™” μ΄ˆκΈ°ν™”
    def clear_chat(student_id, scenario_id):
        """λŒ€ν™” μ΄ˆκΈ°ν™” 및 μƒˆ μ„Έμ…˜ 생성"""
        try:
            supabase_service = SupabaseService()
            new_session_id = supabase_service.create_chat_session(student_id, scenario_id)
            print(f"πŸ”„ λŒ€ν™” μ΄ˆκΈ°ν™” - μƒˆ μ„Έμ…˜ 생성: {new_session_id}")
            
            return [], new_session_id
        except Exception as e:
            print(f"⚠️  λŒ€ν™” μ΄ˆκΈ°ν™” 쀑 μ„Έμ…˜ 생성 μ‹€νŒ¨: {e}")
            return [], ""
    
    clear_btn.click(
        fn=clear_chat,
        inputs=[student_id_state, scenario_id_state],
        outputs=[chatbot, session_id_state]
    )
    
    # 이λ ₯ 쑰회
    history_btn.click(
        fn=get_student_history,
        inputs=[history_student_id],
        outputs=[history_display]
    )
    
    # λ²„νŠΌ ν•Έλ“€λŸ¬ μΆ”κ°€
    def navigate_to_chat(session_id, scenario_id):
        """μ±„νŒ… νŽ˜μ΄μ§€λ‘œ 이동"""
        return gr.update(selected=1)  # μ±„νŒ… νƒ­μœΌλ‘œ μ „ν™˜
    
    def navigate_to_emr():
        """EMR νŽ˜μ΄μ§€λ‘œ 이동"""
        return gr.update(selected=0)  # EMR νƒ­μœΌλ‘œ μ „ν™˜
    
    # λ‹΅μ•ˆ μž‘μ„±ν•˜κΈ° λ²„νŠΌ 클릭 μ‹œ μ±„νŒ… νŽ˜μ΄μ§€λ‘œ 이동
    go_to_chat_btn.click(
        fn=navigate_to_chat,
        inputs=[session_id_state, scenario_id_state],
        outputs=[tabs]
    )
    
    # EMR λ‹€μ‹œ 보기 λ²„νŠΌ 클릭 μ‹œ EMR νŽ˜μ΄μ§€λ‘œ 이동
    back_to_emr_btn.click(
        fn=navigate_to_emr,
        outputs=[tabs]
    )
    
    # 초기 λ‘œλ“œ ν•¨μˆ˜
    def initialize_app():
        """μ•± 초기 λ‘œλ“œ μ‹œ μ‹€ν–‰"""
        default_scenario = "S001_D0_ER_WARD"
        
        # student_id_stateλ₯Ό 초기 ID둜 μ„€μ • (λͺ¨λ“ˆ 레벨 λ³€μˆ˜ μ‚¬μš©)
        current_student_id = initial_student_id
        initial_session_id = ""
        
        # Supabase μ„œλΉ„μŠ€κ°€ 있으면 μ‹œλ‚˜λ¦¬μ˜€ 데이터 λ‘œλ“œ
        if supabase_service:
            scenario, patient, emr_html = load_scenario_data(default_scenario)
            
            if scenario:
                # κΈ°λ³Έ μ‹œλ‚˜λ¦¬μ˜€ 정보 ν‘œμ‹œ
                scenario_info = f"**ν˜„μž¬ μ‹œλ‚˜λ¦¬μ˜€**: {scenario.title}"
                
                # 초기 μ„Έμ…˜ 생성
                try:
                    initial_session_id = supabase_service.create_chat_session(current_student_id, default_scenario)
                    print(f"βœ… 초기 μ„Έμ…˜ 생성 μ™„λ£Œ: {initial_session_id}")
                except Exception as e:
                    print(f"⚠️  초기 μ„Έμ…˜ 생성 μ‹€νŒ¨: {e}")
                    import traceback
                    traceback.print_exc()
                
                return emr_html, default_scenario, scenario_info, current_student_id, "student", initial_session_id
            else:
                return emr_html, default_scenario, "**ν˜„μž¬ μ‹œλ‚˜λ¦¬μ˜€**: μ„ νƒλ˜μ§€ μ•ŠμŒ", current_student_id, "student", ""
        else:
            return "", default_scenario, "**ν˜„μž¬ μ‹œλ‚˜λ¦¬μ˜€**: μ„ νƒλ˜μ§€ μ•ŠμŒ", current_student_id, "student", ""
    
    # 초기 λ‘œλ“œ
    app.load(
        fn=initialize_app,
        outputs=[emr_display, scenario_id_state, current_scenario_display, student_id_state, user_role_state, session_id_state]
    )


if __name__ == "__main__":
    # Hugging Face Space ν™˜κ²½ 확인
    is_hf_space = bool(os.getenv("SPACE_ID") or os.getenv("HF_SPACE_ID"))
    
    if is_hf_space:
        # Hugging Face Spaceμ—μ„œ μ‹€ν–‰
        print("πŸš€ Hugging Face Spaceμ—μ„œ μ‹€ν–‰ 쀑...")
        # Queue μ„€μ •μœΌλ‘œ API 호좜 μ•ˆμ •μ„± ν–₯상
        app.queue()
        # SpaceλŠ” μžλ™μœΌλ‘œ ν˜ΈμŠ€νŒ…ν•˜λ―€λ‘œ μ΅œμ†Œ μ„€μ •
        app.launch(server_name="0.0.0.0", server_port=7860)
    else:
        # 둜컬/직접 μ‹€ν–‰
        print("🏠 둜컬 ν™˜κ²½μ—μ„œ μ‹€ν–‰ 쀑...")
        app.launch(server_name="0.0.0.0", server_port=7860, share=False)