File size: 37,483 Bytes
e8c7fad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# gradio_app.py
"""
Simplified Gradio Interface for Medical Brain with Background Spiritual Monitoring.

Single unified medical interface with invisible spiritual monitoring.
No mode selector - just medical dialog with automatic spiritual support.

Requirements: 1.3, 4.1, 4.2, 12.1, 12.2
"""

import os
import sys

# Ensure project root is in Python path
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if project_root not in sys.path:
    sys.path.insert(0, project_root)

from dotenv import load_dotenv

# Load environment variables
load_dotenv()

import gradio as gr

# Import modularized components
from src.interface.session_manager import SimplifiedSessionData
from src.interface import stats_handlers
from src.interface import chat_handlers
from src.interface import prompt_handlers
from src.interface import verification_handlers
from src.interface import profile_handlers
from src.interface import model_handlers

from src.core.simplified_medical_app import SimplifiedMedicalApp
from src.core.spiritual_state import SpiritualState
from src.interface.enhanced_verification_interface import create_enhanced_verification_tab
from src.interface.help_content import HELP_CONTENT

try:
    from app_config import (
        GRADIO_CONFIG, 
        ENHANCED_VERIFICATION_CONFIG,
        FEATURE_FLAGS,
        is_feature_enabled
    )
except ImportError:
    GRADIO_CONFIG = {"theme": "soft", "show_api": False}
    ENHANCED_VERIFICATION_CONFIG = {"enabled": True}
    FEATURE_FLAGS = {
        "enhanced_verification_enabled": True,
        "standard_verification_enabled": True,
        "show_mode_navigation_hints": True,
    }
    def is_feature_enabled(feature_name: str) -> bool:
        return FEATURE_FLAGS.get(feature_name, False)





def create_simplified_interface():
    """
    Create simplified Gradio interface.
    
    Single medical assistant interface with background spiritual monitoring.
    No mode selector - spiritual support is automatic and invisible.
    
    Requirements: 1.3, 4.1, 12.1
    """
    
    debug_mode = os.getenv("LOG_PROMPTS", "false").lower() == "true"
    
    # Theme setup
    theme_name = GRADIO_CONFIG.get("theme", "soft")
    if theme_name.lower() == "soft":
        theme = gr.themes.Soft()
    else:
        theme = gr.themes.Default()
    
    demo = gr.Blocks(
        title="πŸ₯ Medical Assistant with Spiritual Support",
        analytics_enabled=False
    )
    demo.theme = theme
    
    with demo:
        # Session state
        session_data = gr.State(value=None)
        
        # Header
        gr.Markdown("# πŸ₯ Medical Assistant with Spiritual Support πŸ•ŠοΈ")
        gr.Markdown("Your personal healthcare companion with integrated wellness support")
        
        if debug_mode:
            gr.Markdown("⚠️ **DEBUG MODE:** Prompts and responses are logged")
        
        # Session info
        session_info = gr.Markdown("πŸ”„ **Initializing session...**")
        
        # Initialize session
        def initialize_session():
            """Initialize new user session."""
            new_session = SimplifiedSessionData()
            session_info_text = f"""
βœ… **Session Ready**
πŸ†” Session: `{new_session.session_id[:8]}...`
πŸ•’ Started: {new_session.created_at[:19]}
"""
            return new_session, session_info_text
        
        # Main interface - using Tabs with elem_id for navigation
        main_tabs = gr.Tabs(elem_id="main_tabs")
        with main_tabs:
            # Note: The following tabs are intentionally hidden for now:
            # - ✏️ Edit Enhanced Datasets
            # - βœ“ Standard Verification
            # We keep the rest of the interface focused on Chat + Conversation Verification.
            
            # Chat tab
            with gr.TabItem("πŸ’¬ Chat", id="chat"):
                with gr.Row():
                    with gr.Column(scale=2):
                        chatbot = gr.Chatbot(
                            label="πŸ’¬ Conversation",
                            height=450
                        )
                        
                        with gr.Row():
                            msg = gr.Textbox(
                                label="Your message",
                                placeholder="Type your health question...",
                                scale=4
                            )
                            send_btn = gr.Button("πŸ“€ Send", scale=1, variant="primary")
                        
                        with gr.Row():
                            clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", scale=1)
                        
                        # Conversation logging section
                        gr.Markdown("### πŸ“Š Conversation Logs:")
                        with gr.Row():
                            download_json_btn = gr.DownloadButton("πŸ“₯ Download JSON", scale=1, size="sm")
                            download_csv_btn = gr.DownloadButton("πŸ“Š Download CSV", scale=1, size="sm")

                        # Conversation verification is available in the dedicated
                        # "🧾 Conversation Verification" tab.
                        
                        # Quick examples
                        gr.Markdown("### ⚑ Quick Start:")
                        with gr.Row():
                            example_medical = gr.Button("🟒 I am fine", size="sm")
                            example_wellness = gr.Button("🟑 I'm feeling stressed", size="sm")
                            example_help = gr.Button("πŸ”΄ Emotional crisis", size="sm")
                    
                    with gr.Column(scale=1):
                        status_box = gr.Markdown(
                            value="πŸ”„ Loading...",
                            label="πŸ“Š Status"
                        )
                        
                        refresh_btn = gr.Button("πŸ”„ Check Status & Summary", size="sm")
                        
                        # Conversation statistics
                        gr.Markdown("### πŸ“ˆ Conversation Stats")
                        conversation_stats = gr.Markdown(
                            value="No conversation yet",
                            label="Statistics"
                        )
                        
                        # Debug info (only in debug mode)
                        if debug_mode:
                            gr.Markdown("### πŸ”§ Debug Info")
                            debug_info = gr.Markdown(value="")
                    
                    # Provider Summary Panel (for RED flags) - always visible but content controlled
                    with gr.Column(scale=1) as provider_summary_column:
                        with gr.Group(visible=False) as provider_summary_content:
                            gr.Markdown("### πŸ“‹ Provider Summary")
                            gr.Markdown("*For Spiritual Care Team*", elem_classes=["provider-subtitle"])
                            
                            provider_summary_status = gr.Markdown(
                                value="**Provider Summary Generated**\n\nA detailed summary has been generated for the spiritual care team. Use the Download button below to access the full summary."
                            )
                            
                            # Tabs for different summary views (Medical Brain Summary first by default)
                            with gr.Tabs():
                                # Coherent Paragraph Tab (FIRST - Requirements 2.1-2.8) - Medical Brain compatibility
                                with gr.TabItem("πŸ“ Medical Brain Summary"):
                                    gr.Markdown("*Single paragraph format for Medical Brain compatibility - **Default View***")
                                    coherent_summary_display = gr.Textbox(
                                        value="",
                                        lines=8,
                                        label="Medical Brain Compatible Summary",
                                        interactive=False
                                    )
                                    with gr.Row():
                                        regenerate_coherent_btn = gr.Button(
                                            "πŸ”„ Regenerate Medical Brain Summary",
                                            size="sm",
                                            variant="secondary"
                                        )
                                        download_coherent_btn = gr.DownloadButton(
                                            "πŸ“₯ Download Medical Brain Summary",
                                            size="sm",
                                            variant="secondary"
                                        )
                                
                                # Structured Summary Tab (moved to second position)
                                with gr.TabItem("πŸ“Š Structured Summary"):
                                    provider_summary_display = gr.HTML(value="")
                            
                            with gr.Row():
                                download_summary_btn = gr.DownloadButton(
                                    "πŸ“₯ Download Full Summary", 
                                    size="sm",
                                    variant="secondary"
                                )
                                clear_summary_btn = gr.Button(
                                    "πŸ—‘οΈ Clear", 
                                    size="sm"
                                )

            # Conversation Verification tab (chat-derived)
            with gr.TabItem("🧾 Conversation Verification", id="conversation_verification"):
                gr.Markdown("## 🧾 Conversation Verification (from Chat)")
                gr.Markdown(
                    "Click **Generate** to build a verification session from the current chat. "
                    "Review each exchange, mark it correct/incorrect, and download the session JSON."
                )

                conv_verify_state = gr.State(value=None)  # holds exported JSON path
                conv_verify_index = gr.State(value=0)
                conv_verify_records = gr.State(value=[])

                with gr.Row():
                    generate_conv_verification_btn = gr.Button("πŸ›  Generate from current chat", variant="primary")
                    conv_verify_download_btn = gr.DownloadButton("⬇️ Download reviewed JSON", variant="secondary")
                    conv_verify_download_csv_btn = gr.DownloadButton("πŸ“„ Download CSV", variant="secondary")

                conv_verify_status = gr.Markdown(value="", visible=True)
                conv_verify_exchange = gr.HTML(value="", label="Current Exchange")

                with gr.Row():
                    conv_correct_btn = gr.Button("βœ… Correct", variant="primary")
                    conv_incorrect_btn = gr.Button("❌ Incorrect")
                    conv_prev_btn = gr.Button("⬅️ Previous")
                    conv_next_btn = gr.Button("Next ➑️")

                # Shown only when marking Incorrect
                with gr.Row(visible=False) as conv_incorrect_comment_row:
                    with gr.Column(scale=3):
                        gr.Markdown("### Select Correct Classification:")
                        conv_correct_classification = gr.Radio(
                            choices=[
                                "🟒 Should be GREEN - No distress",
                                "🟑 Should be YELLOW - Needs clarification", 
                                "πŸ”΄ Should be RED - Spiritual distress"
                            ],
                            label="Correct Classification",
                            interactive=True
                        )
                        conv_incorrect_comment = gr.Textbox(
                            label="Comment (why incorrect / what to fix)",
                            placeholder="Add a short note for this exchange...",
                            lines=3,
                        )
                    with gr.Column(scale=1):
                        conv_save_comment_btn = gr.Button("πŸ’Ύ Save comment", variant="secondary")

                with gr.Row():
                    with gr.Column(scale=1):
                        conv_position = gr.Markdown(value="")
                    with gr.Column(scale=1):
                        conv_stats = gr.HTML(value="")

            # Enhanced Verification Modes tab (hidden sub-tabs; kept but moved after Conversation Verification)
            if is_feature_enabled("enhanced_verification_enabled"):
                with gr.TabItem("πŸ” Enhanced Verification", id="enhanced_verification"):
                    enhanced_verification_interface = create_enhanced_verification_tab()
            
            # Model Selection tab (second tab)
            with gr.TabItem("βš™οΈ Model Settings", id="model_settings"):
                gr.Markdown("## βš™οΈ AI Model Configuration")
                gr.Markdown("Select which AI models to use for different tasks. Changes apply to your current session.")
                
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("### πŸ” Spiritual Monitor (Classifier)")
                        spiritual_model = gr.Dropdown(
                            choices=[
                                "gemini-2.5-flash",
                                "gemini-2.0-flash",
                                "gemini-3-flash-preview",
                                "claude-sonnet-4-5-20250929",
                                "claude-sonnet-4-20250514",
                                "claude-3-7-sonnet-20250219"
                            ],
                            value="gemini-2.5-flash",
                            label="Spiritual Distress Analyzer",
                            interactive=True
                        )
                        
                        gr.Markdown("### 🟑 Soft Spiritual Triage")
                        soft_spiritual_triage_model = gr.Dropdown(
                            choices=[
                                "claude-sonnet-4-5-20250929",
                                "claude-sonnet-4-20250514",
                                "claude-3-7-sonnet-20250219",
                                "gemini-2.5-flash",
                                "gemini-2.0-flash",
                                "gemini-3-flash-preview"
                            ],
                            value="claude-sonnet-4-5-20250929",
                            label="Soft Spiritual Triage",
                            interactive=True
                        )
                    
                    with gr.Column():
                        gr.Markdown("### πŸ“Š Triage Response Evaluator")
                        triage_evaluate_model = gr.Dropdown(
                            choices=[
                                "gemini-2.5-flash",
                                "gemini-2.0-flash",
                                "gemini-3-flash-preview",
                                "claude-sonnet-4-5-20250929",
                                "claude-sonnet-4-20250514",
                                "claude-3-7-sonnet-20250219"
                            ],
                            value="gemini-2.5-flash",
                            label="Triage Response Evaluator",
                            interactive=True
                        )
                        
                        gr.Markdown("### πŸ₯ Medical Assistant")
                        medical_model = gr.Dropdown(
                            choices=[
                                "claude-sonnet-4-5-20250929",
                                "claude-sonnet-4-20250514",
                                "claude-3-7-sonnet-20250219",
                                "gemini-2.5-flash",
                                "gemini-2.0-flash",
                                "gemini-3-flash-preview"
                            ],
                            value="claude-sonnet-4-5-20250929",
                            label="Medical Assistant",
                            interactive=True
                        )
                    
                    with gr.Column():
                        gr.Markdown("### 🩺 Soft Medical Triage")
                        soft_triage_model = gr.Dropdown(
                            choices=[
                                "claude-sonnet-4-5-20250929",
                                "claude-sonnet-4-20250514",
                                "claude-3-7-sonnet-20250219",
                                "gemini-2.5-flash",
                                "gemini-2.0-flash",
                                "gemini-3-flash-preview"
                            ],
                            value="claude-sonnet-4-5-20250929",
                            label="Soft Medical Triage",
                            interactive=True
                        )
                        
                        gr.Markdown("### πŸ’¬ Medical Brain Summary Generator")
                        spiritual_care_message_model = gr.Dropdown(
                            choices=[
                                "claude-sonnet-4-5-20250929",
                                "claude-sonnet-4-20250514",
                                "claude-3-7-sonnet-20250219",
                                "gemini-2.5-flash",
                                "gemini-2.0-flash",
                                "gemini-3-flash-preview"
                            ],
                            value="claude-sonnet-4-5-20250929",
                            label="Medical Brain Summary Generator (uses Spiritual Care Message prompt)",
                            interactive=True
                        )
                
                with gr.Row():
                    apply_models_btn = gr.Button("βœ… Apply Model Settings", variant="primary", scale=2)
                    reset_models_btn = gr.Button("πŸ”„ Reset to Defaults", scale=1)
                
                model_status = gr.HTML(value="", visible=True)
            
            # Edit Prompts tab
            with gr.TabItem("πŸ”§ Edit Prompts", id="edit_prompts"):
                gr.Markdown("## πŸ”§ Customize AI Prompts")
                gr.Markdown("⚠️ **Note:** Changes apply only to your current session.")
                
                # Prompt selector
                with gr.Row():
                    prompt_selector = gr.Dropdown(
                        choices=[
                            "πŸ” Spiritual Monitor (Classifier)",
                            "🟑 Soft Spiritual Triage",
                            "πŸ“Š Triage Response Evaluator",
                            "πŸ₯ Medical Assistant",
                            "🩺 Soft Medical Triage",
                            "πŸ’¬ Spiritual Care Message"
                        ],
                        value="πŸ” Spiritual Monitor (Classifier)",
                        label="Select Prompt to Edit",
                        interactive=True
                    )
                
                with gr.Row():
                    with gr.Column(scale=3):
                        # Prompt editor
                        prompt_editor = gr.Code(
                            label="System Prompt",
                            value="",
                            language="markdown",
                            lines=25,
                            interactive=True
                        )
                        
                        with gr.Row():
                            load_prompt_btn = gr.Button("πŸ“₯ Load Prompt", scale=1)
                            apply_prompt_btn = gr.Button("βœ… Apply Changes", variant="primary", scale=2)
                            reset_prompt_btn = gr.Button("πŸ”„ Reset to Default", variant="secondary", scale=1)
                        
                        with gr.Row():
                            promote_prompt_btn = gr.Button("πŸ“€ Promote to File", variant="stop", scale=1)
                            validate_prompt_btn = gr.Button("πŸ” Validate", variant="secondary", scale=1)
                        
                        prompt_status = gr.HTML(
                            value="", 
                            visible=True,
                            elem_classes=["prompt-status-container"]
                        )
                    
                    with gr.Column(scale=1):
                        gr.Markdown("### πŸ“‹ Prompt Info")
                        prompt_info_display = gr.HTML(value="""
<div style="font-family: system-ui; padding: 1em; background-color: #f9fafb; border-radius: 8px;">
<p><strong>Select a prompt to edit</strong></p>

<p><strong>Available prompts:</strong></p>
<ul style="margin-left: 1em;">
<li>πŸ” Spiritual Monitor</li>
<li>🟑 Triage Questions</li>
<li>πŸ“Š Triage Evaluation</li>
<li>πŸ₯ Medical Assistant</li>
<li>🩺 Soft Triage</li>
<li>πŸ’¬ Spiritual Care Message (used for Medical Brain Summary)</li>
</ul>

<p><strong>Tips:</strong></p>
<ul style="margin-left: 1em;">
<li>Load prompt first</li>
<li>Edit carefully</li>
<li>Test changes</li>
<li>Reset if needed</li>
</ul>
</div>
                        """)
            
            # Patient Profiles tab
            with gr.TabItem("πŸ‘₯ Patient Profiles", id="profiles"):
                gr.Markdown("## πŸ‘₯ Patient Profile Management")
                gr.Markdown("Select a predefined profile or customize the current patient settings.")
                
                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Markdown("### πŸ“‹ Predefined Profiles")
                        profile_selector = gr.Dropdown(
                            choices=[
                                "πŸ‘€ Default Profile (Serhii)",
                                "🟒 GREEN - Healthy Coping",
                                "🟑 YELLOW - Mild Distress",
                                "🟑 YELLOW - Grief & Loss",
                                "🟑 YELLOW - Existential Questions",
                                "🟑 YELLOW - Spiritual Disconnection",
                                "πŸ”΄ RED - Crisis (Suicidal Risk)",
                                "πŸ”΄ RED - Severe Hopelessness",
                                "πŸ”΄ RED - Spiritual Crisis",
                                "πŸ«€ Cardiac Patient (Rehabilitation)",
                                "🩸 Diabetic Patient (Management)",
                                "πŸ₯ Post-Surgery (Recovery)",
                                "🧠 Mental Health (Anxiety/Depression)",
                                "πŸ‘΄ Elderly Patient (Chronic Care)",
                                "πŸƒ Athletic Patient (Injury/Training)"
                            ],
                            value="πŸ‘€ Default Profile (Serhii)",
                            label="Select Profile",
                            interactive=True
                        )
                        
                        load_profile_btn = gr.Button("πŸ“₯ Load Profile", variant="primary")
                        profile_status = gr.HTML(value="", visible=True)
                    
                    with gr.Column(scale=2):
                        gr.Markdown("### βš™οΈ Current Patient Settings")
                        
                        with gr.Row():
                            patient_name = gr.Textbox(
                                label="Patient Name",
                                value="Serhii",
                                interactive=True
                            )
                            patient_phone = gr.Textbox(
                                label="Phone Number",
                                value="",
                                placeholder="(555) 123-4567",
                                interactive=True
                            )
                            patient_age = gr.Number(
                                label="Age",
                                value=52,
                                interactive=True
                            )
                        
                        with gr.Row():
                            conditions = gr.Textbox(
                                label="Medical Conditions (comma-separated)",
                                value="Atrial fibrillation, Deep vein thrombosis, Obesity, Hypertension",
                                lines=3,
                                interactive=True
                            )
                        
                        with gr.Row():
                            primary_goal = gr.Textbox(
                                label="Primary Goal",
                                value="Weight reduction and cardiovascular fitness improvement",
                                lines=2,
                                interactive=True
                            )
                        
                        with gr.Row():
                            exercise_prefs = gr.Textbox(
                                label="Exercise Preferences (comma-separated)",
                                value="Swimming, Walking, Light cardio",
                                lines=2,
                                interactive=True
                            )
                        
                        with gr.Row():
                            exercise_limits = gr.Textbox(
                                label="Exercise Limitations (comma-separated)",
                                value="Anticoagulation therapy, Post-thrombotic recovery",
                                lines=2,
                                interactive=True
                            )
                        
                        with gr.Row():
                            save_profile_btn = gr.Button("πŸ’Ύ Save Current Profile", variant="primary", scale=1)
                            reset_profile_btn = gr.Button("πŸ”„ Reset to Default", scale=1)
                        
                        profile_save_status = gr.HTML(value="", visible=True)
            
            # Instructions tab
            with gr.TabItem("πŸ“– Help", id="help"):
                gr.Markdown(HELP_CONTENT)

        
        # Event handlers
        # Handlers moved to modular modules

        
        # Bind events
        demo.load(
            initialize_session,
            outputs=[session_data, session_info]
        )
        
        # Send message
        send_btn.click(
            chat_handlers.handle_message,
            inputs=[msg, chatbot, session_data],
            outputs=[chatbot, status_box, session_data, msg, conversation_stats, provider_summary_content, provider_summary_status, provider_summary_display, coherent_summary_display]
        )
        
        msg.submit(
            chat_handlers.handle_message,
            inputs=[msg, chatbot, session_data],
            outputs=[chatbot, status_box, session_data, msg, conversation_stats, provider_summary_content, provider_summary_status, provider_summary_display, coherent_summary_display]
        )
        
        # Clear chat
        clear_btn.click(
            chat_handlers.handle_clear,
            inputs=[session_data],
            outputs=[chatbot, status_box, session_data, provider_summary_content, provider_summary_status, provider_summary_display, coherent_summary_display]
        )
        
        # Refresh status
        refresh_btn.click(
            stats_handlers.get_status,
            inputs=[session_data],
            outputs=[status_box, conversation_stats, provider_summary_content, provider_summary_status, provider_summary_display, coherent_summary_display]
        )
        
        # Example buttons
        example_medical.click(
            lambda h, s: chat_handlers.send_example_with_stats("I am fine", h, s),
            inputs=[chatbot, session_data],
            outputs=[chatbot, status_box, session_data, msg, conversation_stats, provider_summary_content, provider_summary_status, provider_summary_display, coherent_summary_display]
        )
        
        example_wellness.click(
            lambda h, s: chat_handlers.send_example_with_stats("I'm feeling stressed and overwhelmed lately", h, s),
            inputs=[chatbot, session_data],
            outputs=[chatbot, status_box, session_data, msg, conversation_stats, provider_summary_content, provider_summary_status, provider_summary_display, coherent_summary_display]
        )
        
        example_help.click(
            lambda h, s: chat_handlers.send_example_with_stats("I am currently experiencing an emotional crisis", h, s),
            inputs=[chatbot, session_data],
            outputs=[chatbot, status_box, session_data, msg, conversation_stats, provider_summary_content, provider_summary_status, provider_summary_display, coherent_summary_display]
        )
        
        # Conversation logging buttons
        download_json_btn.click(
            stats_handlers.download_conversation_json,
            inputs=[session_data],
            outputs=[download_json_btn]
        )
        
        download_csv_btn.click(
            stats_handlers.download_conversation_csv,
            inputs=[session_data],
            outputs=[download_csv_btn]
        )
        
        # Provider Summary panel handlers
        download_summary_btn.click(
            stats_handlers.download_provider_summary,
            inputs=[session_data],
            outputs=[download_summary_btn]
        )
        
        clear_summary_btn.click(
            stats_handlers.clear_provider_summary,
            inputs=[],
            outputs=[provider_summary_content, provider_summary_status, provider_summary_display, coherent_summary_display]
        )
        
        # Coherent summary handlers (Medical Brain Summary - now first tab by default)
        regenerate_coherent_btn.click(
            stats_handlers.regenerate_coherent_summary,
            inputs=[session_data],
            outputs=[coherent_summary_display]
        )
        
        download_coherent_btn.click(
            stats_handlers.download_coherent_summary,
            inputs=[session_data],
            outputs=[download_coherent_btn]
        )

        # Conversation Verification events
        generate_conv_verification_btn.click(
            verification_handlers._generate_conv_verification,
            inputs=[session_data],
            outputs=[conv_verify_state, conv_verify_records, conv_verify_index, conv_verify_status, conv_verify_exchange, conv_position, conv_stats]
        )

        conv_verify_download_btn.click(
            verification_handlers._download_reviewed_json,
            inputs=[conv_verify_state, conv_verify_records],
            outputs=[conv_verify_download_btn]
        )

        conv_verify_download_csv_btn.click(
            verification_handlers._download_reviewed_csv,
            inputs=[conv_verify_state, conv_verify_records],
            outputs=[conv_verify_download_csv_btn]
        )

        conv_correct_btn.click(
            verification_handlers._mark_conv_correct,
            inputs=[conv_verify_records, conv_verify_index],
            outputs=[
                conv_verify_records,
                conv_verify_index,
                conv_verify_status,
                conv_verify_exchange,
                conv_position,
                conv_stats,
                conv_incorrect_comment_row,
                conv_incorrect_comment,
                conv_correct_classification,
            ]
        )

        conv_incorrect_btn.click(
            verification_handlers._show_incorrect_comment_ui,
            inputs=[conv_verify_records, conv_verify_index],
            outputs=[
                conv_verify_records,
                conv_verify_index,
                conv_verify_status,
                conv_verify_exchange,
                conv_position,
                conv_stats,
                conv_incorrect_comment_row,
                conv_incorrect_comment,
                conv_correct_classification,
            ]
        )

        conv_save_comment_btn.click(
            verification_handlers._save_incorrect_comment,
            inputs=[conv_verify_records, conv_verify_index, conv_incorrect_comment, conv_correct_classification],
            outputs=[
                conv_verify_records,
                conv_verify_index,
                conv_verify_status,
                conv_verify_exchange,
                conv_position,
                conv_stats,
                conv_incorrect_comment_row,
                conv_incorrect_comment,
                conv_correct_classification,
            ]
        )

        conv_prev_btn.click(
            lambda records, idx: verification_handlers._nav_conv(records, idx, -1),
            inputs=[conv_verify_records, conv_verify_index],
            outputs=[conv_verify_index, conv_verify_exchange, conv_position, conv_stats, conv_incorrect_comment_row, conv_incorrect_comment, conv_correct_classification]
        )

        conv_next_btn.click(
            lambda records, idx: verification_handlers._nav_conv(records, idx, 1),
            inputs=[conv_verify_records, conv_verify_index],
            outputs=[conv_verify_index, conv_verify_exchange, conv_position, conv_stats, conv_incorrect_comment_row, conv_incorrect_comment, conv_correct_classification]
        )

        
        # Prompt editing events
        load_prompt_btn.click(
            prompt_handlers.load_prompt,
            inputs=[prompt_selector, session_data],
            outputs=[prompt_editor, prompt_info_display, prompt_status]
        )
        
        apply_prompt_btn.click(
            prompt_handlers.apply_prompt_changes,
            inputs=[prompt_selector, prompt_editor, session_data],
            outputs=[prompt_status, session_data]
        )
        
        reset_prompt_btn.click(
            prompt_handlers.reset_prompt,
            inputs=[prompt_selector, session_data],
            outputs=[prompt_editor, prompt_info_display, prompt_status, session_data]
        )
        
        promote_prompt_btn.click(
            prompt_handlers.promote_prompt_to_file,
            inputs=[prompt_selector, session_data],
            outputs=[prompt_status, session_data]
        )
        
        validate_prompt_btn.click(
            prompt_handlers.validate_prompt_syntax,
            inputs=[prompt_editor],
            outputs=[prompt_status]
        )
        
        # Auto-load prompt when selector changes
        prompt_selector.change(
            prompt_handlers.load_prompt,
            inputs=[prompt_selector, session_data],
            outputs=[prompt_editor, prompt_info_display, prompt_status]
        )
        
        # Bind model selection events
        apply_models_btn.click(
            model_handlers.apply_model_settings,
            inputs=[spiritual_model, soft_spiritual_triage_model, triage_evaluate_model, medical_model, soft_triage_model, spiritual_care_message_model, session_data],
            outputs=[model_status, session_data]
        )
        
        reset_models_btn.click(
            model_handlers.reset_model_settings,
            inputs=[session_data],
            outputs=[model_status, session_data]
        )
        
        # Bind profile events
        load_profile_btn.click(
            profile_handlers.load_profile,
            inputs=[profile_selector, session_data],
            outputs=[patient_name, patient_phone, patient_age, conditions, primary_goal, exercise_prefs, exercise_limits, profile_status]
        )
        
        save_profile_btn.click(
            profile_handlers.save_profile,
            inputs=[patient_name, patient_phone, patient_age, conditions, primary_goal, exercise_prefs, exercise_limits, session_data],
            outputs=[profile_save_status]
        )
        
        reset_profile_btn.click(
            profile_handlers.reset_profile,
            inputs=[session_data],
            outputs=[patient_name, patient_phone, patient_age, conditions, primary_goal, exercise_prefs, exercise_limits, profile_save_status]
        )
    
    # Add CSS for prompt status container
    demo.css = """
    .prompt-status-container {
        max-height: 300px !important;
        overflow-y: auto !important;
        margin: 0.5em 0 !important;
    }
    .prompt-status-container > div {
        max-height: 280px !important;
        overflow-y: auto !important;
    }
    """
    
    return demo


def main():
    """Launch the simplified Gradio interface."""
    demo = create_simplified_interface()
    
    # Get configuration
    server_name = os.getenv("GRADIO_SERVER_NAME", "0.0.0.0")
    server_port = int(os.getenv("GRADIO_SERVER_PORT", "7860"))
    share = os.getenv("GRADIO_SHARE", "false").lower() == "true"
    
    print(f"πŸš€ Starting Simplified Medical Assistant...")
    print(f"πŸ“ Server: http://{server_name}:{server_port}")
    
    demo.launch(
        server_name=server_name,
        server_port=server_port,
        share=share
    )


if __name__ == "__main__":
    main()