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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6128dd
2071663
 
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
import os
import streamlit as st
import requests
import pandas as pd
from datetime import datetime
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass
import plotly.express as px
import plotly.graph_objects as go

# ─────────────────────────────────────────────────────────────────────────────
# Configuration & Data Classes
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class UserConfig:
    id: int
    name: str
    email: str
    age: int
    gender: str
    user_type: str
    created_at: str
    updated_at: str

@dataclass
class ChatMessage:
    role: str
    content: str
    timestamp: Optional[datetime] = None

class Config:
    API_URL = os.getenv("API_URL", "https://clinical-agents-333016757590.us-central1.run.app/api/v1")
    PAGE_TITLE = "AI Triage System"
    PAGE_ICON = "πŸ₯"
    
    # UI Constants
    SIDEBAR_WIDTH = 300
    CHAT_HEIGHT = 500
    
    # Colors
    PRIMARY_COLOR = "#1f77b4"
    SUCCESS_COLOR = "#2ca02c"
    WARNING_COLOR = "#ff7f0e"
    ERROR_COLOR = "#d62728"

# ─────────────────────────────────────────────────────────────────────────────
# Session State Manager
# ─────────────────────────────────────────────────────────────────────────────

class SessionStateManager:
    @staticmethod
    def init_state():
        """Initialize session state with default values"""
        defaults = {
            "user_type": "patient",
            "auth_done": False,
            "user_id": None,
            "user_data": None,
            "messages": [],
            "notes": [],
            "chat_active": False,
            "finished": False,
            "current_assessment_id": None,
            "show_help": False
        }
        
        for key, val in defaults.items():
            if key not in st.session_state:
                st.session_state[key] = val
    
    @staticmethod
    def get_user_config() -> Optional[UserConfig]:
        """Get current user configuration"""
        if st.session_state.auth_done and st.session_state.user_data:
            data = st.session_state.user_data
            return UserConfig(
                id=data["id"],
                name=data["name"],
                email=data["email"],
                age=data["age"],
                gender=data["gender"],
                user_type=data["user_type"],
                created_at=data["created_at"],
                updated_at=data["updated_at"]
            )
        return None
    
    @staticmethod
    def reset_chat():
        """Reset chat state"""
        st.session_state.messages = []
        st.session_state.chat_active = False
        st.session_state.finished = False
        st.session_state.current_assessment_id = None

# ─────────────────────────────────────────────────────────────────────────────
# API Service Layer
# ─────────────────────────────────────────────────────────────────────────────

class APIService:
    @staticmethod
    def login_user(name: str, email: str, age: int, gender: str, user_type: str) -> Tuple[bool, Dict]:
        """Login user with the new API structure"""
        try:
            payload = {
                "name": name,
                "email": email,
                "age": age,
                "gender": gender,
                "user_type": user_type
            }
            
            resp = requests.post(
                f"{Config.API_URL}/users/login",
                json=payload,
                timeout=10
            )
            resp.raise_for_status()
            return True, resp.json()
        except Exception as e:
            return False, {"error": str(e)}
    
    @staticmethod
    def get_user_by_id(user_id: int) -> Tuple[bool, Dict]:
        """Get user information by ID"""
        try:
            resp = requests.get(f"{Config.API_URL}/users/{user_id}", timeout=10)
            resp.raise_for_status()
            return True, resp.json()
        except Exception as e:
            return False, {"error": str(e)}
    
    @staticmethod
    def fetch_assessments() -> List[Dict]:
        """Fetch all assessments from API"""
        try:
            resp = requests.get(f"{Config.API_URL}/assessments", timeout=10)
            resp.raise_for_status()
            return resp.json()
        except Exception as e:
            st.error(f"Failed to fetch assessments: {str(e)}")
            return []
    
    @staticmethod
    def send_chat_message(message: str, history: List[Dict], patient_id: int) -> Tuple[bool, Dict]:
        """Send chat message to triage API"""
        try:
            payload = {
                "message": message,
                "history": history,
                "patient_id": patient_id
            }
            
            resp = requests.post(
                f"{Config.API_URL}/triage/chat",
                json=payload,
                timeout=30
            )
            resp.raise_for_status()
            return True, resp.json()
        except Exception as e:
            return False, {"error": str(e)}

# ─────────────────────────────────────────────────────────────────────────────
# UI Components
# ─────────────────────────────────────────────────────────────────────────────

class UIComponents:
    @staticmethod
    def render_header():
        """Render main header with branding"""
        st.markdown("""
        <div style="text-align: center; padding: 1rem 0; background: linear-gradient(90deg, #1f77b4, #2ca02c); 
                    border-radius: 10px; margin-bottom: 2rem;">
            <h1 style="color: white; margin: 0; font-size: 2.5rem;">πŸ₯ AI Triage System</h1>
            <p style="color: #f0f0f0; margin: 0.5rem 0 0 0; font-size: 1.1rem;">
                Intelligent healthcare assessment at your fingertips
            </p>
        </div>
        """, unsafe_allow_html=True)
    
    @staticmethod
    def render_sidebar_auth() -> bool:
        """Render sidebar authentication section"""
        with st.sidebar:
            st.markdown("### πŸ‘€ Authentication")
            
            # User type selection
            user_type = st.selectbox(
                "Select your role:",
                ["patient", "staff"],
                key="user_type_select",
                help="Choose whether you're a patient seeking assessment or medical staff"
            )
            st.session_state.user_type = user_type
            
            # Sign in form
            with st.form("signin_form"):
                st.markdown("**Sign In / Register**")
                name = st.text_input("Full Name", placeholder="Enter your full name")
                email = st.text_input("Email", placeholder="Enter your email address")
                
                # Additional fields for patients
                if user_type == "patient":
                    col1, col2 = st.columns(2)
                    with col1:
                        age = st.number_input("Age", min_value=1, max_value=120, value=25)
                    with col2:
                        gender = st.selectbox("Gender", ["male", "female", "other"])
                else:
                    age = 30  # Default for staff
                    gender = "not_specified"
                
                submitted = st.form_submit_button("πŸ” Sign In", use_container_width=True)
                
                if submitted:
                    if name.strip() and email.strip():
                        with st.spinner("πŸ”„ Signing in..."):
                            success, response = APIService.login_user(
                                name.strip(), 
                                email.strip(), 
                                age, 
                                gender, 
                                user_type
                            )
                            
                            if success:
                                st.session_state.user_data = response
                                st.session_state.user_id = response["id"]
                                st.session_state.auth_done = True
                                st.success("βœ… Successfully signed in!")
                                st.rerun()
                            else:
                                st.error(f"❌ Login failed: {response.get('error', 'Unknown error')}")
                    else:
                        st.error("❌ Please enter both name and email")
            
            # Show current user info
            if st.session_state.auth_done and st.session_state.user_data:
                st.markdown("---")
                st.markdown("**Current User:**")
                user_data = st.session_state.user_data
                st.info(f"""
                πŸ‘€ **{user_data['name']}**
                πŸ“§ {user_data['email']}
                🏷️ {user_data['user_type'].title()}
                πŸ†” ID: {user_data['id']}
                """)
                
                if st.button("πŸšͺ Sign Out", use_container_width=True):
                    for key in list(st.session_state.keys()):
                        del st.session_state[key]
                    st.rerun()
        
        return st.session_state.auth_done
    
    @staticmethod
    def render_chat_interface(user_config: UserConfig):
        """Render patient chat interface"""
        st.markdown("### πŸ’¬ Chat Assessment")
        
        # Chat container
        chat_container = st.container(height=Config.CHAT_HEIGHT)
        
        with chat_container:
            # Display chat history
            for i, msg in enumerate(st.session_state.messages):
                with st.chat_message(msg["role"]):
                    st.markdown(msg["content"])
        
        # Chat controls
        col1, col2, col3 = st.columns([2, 1, 1])
        
        with col1:
            if not st.session_state.chat_active:
                if st.button("πŸš€ Start New Assessment", use_container_width=True, type="primary"):
                    UIComponents._start_new_assessment(user_config)
        
        with col2:
            if st.session_state.chat_active and st.button("πŸ”„ Reset Chat", use_container_width=True):
                SessionStateManager.reset_chat()
                st.rerun()
        
        with col3:
            if st.button("❓ Help", use_container_width=True):
                st.session_state.show_help = not st.session_state.get("show_help", False)
        
        # Help section
        if st.session_state.get("show_help", False):
            st.markdown("""
            ---
            **ℹ️ How to use the AI Triage System:**
            
            1. **Start Assessment**: Click 'Start New Assessment' to begin
            2. **Describe Symptoms**: Be detailed about your symptoms, when they started, and their severity
            3. **Answer Questions**: The AI will ask follow-up questions to better understand your condition
            4. **Get Results**: Receive your triage level and recommended next steps
            
            **Tips for better results:**
            - Be honest and specific about your symptoms
            - Include timeline information (when symptoms started)
            - Mention any relevant medical history
            - Don't hesitate to ask for clarification
            """)
        
        # Chat input
        if st.session_state.chat_active and not st.session_state.finished:
            if user_input := st.chat_input("πŸ’­ Describe your symptoms or ask a question..."):
                UIComponents._handle_user_message(user_input, user_config)
    
    @staticmethod
    def _start_new_assessment(user_config: UserConfig):
        """Start a new triage assessment"""
        st.session_state.chat_active = True
        st.session_state.messages = []
        st.session_state.finished = False
        
        with st.spinner("πŸ”„ Starting your assessment..."):
            success, response = APIService.send_chat_message("", [], user_config.id)
            
            if success:
                st.session_state.messages.append({
                    "role": "assistant",
                    "content": response["response"]
                })
                st.rerun()
            else:
                st.error(f"❌ Failed to start assessment: {response.get('error', 'Unknown error')}")
                st.session_state.chat_active = False
    
    @staticmethod
    def _handle_user_message(user_input: str, user_config: UserConfig):
        """Handle user message in chat"""
        # Add user message
        st.session_state.messages.append({"role": "user", "content": user_input})
        
        with st.spinner("πŸ€” AI is analyzing your response..."):
            # Convert messages to API format
            history = [{"role": msg["role"], "content": msg["content"]} 
                      for msg in st.session_state.messages]
            
            success, response = APIService.send_chat_message(user_input, history, user_config.id)
            
            if success:
                st.session_state.messages.append({
                    "role": "assistant",
                    "content": response["response"]
                })
                
                if response.get("finished", False):
                    st.session_state.chat_active = False
                    st.session_state.finished = True
                    st.success("βœ… Assessment completed successfully!")
                    st.balloons()
                
                st.rerun()
            else:
                st.error(f"❌ Error: {response.get('error', 'Unknown error')}")

class StaffDashboard:
    @staticmethod
    def render_dashboard(user_config: UserConfig):
        """Render staff dashboard"""
        st.markdown("### πŸ“Š Staff Dashboard")
        
        # Fetch data
        with st.spinner("πŸ“₯ Loading assessment data..."):
            assessments = APIService.fetch_assessments()
        
        if not assessments:
            st.info("πŸ“­ No assessments available yet.")
            return
        
        df = pd.DataFrame(assessments)
        df["created_at"] = pd.to_datetime(df["created_at"])
        
        # Dashboard metrics
        StaffDashboard._render_metrics(df)
        
        # Charts
        col1, col2 = st.columns(2)
        with col1:
            StaffDashboard._render_esi_distribution(df)
        with col2:
            StaffDashboard._render_timeline_chart(df)
        
        # Data table
        StaffDashboard._render_assessments_table(df)
    
    @staticmethod
    def _render_metrics(df: pd.DataFrame):
        """Render key metrics"""
        col1, col2, col3, col4 = st.columns(4)
        
        with col1:
            st.metric(
                "πŸ“‹ Total Assessments",
                len(df),
                delta=None
            )
        
        with col2:
            avg_esi = df['esi_level'].mean()
            st.metric(
                "⚑ Avg ESI Level",
                f"{avg_esi:.1f}",
                delta=None
            )
        
        with col3:
            emergency_cases = len(df[df['esi_level'] <= 2])
            st.metric(
                "🚨 Emergency Cases",
                emergency_cases,
                delta=f"{(emergency_cases/len(df)*100):.1f}% of total"
            )
        
        with col4:
            latest = df['created_at'].max()
            hours_ago = (datetime.now() - latest.replace(tzinfo=None)).total_seconds() / 3600
            st.metric(
                "πŸ• Last Assessment",
                f"{hours_ago:.1f}h ago",
                delta=None
            )
    
    @staticmethod
    def _render_esi_distribution(df: pd.DataFrame):
        """Render ESI level distribution chart"""
        st.markdown("**🎯 ESI Level Distribution**")
        
        esi_counts = df['esi_level'].value_counts().sort_index()
        
        colors = ['#d62728', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a']
        
        fig = px.bar(
            x=esi_counts.index,
            y=esi_counts.values,
            color=esi_counts.index,
            color_continuous_scale='RdYlGn_r',
            title="Distribution by ESI Level"
        )
        
        fig.update_layout(
            xaxis_title="ESI Level",
            yaxis_title="Count",
            showlegend=False,
            height=300
        )
        
        st.plotly_chart(fig, use_container_width=True)
    
    @staticmethod
    def _render_timeline_chart(df: pd.DataFrame):
        """Render assessments timeline"""
        st.markdown("**πŸ“ˆ Assessment Timeline**")
        
        # Group by date
        df_daily = df.groupby(df['created_at'].dt.date).size().reset_index()
        df_daily.columns = ['date', 'count']
        
        fig = px.line(
            df_daily,
            x='date',
            y='count',
            title="Daily Assessment Volume",
            markers=True
        )
        
        fig.update_layout(
            xaxis_title="Date",
            yaxis_title="Number of Assessments",
            height=300
        )
        
        st.plotly_chart(fig, use_container_width=True)
    
    @staticmethod
    def _render_assessments_table(df: pd.DataFrame):
        """Render assessments data table"""
        st.markdown("**πŸ“‹ Recent Assessments**")
        
        # Prepare display dataframe
        display_df = df.copy()
        display_df['created_at'] = pd.to_datetime(display_df['created_at']).dt.strftime("%Y-%m-%d %H:%M:%S")
        
        # Add user information by fetching user details
        if not display_df.empty:
            # Create a dictionary to store user info to avoid multiple API calls
            user_info_cache = {}
            user_names = []
            user_emails = []
            
            for user_id in display_df['user_id']:
                if user_id not in user_info_cache:
                    success, user_data = APIService.get_user_by_id(user_id)
                    if success:
                        user_info_cache[user_id] = user_data
                    else:
                        user_info_cache[user_id] = {"name": "Unknown", "email": "Unknown"}
                
                user_info = user_info_cache[user_id]
                user_names.append(user_info.get("name", "Unknown"))
                user_emails.append(user_info.get("email", "Unknown"))
            
            display_df['patient_name'] = user_names
            display_df['patient_email'] = user_emails
        
        # Select columns to display
        columns = ["id", "patient_name", "patient_email", "esi_level", "diagnosis", "notes", "created_at"]
        
        # Sort by creation time (newest first)
        display_df = display_df.sort_values('created_at', ascending=False)
        
        st.dataframe(
            display_df[columns],
            use_container_width=True,
            hide_index=True,
            column_config={
                "id": "Assessment ID",
                "patient_name": "Patient Name",
                "patient_email": "Patient Email",
                "esi_level": st.column_config.NumberColumn(
                    "ESI Level",
                    help="Emergency Severity Index (1=Most urgent, 5=Least urgent)",
                    min_value=1,
                    max_value=5,
                    format="%d"
                ),
                "diagnosis": "Diagnosis",
                "notes": "Notes",
                "created_at": "Created At"
            }
        )

# ─────────────────────────────────────────────────────────────────────────────
# Main Application
# ─────────────────────────────────────────────────────────────────────────────

def main():
    """Main application entry point"""
    # Page configuration
    st.set_page_config(
        page_title=Config.PAGE_TITLE,
        layout="wide",
        page_icon=Config.PAGE_ICON,
        initial_sidebar_state="expanded"
    )
    
    # Initialize session state
    SessionStateManager.init_state()
    
    # Custom CSS
    st.markdown("""
    <style>
    .main > div {
        padding-top: 2rem;
    }
    .stChatMessage {
        padding: 1rem;
        border-radius: 10px;
        margin-bottom: 1rem;
    }
    .stButton > button {
        border-radius: 20px;
        border: none;
        font-weight: 600;
    }
    .metric-container {
        background: #f8f9fa;
        padding: 1rem;
        border-radius: 10px;
        margin-bottom: 1rem;
    }
    </style>
    """, unsafe_allow_html=True)
    
    # Render header
    UIComponents.render_header()
    
    # Handle authentication
    if not UIComponents.render_sidebar_auth():
        st.markdown("""
        <div style="text-align: center; padding: 3rem; color: #666;">
            <h3>πŸ‘‹ Welcome to AI Triage System</h3>
            <p>Please sign in using the sidebar to get started with your health assessment.</p>
        </div>
        """, unsafe_allow_html=True)
        st.stop()
    
    # Get user configuration
    user_config = SessionStateManager.get_user_config()
    
    # Route to appropriate interface
    if user_config.user_type == "patient":
        UIComponents.render_chat_interface(user_config)
    else:
        StaffDashboard.render_dashboard(user_config)

if __name__ == "__main__":
    main()