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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fe9e1e
18bfaa1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
"""
medical_chatbot_app.py

Multi-agent medical assistant with:
- ReAct-style LLM router
- FAISS-based diagnosis engine (in diagnosis_engine)
- Symptom severity scoring
- Disease description + precautions
- Logging & usage metrics
- Gradio UI

Requires:
    pip install pandas numpy faiss-cpu scikit-learn gradio openai python-dotenv
"""

import os
import re
import json
import time
import logging
import hashlib
import html
from logging.handlers import RotatingFileHandler
from pathlib import Path
from typing import Any, Dict, List, Optional

import gradio as gr
import pandas as pd
from dotenv import load_dotenv
from openai import OpenAI

from diagnosis_engine import DiseaseDiagnosisAgent
from diagnosis_engine.vocabulary import map_to_known_symptoms, normalize_symptom

# ---------------------------------------------------------------------
# Environment
# ---------------------------------------------------------------------

# Load environment variables from likely .env locations relative to this file
BASE_DIR = Path(__file__).resolve().parent
ENV_CANDIDATES = [
    BASE_DIR / ".env",
    BASE_DIR.parent / ".env",
    Path.cwd() / ".env",
]
for env_path in ENV_CANDIDATES:
    if env_path.exists():
        load_dotenv(env_path, override=False)

# Ensure OPENAI_API_KEY is set in the environment
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not OPENAI_API_KEY:
    searched = ", ".join(str(path) for path in ENV_CANDIDATES)
    raise RuntimeError(
        "OPENAI_API_KEY environment variable is not set. "
        f"Add it to your environment or a .env file in one of these locations: {searched}"
    )

# Initialize OpenAI client
client = OpenAI(api_key=OPENAI_API_KEY)

# ---------------------------------------------------------------------
# Logging setup
# ---------------------------------------------------------------------

os.makedirs("logs", exist_ok=True)
# Set up a rotating file handler to keep logs manageable, and also log to console
handler = RotatingFileHandler("logs/app.log", maxBytes=2_000_000, backupCount=5)
logging.basicConfig(
    level=logging.INFO,
    format="%(message)s",
    handlers=[handler, logging.StreamHandler()],
)
logger = logging.getLogger("medical_chatbot")


SAFE_ERROR_MESSAGE = (
    "I couldn't complete your request. Please rephrase your symptoms, "
    "ask for severity, or name a condition for description/precautions."
)

# ---------------------------------------------------------------------
# Metrics store
# ---------------------------------------------------------------------

# Track the number of calls to each agent and other relevant metrics for monitoring and analysis
METRICS = {
    "diagnosis_calls": 0,
    "severity_calls": 0,
    "clarification_calls": 0,
    "description_calls": 0,
    "precaution_calls": 0,
}

# ---------------------------------------------------------------------
# ReAct prompt
# ---------------------------------------------------------------------

PLANNER_PROMPT = """
You are a medical triage planning assistant. Create a short execution plan using one or more of the available agents.

Available agents:
- clarification_agent -> {"user_symptoms": ["symptom_1", "symptom_2"]}
- disease_diagnosis -> {"user_symptoms": ["symptom_1", "symptom_2"]}
- symptom_severity -> {"user_symptoms": ["symptom_1", "symptom_2"]}
- disease_description -> {"disease": "disease_name"}
- precaution_advisor -> {"disease": "disease_name"}

Return JSON only with this exact schema:
{
  "thought": "short planning rationale",
  "steps": [
    {
      "agent": "clarification_agent | disease_diagnosis | symptom_severity | disease_description | precaution_advisor",
      "reason": "why this step helps",
      "input": {}
    }
  ]
}

Rules:
- Include 1 to 3 steps.
- Use clarification_agent when symptoms are vague, too few, contradictory, or likely to need follow-up questions before diagnosis.
- Use symptom_severity when the user asks about urgency or symptoms sound clinically important.
- Use disease_diagnosis when the user provides symptoms and wants likely causes.
- Use disease_description and/or precaution_advisor when the user asks about a specific disease.
- For symptom-based questions, symptom lists must be arrays of strings.
- For disease-focused questions, disease must be a string.
- Never wrap the JSON in markdown fences.
"""

# ---------------------------------------------------------------------
# Data loading
# ---------------------------------------------------------------------

DATA_DIR = BASE_DIR / "data"

# Paths to CSV dataset files
SYMPTOM_DISEASE_FILE = DATA_DIR / "dataset.csv"
SEVERITY_FILE = DATA_DIR / "Symptom-severity.csv"
DESCRIPTION_FILE = DATA_DIR / "symptom_Description.csv"
PRECAUTION_FILE = DATA_DIR / "symptom_precaution.csv"

# Verify that all required data files are present before starting the app
for path in [SYMPTOM_DISEASE_FILE, SEVERITY_FILE, DESCRIPTION_FILE, PRECAUTION_FILE]:
    if not path.exists():
        raise FileNotFoundError(f"Missing required data file: {path}")

# Set a threshold to identify urgent cases based on severity scores
SEVERITY_URGENT_THRESHOLD = 15
# Some symptoms should prompt an emergency message regardless of the overall score
EMERGENCY_SYMPTOMS = {
    "chest_pain",
    "breathlessness",
    "shortness_of_breath",
}
# A standard message to show when urgent symptoms are detected
EMERGENCY_MESSAGE = (
    "Urgent symptoms detected that could be a medical emergency. "
    "Please seek immediate medical care now or call emergency services right away, especially "
    "if symptoms are severe, worsening, or accompanied by sweating, fainting, confusion, or pain "
    "spreading to the arm, back, jaw, or neck."
)
# Keywords that may indicate travel-related exposure, which can be relevant for certain diagnoses
TRAVEL_INDICATORS = [
    "travel",
    "traveled",
    "abroad",
    "trip",
    "vacation",
    "south africa",
    "mosquito",
    "exposure",
]

# Load the datasets
def load_datasets() -> Dict[str, pd.DataFrame]:
    df_sd = pd.read_csv(SYMPTOM_DISEASE_FILE)
    df_desc = pd.read_csv(DESCRIPTION_FILE)
    df_prec = pd.read_csv(PRECAUTION_FILE)
    df_sev = pd.read_csv(SEVERITY_FILE)
    
    # Do preprocessing
    df_sd["Disease"] = df_sd["Disease"].str.strip().str.lower()
    df_desc["Disease"] = df_desc["Disease"].str.strip().str.lower()
    df_prec["Disease"] = df_prec["Disease"].str.strip().str.lower()
    df_sev["Symptom"] = df_sev["Symptom"].str.strip().str.lower()
    
    # Return as a dictionary of DataFrames
    return {
        "symptom_disease": df_sd,
        "description": df_desc,
        "precaution": df_prec,
        "severity": df_sev,
    }

# Get a list of symptom columns (use on the symptom-disease dataset)
def extract_symptom_columns(df: pd.DataFrame) -> List[str]:
    return [c for c in df.columns if c.lower() != "disease"]

# Normalize text by stripping whitespace and converting to lowercase, for consistent matching and logging
def normalize(text: str) -> str:
    return re.sub(r"\s+", " ", text.strip().lower())

# Calculate a severity score by summing the weights of the user's symptoms based on the severity dataset
def severity_score(symptoms: List[str], df_sev: pd.DataFrame) -> int:
    sev_map = dict(zip(df_sev["Symptom"], df_sev["weight"].astype(int)))
    return sum(sev_map.get(s, 0) for s in symptoms)

# Redact text by hashing it and recording its length, to allow for logging without storing sensitive information
def redact_text(value: str) -> Dict[str, Any]:
    normalized = (value or "").strip()
    return {
        "text_sha256": hashlib.sha256(normalized.encode("utf-8")).hexdigest()[:16],
        "length": len(normalized),
    }

# Extract a JSON object from text
def extract_json_object(text: str) -> Optional[Dict[str, Any]]:
    if not text:
        return None

    # Normalize the text
    stripped = text.strip()
    if stripped.startswith("```"):
        stripped = re.sub(r"^```(?:json)?\s*", "", stripped)
        stripped = re.sub(r"\s*```$", "", stripped)

    # First try to parse the entire text as JSON
    try:
        parsed = json.loads(stripped)
        return parsed if isinstance(parsed, dict) else None
    except Exception:
        pass

    # Identify the starting and ending braces of the JSON text
    start = stripped.find("{")
    end = stripped.rfind("}")
    if start == -1 or end == -1 or end <= start:
        return None

    # Try to parse the substring that looks like JSON
    try:
        parsed = json.loads(stripped[start : end + 1])
        return parsed if isinstance(parsed, dict) else None
    except Exception:
        return None

# Extract structured context from user input
def extract_structured_context(text: str, all_symptoms: List[str]) -> Dict[str, Any]:
    lower = normalize(text)
    context: Dict[str, Any] = {
        "reported_symptoms": [],
        "duration": None,
        "progression": None,
        "exposures": [],
    }

    # Get potential symptoms from the text by splitting on common delimiters and conjunctions
    symptom_candidates = [
        segment.strip()
        for segment in re.split(r"[,\n]| and | but ", lower)
        if segment.strip()
    ]
    mapped = map_to_known_symptoms(symptom_candidates, all_symptoms)

    # Also scan short n-grams from the whole sentence so symptoms embedded
    # in natural phrasing like "I have fever and cough for 3 days" are captured.
    tokens = re.findall(r"[a-z0-9]+", lower)
    ngrams = []
    for size in (1, 2, 3):
        for idx in range(len(tokens) - size + 1):
            ngrams.append(" ".join(tokens[idx : idx + size]))

    # Get symptom matches using the ngrams
    phrase_matches = map_to_known_symptoms(ngrams, all_symptoms)
    # Combine and deduplicate symptoms from both matching lists
    if phrase_matches:
        mapped = list(dict.fromkeys(mapped + phrase_matches))

    if mapped:
        context["reported_symptoms"] = mapped

    # Extract duration info using regex patterns - this will be used to give extra context to the diagnosis agent
    duration_patterns = [
        r"\bfor (\d+\s+(?:hour|hours|day|days|week|weeks|month|months))\b",
        r"\bsince (yesterday|today|last night|this morning|\d+\s+(?:day|days|week|weeks|month|months)\s+ago)\b",
        r"\bstarted (today|yesterday|last night|\d+\s+(?:hour|hours|day|days|week|weeks)\s+ago)\b",
    ]
    # Check each pattern to see if it matches any duration information in the user's input
    for pattern in duration_patterns:
        match = re.search(pattern, lower)
        if match:
            context["duration"] = match.group(1)
            break

    # Extract symptom progression info - can help the diagnosis agent adjust symptom scores
    progression_map = {
        "worse": "worsening",
        "worsening": "worsening",
        "getting worse": "worsening",
        "better": "improving",
        "improving": "improving",
        "same": "stable",
        "unchanged": "stable",
        "staying the same": "stable",
    }
    for phrase, label in progression_map.items():
        if phrase in lower:
            context["progression"] = label
            break

    # Extract exposure info based on keywords - helps the diagnosis agent consider rare diseases 
    # related to travel or specific exposures
    exposure_keywords = {
        "travel": ["travel", "traveled", "abroad", "trip", "vacation"],
        "mosquito exposure": ["mosquito", "bug bites", "insect bites"],
        "sick contacts": ["sick contact", "someone sick", "around sick people", "coworker was sick"],
        "food exposure": ["new food", "undercooked", "restaurant", "takeout"],
        "medication exposure": ["new medication", "started a medication", "antibiotic", "medicine"],
    }
    exposures = []
    for label, keywords in exposure_keywords.items():
        if any(keyword in lower for keyword in keywords):
            exposures.append(label)
    context["exposures"] = exposures

    return context

# Merge structured context from multiple turns, give precedence to new info, but preserving all reported symptoms and exposure info
def merge_structured_context(existing: Optional[Dict[str, Any]], new: Optional[Dict[str, Any]]) -> Dict[str, Any]:
    existing = existing or {}
    new = new or {}

    merged = {
        "reported_symptoms": [],
        "duration": new.get("duration") or existing.get("duration"),
        "progression": new.get("progression") or existing.get("progression"),
        "exposures": [],
    }

    # Combine and deduplicate symptoms
    seen_symptoms = set()
    for symptom in existing.get("reported_symptoms", []) + new.get("reported_symptoms", []):
        if symptom not in seen_symptoms:
            merged["reported_symptoms"].append(symptom)
            seen_symptoms.add(symptom)

    # Combine and deduplicate exposures
    seen_exposures = set()
    for exposure in existing.get("exposures", []) + new.get("exposures", []):
        if exposure not in seen_exposures:
            merged["exposures"].append(exposure)
            seen_exposures.add(exposure)

    return merged

# Format the structured context into a human-readable string to include in the LLM prompt
def format_structured_context_for_prompt(structured_context: Optional[Dict[str, Any]]) -> str:
    context = structured_context or {}
    lines = []

    symptoms = context.get("reported_symptoms", [])
    if symptoms:
        lines.append("Known symptoms from prior turns: " + ", ".join(symptoms))
    if context.get("duration"):
        lines.append(f"Symptom duration: {context['duration']}")
    if context.get("progression"):
        lines.append(f"Symptom progression: {context['progression']}")
    if context.get("exposures"):
        lines.append("Relevant exposures: " + ", ".join(context["exposures"]))

    return "\n".join(lines)

# ---------------------------------------------------------------------
# Agents
# ---------------------------------------------------------------------

# Symptom severity agent
class SymptomSeverityAgent:
    name = "symptom_severity"

    def __init__(self, df_sev: pd.DataFrame):
        self.df = df_sev

    def handle(self, user_symptoms: List[str], **kwargs) -> Dict[str, Any]:
        # Increment the severity_calls metric each time this agent is invoked
        METRICS["severity_calls"] += 1
        # Calculate the severity score based on the user's symptoms and the severity dataset
        score = severity_score(user_symptoms, self.df)
        # Check for any red-flag symptoms that would indicate an urgent situation regardless of the overall score
        matched_red_flags = sorted(set(user_symptoms).intersection(EMERGENCY_SYMPTOMS))
        # Determine urgency based on the severity score and presence of red-flag symptoms
        urgency = "urgent" if matched_red_flags or score >= SEVERITY_URGENT_THRESHOLD else "non-urgent"
        return {
            "severity_score": score,
            "urgency": urgency,
            "matched_red_flags": matched_red_flags,
        }

# Clarification agent that asks follow-up questions when needed to improve diagnosis accuracy
class ClarificationAgent:
    name = "clarification_agent"

    # The clarification agent uses the diagnosis agent
    def __init__(
        self,
        diagnosis_agent: DiseaseDiagnosisAgent,
        symptom_df: pd.DataFrame,
        symptom_cols: List[str],
    ):
        self.diagnosis_agent = diagnosis_agent
        self.df = symptom_df
        self.symptom_cols = symptom_cols

    # Get the list of symptoms associated with a candidate disease from the dataset
    def _candidate_symptoms(self, disease: str) -> List[str]:
        row = self.df[self.df["Disease"] == normalize(disease)]
        if row.empty:
            return []
        first = row.iloc[0]
        return [
            str(first[col]).strip()
            for col in self.symptom_cols
            if pd.notna(first[col]) and str(first[col]).strip()
        ]

    # Generate follow-up questions based on the top candidate diseases and their associated symptoms
    def _follow_up_questions(
        self,
        user_symptoms: List[str],
        candidates: List[Dict[str, Any]],
    ) -> List[str]:
        symptom_set = set(user_symptoms)
        symptom_counts: Dict[str, int] = {}
        for candidate in candidates[:3]:
            for symptom in self._candidate_symptoms(candidate["disease"]):
                if symptom not in symptom_set:
                    symptom_counts[symptom] = symptom_counts.get(symptom, 0) + 1

        ranked = sorted(
            symptom_counts.items(),
            key=lambda item: (item[1], len(item[0]), item[0]),
            reverse=True,
        )

        questions = [
            f"Are you also experiencing {symptom.replace('_', ' ')}?"
            for symptom, _ in ranked[:4]
        ]
        questions.extend(
            [
                "How long have these symptoms been present?",
                "Have your symptoms been getting worse, staying the same, or improving?",
                "Any recent travel, sick contacts, or new food or medication exposure?",
            ]
        )

        deduped = []
        seen = set()
        for question in questions:
            if question not in seen:
                deduped.append(question)
                seen.add(question)
        return deduped[:5]

    # Rerank candidate diseases using the LLM when the initial scores are close or there is uncertainty
    def handle(self, user_symptoms: List[str], **kwargs) -> Dict[str, Any]:
        METRICS["clarification_calls"] += 1

        # Extract structured context from the user's input to provide additional information to the diagnosis agent
        structured_context = kwargs.get("structured_context") or {}
        # Merge with any existing structured context to preserve information across turns
        result = self.diagnosis_agent.handle(user_symptoms, travel_exposure=kwargs.get("travel_exposure", False))
        candidates = result.get("diagnoses", [])

        # Set the reason for whether or not clarification is needed
        reason = "enough_signal"
        needs_clarification = False
        # We need at least 2 symptoms
        if len(user_symptoms) < 2:
            needs_clarification = True
            reason = "too_few_symptoms"
        # Check if we have any strong symptom matches
        elif not candidates:
            needs_clarification = True
            reason = "no_strong_matches"
        else:
            # Get the score difference btw the top 2 candidates
            top_score = candidates[0]["hybrid_score"]
            second_score = candidates[1]["hybrid_score"] if len(candidates) > 1 else 0.0
            score_gap = top_score - second_score
            # If the top score is low or the score gap is small, request clarification
            if top_score < 0.25:
                needs_clarification = True
                reason = "weak_match"
            elif score_gap < 0.08:
                needs_clarification = True
                reason = "top_candidates_too_close"

        # Give the LLM extra context (symptom duration, progression, exposures) to help determine if clarification is needed)
        context_bonus = sum(
            1
            for value in [
                structured_context.get("duration"),
                structured_context.get("progression"),
                bool(structured_context.get("exposures")),
            ]
            if value
        )
        if needs_clarification and context_bonus >= 2 and len(user_symptoms) >= 2 and candidates:
            if candidates[0]["hybrid_score"] >= 0.22:
                needs_clarification = False
                reason = "context_resolved"

        return {
            "needs_clarification": needs_clarification,
            "reason": reason,
            "questions": self._follow_up_questions(user_symptoms, candidates),
            "candidate_preview": [
                {
                    "disease": item["disease"],
                    "hybrid_score": item["hybrid_score"],
                }
                for item in candidates[:3]
            ],
        }

# Disease description agent
class DiseaseDescriptionAgent:
    name = "disease_description"

    def __init__(self, df_desc: pd.DataFrame):
        self.df = df_desc

    def handle(self, disease: str) -> Dict[str, Any]:
        # Increment the description_calls metric each time this agent is invoked
        METRICS["description_calls"] += 1
        # Look up the disease in the description dataset and return its description, or a default message if not found
        row = self.df[self.df["Disease"] == normalize(disease)]
        if row.empty:
            return {"description": "No description found."}
        return {"description": row["Description"].iloc[0]}

# Precaution advisor agent
class PrecautionAdvisorAgent:
    name = "precaution_advisor"

    def __init__(self, df_prec: pd.DataFrame):
        self.df = df_prec

    def handle(self, disease: str) -> Dict[str, Any]:
        # Increment the precaution_calls metric each time this agent is invoked
        METRICS["precaution_calls"] += 1
        # Look up the disease in the precaution dataset and return a list of precautions, or an empty list if not found
        row = self.df[self.df["Disease"] == normalize(disease)]
        if row.empty:
            return {"precautions": []}

        # Extract all columns that start with "precaution" and have non-empty values, and return them as a list
        first = row.iloc[0]
        precautions = [
            str(first[c]).strip()
            for c in first.index
            if c.lower().startswith("precaution")
            and pd.notna(first[c])
            and str(first[c]).strip()
        ]
        return {"precautions": precautions}

# ---------------------------------------------------------------------
# ReAct Router
# ---------------------------------------------------------------------

# The ReActRouter class takes the user's input and conversation history, constructs a prompt for the LLM, 
# and parses the LLM's response to determine which agent to call and with what payload. It also includes logic to handle 
# symptom normalization and mapping, as well as special handling for travel-related symptoms in the diagnosis agent.
class ReActRouter:
    def __init__(self, agents: Dict[str, Any], all_symptoms: List[str]):
        self.agents = agents
        self.all_symptoms = all_symptoms

    # Build the messages for the LLM by taking the recent conversation history and appending the user's current input, 
    # while ensuring that only relevant roles and content are included.
    def _build_messages(
        self,
        user_input: str,
        history: List[Dict[str, str]],
        structured_context: Optional[Dict[str, Any]] = None,
    ) -> List[Dict[str, str]]:
        recent_history = history[-6:] if history else []
        messages = [{"role": "system", "content": PLANNER_PROMPT}]
        context_note = format_structured_context_for_prompt(structured_context)
        if context_note:
            messages.append(
                {
                    "role": "system",
                    "content": "Structured context from earlier turns:\n" + context_note,
                }
            )
        for item in recent_history:
            role = item.get("role")
            content = item.get("content", "")
            if role in {"user", "assistant"} and content:
                messages.append({"role": role, "content": content})
        messages.append({"role": "user", "content": user_input})
        return messages

    # Call the LLM to get a plan
    def llm_plan(
        self,
        user_input: str,
        history: List[Dict[str, str]],
        structured_context: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        
        # Log the input to the router
        resp = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=self._build_messages(user_input, history, structured_context),
            temperature=0,
        )
        text = resp.choices[0].message.content or ""

        # Log the raw output from the LLM, with redactions
        logger.info(json.dumps({
            "event": "router_llm_output",
            "output_hash": redact_text(text),
        }))

        parsed = extract_json_object(text)
        if not parsed:
            logger.error(f"Router could not parse structured JSON. Raw output:\n{text}")
            return self._fallback_plan(user_input, structured_context)

        steps = parsed.get("steps", [])
        if not isinstance(steps, list) or not steps:
            logger.error("Planner steps were missing or invalid.")
            return self._fallback_plan(user_input, structured_context)

        # Normalize and validate the steps to ensure they conform to the expected schema, and log any issues
        normalized_steps = []
        for step in steps[:3]:
            if not isinstance(step, dict):
                continue
            agent_name = str(step.get("agent", "")).strip()
            payload = step.get("input", {})
            reason = str(step.get("reason", "")).strip()
            if not agent_name or not isinstance(payload, dict):
                continue
            normalized_steps.append(
                {"agent": agent_name, "payload": payload, "reason": reason}
            )

        if not normalized_steps:
            logger.error("Planner returned no valid steps.")
            return self._fallback_plan(user_input, structured_context)

        logger.info(json.dumps({
            "event": "planner_parsed",
            "step_count": len(normalized_steps),
            "agents": [step["agent"] for step in normalized_steps],
        }))
        return {"steps": normalized_steps}

    # If the LLM fails to produce a valid plan, use heuristic rules to create a fallback plan based on symptom keywords and disease mentions
    def _fallback_plan(
        self,
        user_input: str,
        structured_context: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        lower = user_input.lower()
        # Split the input into parts, normalize them
        normalized_tokens = [normalize_symptom(part) for part in re.split(r"[,\n]| and ", lower) if part.strip()]
        mapped = map_to_known_symptoms(normalized_tokens, self.all_symptoms)
        structured_context = structured_context or {}
        # If no symptoms were mapped, check the context for previous symptoms from earlier turns
        if not mapped and structured_context.get("reported_symptoms"):
            mapped = structured_context["reported_symptoms"]
        # Look for disease mentions in the input to trigger description or precaution agents
        disease_match = re.search(r"(?:what is|describe|tell me about|precautions for)\s+([a-zA-Z\s\-]+)", lower)
        steps: List[Dict[str, Any]] = []

        # Check if the user is asking about symptoms urgency or severity
        if any(term in lower for term in ["how urgent", "severity", "serious", "emergency"]):
            # If we have mapped symptoms, call the symptom severity agent to evaluate
            if mapped:
                return {"steps": [{"agent": "symptom_severity", "payload": {"user_symptoms": mapped}, "reason": "Assess clinical urgency."}]}
            return {"error": SAFE_ERROR_MESSAGE}

        # If we have mapped symptoms, add steps for clarification, severity, and diagnosis agents to the plan
        if mapped:
            steps.append(
                {"agent": "clarification_agent", "payload": {"user_symptoms": mapped}, "reason": "Check whether follow-up questions are needed before diagnosis."}
            )
            steps.append(
                {"agent": "symptom_severity", "payload": {"user_symptoms": mapped}, "reason": "Assess urgency for the same symptom set."}
            )
            steps.append(
                {"agent": "disease_diagnosis", "payload": {"user_symptoms": mapped}, "reason": "Find likely conditions from symptoms if the evidence is specific enough."}
            )
            return {"steps": steps[:3]}

        if disease_match:
            # Normalize the disease match info
            disease = normalize(disease_match.group(1))

            # If the user asked about precautions, call the precaution advisor agent
            if "precaution" in lower:
                steps.append(
                    {"agent": "precaution_advisor", "payload": {"disease": disease}, "reason": "Provide basic safety guidance."}
                )
            else:
                # Add steps to call the disease description and precaution agents
                steps.append(
                    {"agent": "disease_description", "payload": {"disease": disease}, "reason": "Explain the named condition."}
                )
                steps.append(
                    {"agent": "precaution_advisor", "payload": {"disease": disease}, "reason": "Provide basic safety guidance."}
                )
            return {"steps": steps}

        return {"error": SAFE_ERROR_MESSAGE}

    # The  main method for generating a plan to produce a response to user input
    def plan(
        self,
        user_input: str,
        history: List[Dict[str, str]],
        structured_context: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        parsed = self.llm_plan(user_input, history, structured_context)
        if "error" in parsed:
            return parsed

        structured_context = structured_context or {}
        # Set a flag to indicate if the user has mentioned travel or exposure that could make certain diseases more likely
        travel_exposure_flag = (
            any(token in user_input.lower() for token in TRAVEL_INDICATORS)
            or any("travel" in exposure or "mosquito" in exposure for exposure in structured_context.get("exposures", []))
        )
        executable_steps = []
        # Iterate through the steps
        for step in parsed["steps"]:
            agent_name = step["agent"]
            payload = dict(step["payload"])
            if agent_name not in self.agents:
                logger.error(f"Unknown agent in plan: {agent_name}")
                continue

            # Extract any symptoms in the payload and map to known symptoms
            if "user_symptoms" in payload:
                raw_symptoms = payload["user_symptoms"]
                if not isinstance(raw_symptoms, list):
                    continue

                normalized = [normalize_symptom(s) for s in raw_symptoms]
                mapped = map_to_known_symptoms(normalized, self.all_symptoms)
                logger.info(json.dumps({
                    "event": "planner_mapped_symptoms",
                    "agent": agent_name,
                    "mapped_count": len(mapped),
                }))

                if not mapped:
                    continue
                payload["user_symptoms"] = mapped

            # Pass in payload data to help with diagnosis and clarification
            if agent_name == "disease_diagnosis":
                payload["travel_exposure"] = travel_exposure_flag
            if agent_name == "clarification_agent":
                payload["structured_context"] = structured_context

            executable_steps.append(
                {"agent": agent_name, "payload": payload, "reason": step.get("reason", "")}
            )

        # If no steps were added, return an appropriate message to the user
        if not executable_steps:
            if travel_exposure_flag:
                return {
                    "diagnoses": [],
                    "message": "It looks like you mentioned travel or exposure but did not describe symptoms. Please specify symptoms such as fever, rash, or cough.",
                }
            return {
                "diagnoses": [],
                "message": "No recognizable symptoms were detected. Please describe your symptoms in more detail, such as fever, headache, or cough.",
            }

        return {"steps": executable_steps}


# ---------------------------------------------------------------------
# App
# ---------------------------------------------------------------------

# The MedicalChatbotApp class initializes the agents, loads the datasets, and sets up the Gradio interface. 
class MedicalChatbotApp:
    def __init__(self):
        self.client = OpenAI(api_key=OPENAI_API_KEY)
        self.data = load_datasets()
        self.symptom_cols = extract_symptom_columns(self.data["symptom_disease"])

        # Define the diagnosis agent
        diagnosis_agent = DiseaseDiagnosisAgent(
            df=self.data["symptom_disease"], # Symptom-disease dataset
            client=self.client,
            llm_model="gpt-4o-mini", # Use a smaller model to reduce latency
            top_k_faiss=10, # Pulling top 10 is reasonable given the total disease count of 41 in the dataset
        )

        self.all_symptoms = diagnosis_agent.all_symptoms
        # Create a disease description lookup dict using the description dataset (makes later lookups faster)
        self.disease_description_lookup = {
            row["Disease"]: row["Description"]
            for _, row in self.data["description"].drop_duplicates(subset=["Disease"]).iterrows()
        }
        # Create a disease precaution lookup dict using the precaution dataset (makes later lookups faster)
        self.disease_precaution_lookup = {}
        for _, row in self.data["precaution"].drop_duplicates(subset=["Disease"]).iterrows():
            disease = row["Disease"]
            precautions = [
                str(row[col]).strip()
                for col in row.index
                if col.lower().startswith("precaution")
                and pd.notna(row[col])
                and str(row[col]).strip()
            ]
            self.disease_precaution_lookup[disease] = precautions
        # Create a disease symptom lookup dict using the symptom-disease dataset (makes later lookups faster)
        self.disease_symptom_lookup = {}
        for _, row in self.data["symptom_disease"].iterrows():
            disease = row["Disease"]
            self.disease_symptom_lookup[disease] = [
                str(row[col]).strip()
                for col in self.symptom_cols
                if pd.notna(row[col]) and str(row[col]).strip()
            ]
        # Initialize the agents and the router
        self.agents = {
            "clarification_agent": ClarificationAgent(
                diagnosis_agent=diagnosis_agent,
                symptom_df=self.data["symptom_disease"],
                symptom_cols=self.symptom_cols,
            ),
            "disease_diagnosis": diagnosis_agent,
            "symptom_severity": SymptomSeverityAgent(self.data["severity"]),
            "disease_description": DiseaseDescriptionAgent(self.data["description"]),
            "precaution_advisor": PrecautionAdvisorAgent(self.data["precaution"]),
        }
        self.router = ReActRouter(self.agents, self.all_symptoms)

    # Build a log payload
    def _build_log_payload(self, user_input: str, routed: Dict[str, Any], latency: int) -> Dict[str, Any]:
        return {
            "timestamp": time.time(),
            "user_input": redact_text(user_input),
            "response_shape": sorted(routed.keys()),
            "routed_agent": routed.get("agent"),
            "planned_agents": [step["agent"] for step in routed.get("steps", [])] if isinstance(routed.get("steps"), list) else None,
            "metrics": {
                "diagnosis_calls": METRICS["diagnosis_calls"],
                "severity_calls": METRICS["severity_calls"],
                "clarification_calls": METRICS["clarification_calls"],
                "description_calls": METRICS["description_calls"],
                "precaution_calls": METRICS["precaution_calls"],
            },
            "latency_ms": latency,
        }

    # Format the severity assessment answer based on the severity score, urgency level, and any matched 
    # red-flag symptoms
    def _format_severity_answer(
        self,
        score: Optional[int],
        urgency: Optional[str],
        matched_red_flags: Optional[List[str]] = None,
    ) -> str:
        severity_level = urgency.upper() if isinstance(urgency, str) else urgency
        recommendation = "recommended" if urgency == "urgent" else "not required urgently"
        red_flag_note = ""
        # If red flags were found, generate a note listing the red-flag symptoms
        if matched_red_flags:
            pretty_flags = ", ".join(symptom.replace("_", " ") for symptom in matched_red_flags)
            red_flag_note = f"\nRed-flag symptoms detected: {pretty_flags}."
        return (
            "Clinical urgency assessment:\n"
            f"- Severity score: {score} (threshold: {SEVERITY_URGENT_THRESHOLD})\n"
            f"- Triage level: {severity_level}\n"
            "Based on your symptoms, this indicates that immediate medical attention is "
            f"{recommendation}.{red_flag_note}\n"
            "Please consult a healthcare provider for evaluation and next steps."
        )

    # Format the diagnosis answer
    def _format_diagnosis_answer(
        self,
        diagnosis_input: List[str],
        result: Dict[str, Any],
        severity_result: Optional[Dict[str, Any]] = None,
    ) -> str:
        if not result.get("diagnoses"):
            return result.get("message", "No recognizable symptoms were detected.")

        # Get the top hybrid score from the diagnoses
        top_score = result["diagnoses"][0]["hybrid_score"]
        # Set a minimum score threshold to filter the diagnoses (0.10), 
        # but ensure that at least one diagnosis is included even if the scores are low
        min_score = max(0.10, 0.5 * top_score)
        filtered_diagnoses = [item for item in result["diagnoses"] if item["hybrid_score"] >= min_score]
        if not filtered_diagnoses:
            filtered_diagnoses = [result["diagnoses"][0]]

        # Get the result from the symptom severity agent
        severity_result = severity_result or self.agents["symptom_severity"].handle(diagnosis_input)
        text = (
            "## Clinical Summary\n"
            f"- Symptom set: {', '.join(s.replace('_', ' ') for s in diagnosis_input)}\n"
            f"- Severity score: {severity_result['severity_score']} (threshold: {SEVERITY_URGENT_THRESHOLD})\n"
            f"- Triage level: {severity_result['urgency'].upper()}\n\n"
        )

        # If the top score is below a certain threshold, include a note that the matches are weak and 
        # that additional symptoms could help narrow down the possibilities. This helps set expectations 
        # for the user about the confidence of the diagnosis and encourages them to provide more information if possible.
        if top_score < 0.25:
            text += "We found possible matches based on your symptoms, but none are strong matches.\n\n"

        text += "## Top Matching Conditions\n\n"

        # For each filtered diagnosis, look up its description and precautions, and also determine which 
        # symptoms matched between the user's input and the symptoms associated with that disease in the dataset. 
        for rank, item in enumerate(filtered_diagnoses, start=1):
            disease = item["disease"]
            description = self.disease_description_lookup.get(disease, "No description found.")
            precautions_list = self.disease_precaution_lookup.get(disease, [])
            precautions = ", ".join(precautions_list) if precautions_list else "No specific precautions listed."

            # Look up the symptoms associated with this disease in the symptom-disease dataset, 
            # and determine which of those symptoms match the user's input.
            disease_symptoms = self.disease_symptom_lookup.get(disease, [])
            if disease_symptoms:
                matched = set(diagnosis_input).intersection(set(disease_symptoms))
                matched_text = ", ".join(s.replace("_", " ") for s in sorted(matched)) if matched else "No direct matches"
            else:
                matched_text = "No symptom data available"

            text += f"### {rank}. {disease.title()}\n"
            text += f"- Match strength: {item['hybrid_score']:.2f}\n"
            text += f"- Matched symptoms: {matched_text}\n"
            text += f"- Description: {description}\n"
            text += f"- Precautions: {precautions}\n\n"

        # Give the user a message based on the urgency of the symptoms
        if severity_result["urgency"] == "urgent":
            text += "Given the urgent severity, please seek immediate medical attention.\n\n"
        else:
            text += "Please consult a healthcare professional for accurate diagnosis and appropriate treatment.\n\n"

        # Give a special message if the user mentioned travel or exposure
        if result.get("tropical_diseases_present", False):
            text += (
                "**Important Note**: One or more listed conditions are typically linked to international travel. "
                "If you have not traveled recently, those options are much less likely.\n\n"
            )

        # If the confidence of the matches is low, prompt for more symptoms
        if top_score < 0.25:
            text += (
                "Additional symptoms (i.e. body ache, sore throat, nausea, or shortness of breath) "
                "could help narrow down the possibilities."
            )

        return text.strip()

    # Format the clarification questions into a readable format for the user
    def _render_session_summary(
        self,
        symptom_context: List[str],
        last_diagnoses: List[Dict[str, Any]],
        structured_context: Optional[Dict[str, Any]] = None,
    ) -> str:
        structured_context = structured_context or {}
        # If there are no symptoms or diagnoses or structured context yet, show a blank, default summary
        if not symptom_context and not last_diagnoses and not format_structured_context_for_prompt(structured_context):
            return (
                "## Session Summary\n"
                "- Symptoms tracked: none yet\n"
                "- Latest matches: none yet\n"
                "- Structured context: none yet"
            )

        # Format symptoms, diagnoses, and context for presentation to the user
        symptom_text = ", ".join(s.replace("_", " ") for s in symptom_context) if symptom_context else "none yet"
        diagnosis_text = ", ".join(item["disease"].title() for item in last_diagnoses[:3]) if last_diagnoses else "none yet"
        context_parts = []
        if structured_context.get("duration"):
            context_parts.append(f"duration {structured_context['duration']}")
        if structured_context.get("progression"):
            context_parts.append(f"progression {structured_context['progression']}")
        if structured_context.get("exposures"):
            context_parts.append("exposures " + ", ".join(structured_context["exposures"]))
        context_text = "; ".join(context_parts) if context_parts else "none yet"
        return (
            "## Session Summary\n"
            f"- Symptoms tracked: {symptom_text}\n"
            f"- Latest matches: {diagnosis_text}\n"
            f"- Structured context: {context_text}"
        )

    # Render a clinical summary card - this gives a comprehensive overview of the session for the user
    def _render_result_card(
        self,
        symptom_context: List[str],
        last_diagnoses: List[Dict[str, Any]],
        severity_result: Optional[Dict[str, Any]],
        plan_trace: List[Dict[str, str]],
        clarification_result: Optional[Dict[str, Any]],
        structured_context: Optional[Dict[str, Any]],
    ) -> str:
        structured_context = structured_context or {}
        # Format symptoms for display in the card
        symptoms_html = "".join(
            f"<span class='chip'>{html.escape(symptom.replace('_', ' '))}</span>"
            for symptom in symptom_context[:8]
        ) or "<span class='muted'>No symptoms tracked yet.</span>"
        # Format severity for disply in the card
        severity_html = "<span class='muted'>No severity assessment yet.</span>"
        if severity_result:
            badge_class = "badge urgent" if severity_result.get("urgency") == "urgent" else "badge nonurgent"
            severity_html = (
                f"<div class='{badge_class}'>{html.escape(severity_result.get('urgency', 'unknown').upper())}</div>"
                f"<p>Severity score: <strong>{severity_result.get('severity_score', 'n/a')}</strong></p>"
            )

        # Format diseases diagnoses for display in the card
        diagnosis_items = ""
        for item in last_diagnoses[:3]:
            diagnosis_items += (
                "<div class='result-item'>"
                f"<div class='result-title'>{html.escape(item['disease'].title())}</div>"
                f"<div class='result-meta'>Match strength: {item['hybrid_score']:.2f}</div>"
                "</div>"
            )
        if not diagnosis_items:
            diagnosis_items = "<div class='muted'>No diagnosis results yet.</div>"
        
        # Format the structured context for display in the card
        structured_context_html = []
        if structured_context.get("duration"):
            structured_context_html.append(f"<div class='result-meta'>Duration: {html.escape(structured_context['duration'])}</div>")
        if structured_context.get("progression"):
            structured_context_html.append(f"<div class='result-meta'>Progression: {html.escape(structured_context['progression'])}</div>")
        if structured_context.get("exposures"):
            structured_context_html.append(
                f"<div class='result-meta'>Exposures: {html.escape(', '.join(structured_context['exposures']))}</div>"
            )
        context_html = "".join(structured_context_html) or "<div class='muted'>No structured context captured yet.</div>"

        # Format clarification/additional questions for disply in the card
        clarification_html = "<div class='muted'>No follow-up questions pending.</div>"
        if clarification_result and clarification_result.get("needs_clarification"):
            question_items = "".join(
                f"<li>{html.escape(question)}</li>"
                for question in clarification_result.get("questions", [])
            )
            clarification_html = (
                f"<div class='result-meta'>Reason: {html.escape(clarification_result.get('reason', 'needs more detail'))}</div>"
                f"<ul class='plan-list'>{question_items}</ul>"
            )

        # Format the planner trace for display in the card
        plan_items = "".join(
            "<li>"
            f"<strong>{html.escape(step['agent'])}</strong>: {html.escape(step.get('reason', ''))}"
            "</li>"
            for step in plan_trace
        ) or "<li>No planner steps yet.</li>"

        return (
            "<div class='clinical-card'>"
            "<div class='card-section'>"
            "<div class='card-title'>Tracked Symptoms</div>"
            f"<div class='chip-row'>{symptoms_html}</div>"
            "</div>"
            "<div class='card-section'>"
            "<div class='card-title'>Urgency</div>"
            f"{severity_html}"
            "</div>"
            "<div class='card-section'>"
            "<div class='card-title'>Top Matches</div>"
            f"{diagnosis_items}"
            "</div>"
            "<div class='card-section'>"
            "<div class='card-title'>Structured Context</div>"
            f"{context_html}"
            "</div>"
            "<div class='card-section'>"
            "<div class='card-title'>Follow-Up Questions</div>"
            f"{clarification_html}"
            "</div>"
            "<div class='card-section'>"
            "<div class='card-title'>Planner Trace</div>"
            f"<ol class='plan-list'>{plan_items}</ol>"
            "</div>"
            "</div>"
        )

    # Format the emergency answer
    def _format_emergency_answer(self, matched_red_flags: List[str]) -> str:
        pretty_flags = ", ".join(symptom.replace("_", " ") for symptom in matched_red_flags)
        return (
            f"{EMERGENCY_MESSAGE}\n\n"
            f"Detected red-flag symptoms: {pretty_flags}.\n"
            "This app should not be used to rule out serious causes of these symptoms."
        )

    # Format the clarification answer
    def _format_clarification_answer(self, clarification_result: Dict[str, Any]) -> str:
        reason_map = {
            "too_few_symptoms": "I need a bit more detail before ranking possible conditions.",
            "no_strong_matches": "Your current symptom list does not map strongly to the dataset yet.",
            "weak_match": "The current matches are too weak to present confidently.",
            "top_candidates_too_close": "Several conditions are currently too close to separate confidently.",
        }
        intro = reason_map.get(
            clarification_result.get("reason"),
            "I need a bit more detail before I can narrow this down reliably.",
        )
        questions = clarification_result.get("questions", [])
        lines = "\n".join(f"- {question}" for question in questions[:5])
        return (
            "## Follow-Up Questions\n"
            f"{intro}\n\n"
            "Please answer a few of these:\n"
            f"{lines}\n\n"
            "Once you answer, I can refine the urgency assessment and possible matches."
        )

    # Execute the plan
    def _execute_plan(
        self,
        planned: Dict[str, Any],
        symptom_context: List[str],
        structured_context: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        structured_context = structured_context or {}
        if "error" in planned:
            return {"error": planned["error"], "symptom_context": symptom_context, "structured_context": structured_context, "plan_trace": [], "last_diagnoses": [], "severity_result": None}
        if "diagnoses" in planned and "message" in planned:
            return {
                "answer": planned["message"],
                "symptom_context": symptom_context,
                "structured_context": structured_context,
                "plan_trace": [],
                "last_diagnoses": [],
                "severity_result": None,
            }

        diagnosis_result = None
        severity_result = None
        clarification_result = None
        disease_details: Dict[str, Dict[str, Any]] = {}
        plan_trace: List[Dict[str, str]] = []

        # Iterate through the planned steps
        for step in planned.get("steps", []):
            agent_name = step["agent"]
            payload = dict(step["payload"])
            plan_trace.append({"agent": agent_name, "reason": step.get("reason", "")})

            if (
                agent_name == "disease_diagnosis"
                and clarification_result
                and clarification_result.get("needs_clarification")
            ):
                continue

            if agent_name in {"clarification_agent", "disease_diagnosis", "symptom_severity"}:
                step_symptoms = payload.get("user_symptoms", [])
                if step_symptoms:
                    symptom_context = sorted(set(symptom_context).union(step_symptoms))
                    payload["user_symptoms"] = symptom_context
            if agent_name == "disease_diagnosis":
                payload["structured_context"] = structured_context

            result = self.agents[agent_name].handle(**payload)

            if agent_name == "clarification_agent":
                clarification_result = result
            elif agent_name == "disease_diagnosis":
                diagnosis_result = result
            elif agent_name == "symptom_severity":
                severity_result = result
            else:
                disease_key = normalize(payload.get("disease", ""))
                disease_details.setdefault(disease_key, {}).update(result)

            if (
                agent_name == "symptom_severity"
                and severity_result
                and severity_result.get("matched_red_flags")
            ):
                break

        if severity_result and severity_result.get("matched_red_flags"):
            return {
                "answer": self._format_emergency_answer(severity_result["matched_red_flags"]),
                "symptom_context": symptom_context,
                "structured_context": structured_context,
                "plan_trace": plan_trace,
                "last_diagnoses": [],
                "severity_result": severity_result,
                "clarification_result": clarification_result,
            }

        if clarification_result and clarification_result.get("needs_clarification"):
            return {
                "answer": self._format_clarification_answer(clarification_result),
                "symptom_context": symptom_context,
                "structured_context": structured_context,
                "plan_trace": plan_trace,
                "last_diagnoses": [],
                "severity_result": severity_result,
                "clarification_result": clarification_result,
            }

        if diagnosis_result:
            answer = self._format_diagnosis_answer(symptom_context, diagnosis_result, severity_result)
            return {
                "answer": answer,
                "symptom_context": symptom_context,
                "structured_context": structured_context,
                "plan_trace": plan_trace,
                "last_diagnoses": diagnosis_result.get("diagnoses", []),
                "severity_result": severity_result,
                "clarification_result": clarification_result,
            }

        if severity_result:
            answer = self._format_severity_answer(
                severity_result.get("severity_score"),
                severity_result.get("urgency"),
                severity_result.get("matched_red_flags"),
            )
            return {
                "answer": answer,
                "symptom_context": symptom_context,
                "structured_context": structured_context,
                "plan_trace": plan_trace,
                "last_diagnoses": [],
                "severity_result": severity_result,
                "clarification_result": clarification_result,
            }

        if disease_details:
            disease_name = next(iter(disease_details))
            detail = disease_details[disease_name]
            description = detail.get("description", "No description found.")
            precautions = detail.get("precautions", [])
            precaution_text = ", ".join(precautions) if precautions else "No specific precautions listed."
            answer = (
                f"## Condition Overview\n"
                f"- Disease: {disease_name.title()}\n"
                f"- Description: {description}\n"
                f"- Precautions: {precaution_text}\n\n"
                "Please consult a healthcare professional for diagnosis and treatment."
            )
            return {
                "answer": answer,
                "symptom_context": symptom_context,
                "structured_context": structured_context,
                "plan_trace": plan_trace,
                "last_diagnoses": [],
                "severity_result": None,
                "clarification_result": clarification_result,
            }

        return {
            "error": SAFE_ERROR_MESSAGE,
            "symptom_context": symptom_context,
            "structured_context": structured_context,
            "plan_trace": plan_trace,
            "last_diagnoses": [],
            "severity_result": severity_result,
            "clarification_result": clarification_result,
        }

    # The main chat method
    def chat(self, user_input: str, session_state: Optional[Dict[str, Any]] = None):
        try:
            session_state = session_state or {}
            history = session_state.get("messages", [])
            symptom_context = session_state.get("symptom_context", [])
            last_diagnoses = session_state.get("last_diagnoses", [])
            last_severity = session_state.get("last_severity")
            last_plan_trace = session_state.get("last_plan_trace", [])
            last_clarification = session_state.get("last_clarification")
            structured_context = session_state.get("structured_context", {})

            turn_context = extract_structured_context(user_input, self.all_symptoms)
            structured_context = merge_structured_context(structured_context, turn_context)
            if turn_context.get("reported_symptoms"):
                symptom_context = sorted(set(symptom_context).union(turn_context["reported_symptoms"]))

            # Record the start time
            start = time.time()
            planned = self.router.plan(user_input, history, structured_context)
            latency = int((time.time() - start) * 1000)

            logger.info(json.dumps(self._build_log_payload(user_input, planned, latency)))

            executed = self._execute_plan(planned, symptom_context, structured_context)
            answer = executed.get("answer") or executed.get("error", SAFE_ERROR_MESSAGE)
            symptom_context = executed.get("symptom_context", symptom_context)
            structured_context = executed.get("structured_context", structured_context)
            last_diagnoses = executed.get("last_diagnoses", last_diagnoses)
            last_severity = executed.get("severity_result", last_severity)
            last_plan_trace = executed.get("plan_trace", last_plan_trace)
            last_clarification = executed.get("clarification_result", last_clarification)

            history = history + [
                {"role": "user", "content": user_input},
                {"role": "assistant", "content": answer},
            ]
            updated_state = {
                "messages": history,
                "symptom_context": symptom_context,
                "last_diagnoses": last_diagnoses,
                "last_severity": last_severity,
                "last_plan_trace": last_plan_trace,
                "last_clarification": last_clarification,
                "structured_context": structured_context,
            }
            summary = self._render_session_summary(symptom_context, last_diagnoses, structured_context)
            # Get the HTML formatted result card to give a comprehensive overview of the session for the user
            card_html = self._render_result_card(
                symptom_context,
                last_diagnoses,
                last_severity,
                last_plan_trace,
                last_clarification,
                structured_context,
            )
            return history, updated_state, summary, card_html

        # Catch any unexpected exceptions, log the error, and return an error message to the user
        except Exception as exc:
            logger.error(f"Error in chat: {exc}")
            error_msg = (
                "I hit an internal error while processing that request. "
                "Please try again with a short symptom list like `fever, cough, fatigue`."
            )
            session_state = session_state or {}
            history = session_state.get("messages", [])
            history = history + [
                {"role": "user", "content": user_input},
                {"role": "assistant", "content": error_msg},
            ]
            updated_state = {
                "messages": history,
                "symptom_context": session_state.get("symptom_context", []),
                "last_diagnoses": session_state.get("last_diagnoses", []),
                "last_severity": session_state.get("last_severity"),
                "last_plan_trace": session_state.get("last_plan_trace", []),
                "last_clarification": session_state.get("last_clarification"),
                "structured_context": session_state.get("structured_context", {}),
            }
            summary = self._render_session_summary(
                updated_state["symptom_context"],
                updated_state["last_diagnoses"],
                updated_state.get("structured_context", {}),
            )
            card_html = self._render_result_card(
                updated_state["symptom_context"],
                updated_state["last_diagnoses"],
                updated_state.get("last_severity"),
                updated_state.get("last_plan_trace", []),
                updated_state.get("last_clarification"),
                updated_state.get("structured_context", {}),
            )
            return history, updated_state, summary, card_html

    # Launch the Gradio interface
    def launch(self):
        custom_css = """
            .app-shell {max-width: 1280px; margin: 0 auto;}
            .hero {padding: 18px 20px; border-radius: 18px; background: linear-gradient(135deg, #f6f1df, #dceef5); border: 1px solid #d9d1b5;}
            .clinical-card {background: #fffdf7; border: 1px solid #d8d1bf; border-radius: 18px; padding: 18px; box-shadow: 0 10px 30px rgba(60, 52, 33, 0.08);}
            .card-section {margin-bottom: 16px;}
            .card-title {font-size: 0.85rem; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: #7a6440; margin-bottom: 8px;}
            .chip-row {display: flex; flex-wrap: wrap; gap: 8px;}
            .chip {display: inline-block; background: #efe6cf; color: #4f4027; padding: 6px 10px; border-radius: 999px; font-size: 0.92rem;}
            .badge {display: inline-block; padding: 7px 12px; border-radius: 999px; font-weight: 700; margin-bottom: 10px;}
            .badge.urgent {background: #f6d2c9; color: #8a2410;}
            .badge.nonurgent {background: #dcefdc; color: #1f6134;}
            .result-item {padding: 10px 0; border-top: 1px solid #ece4d1;}
            .result-item:first-child {border-top: 0;}
            .result-title {font-weight: 700; color: #2d2418;}
            .result-meta, .muted {color: #6d6559;}
            .plan-list {margin: 0; padding-left: 18px;}
            """

        with gr.Blocks(title="MediBot - Disease & Symptom Assistant") as demo:
            gr.Markdown(
                """
                <div class="app-shell">
                  <div class="hero">
                    <h1>MediBot - Disease & Symptom Assistant</h1>
                    <p>Describe symptoms in plain language, ask about urgency, or request condition details. Results are educational and should be confirmed by a healthcare professional.</p>
                  </div>
                </div>
                """
            )
            with gr.Row():
                with gr.Column(scale=7):
                    chatbot = gr.Chatbot(height=520)
                    user_box = gr.Textbox(
                        label="Tell me your symptoms",
                        placeholder="e.g., fever, headache, chills, fatigue",
                        scale=8,
                    )
                with gr.Column(scale=5):
                    summary = gr.Markdown(self._render_session_summary([], [], {}))
                    result_card = gr.HTML(self._render_result_card([], [], None, [], None, {}))
            state = gr.State(
                {
                    "messages": [],
                    "symptom_context": [],
                    "last_diagnoses": [],
                    "last_severity": None,
                    "last_plan_trace": [],
                    "last_clarification": None,
                    "structured_context": {},
                }
            )

            # Handle user input from the chat
            def respond(msg, st):
                hist, next_state, summary_text, card_html = self.chat(msg, st)
                return "", hist, next_state, summary_text, card_html

            # Start a new chat and clear out all session tracking objects
            def new_chat():
                empty_state = {
                    "messages": [],
                    "symptom_context": [],
                    "last_diagnoses": [],
                    "last_severity": None,
                    "last_plan_trace": [],
                    "last_clarification": None,
                    "structured_context": {},
                }
                return [], empty_state, self._render_session_summary([], [], {}), self._render_result_card([], [], None, [], None, {})

            # Submit the user's input
            user_box.submit(respond, [user_box, state], [user_box, chatbot, state, summary, result_card])

            send_button = gr.Button("Send")
            send_button.click(respond, [user_box, state], [user_box, chatbot, state, summary, result_card])

            # Add example buttons for quick testing of different symptom scenarios
            gr.Examples(
                examples=[
                    "I have fever, headache, chills, and fatigue. What could it be?",
                    "I also have nausea and joint pain.",
                    "Sore throat, runny nose, mild cough for 2 days.",
                    "Chest pain and shortness of breath.",
                ],
                inputs=user_box,
            )

            # Add a button to start a new chat, which clears the conversation history and symptom context
            new_chat_button = gr.Button("New Chat")
            new_chat_button.click(new_chat, outputs=[chatbot, state, summary, result_card])

            # Add a disclaimer
            gr.Markdown(
                "*Disclaimer: This app is for educational purposes only and is not a replacement for professional medical advice. Please consult a healthcare professional for medical concerns.*"
            )

        demo.launch(css=custom_css)

# Run the app
if __name__ == "__main__":
    MedicalChatbotApp().launch()