File size: 143,430 Bytes
9e3b6f4
 
cf9241f
9e3b6f4
 
cf9241f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e3b6f4
 
 
cf9241f
 
 
92c803c
cf9241f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e3b6f4
cf9241f
 
 
 
92c803c
cf9241f
 
 
 
9e3b6f4
cf9241f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e3b6f4
cf9241f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e3b6f4
92c803c
 
cf9241f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92c803c
cf9241f
 
 
 
 
 
 
 
 
 
 
92c803c
 
cf9241f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92c803c
 
cf9241f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92c803c
cf9241f
 
 
 
92c803c
cf9241f
 
 
 
 
 
92c803c
 
cf9241f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e3b6f4
cf9241f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce87cd9
 
 
cf9241f
ce87cd9
 
 
 
 
 
 
cf9241f
ce87cd9
cf9241f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92c803c
cf9241f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92c803c
cf9241f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92c803c
9e3b6f4
 
cf9241f
 
9e3b6f4
cf9241f
 
 
 
 
 
9e3b6f4
cf9241f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92c803c
cf9241f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92c803c
cf9241f
 
 
 
 
9e3b6f4
cf9241f
 
 
 
 
9e3b6f4
cf9241f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e3b6f4
cf9241f
9e3b6f4
 
cf9241f
9e3b6f4
92c803c
9e3b6f4
 
 
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
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
"""
MedGuard - Healthcare Multi-Agent Medication Safety System
Hugging Face Space Entry Point

MCP 1st Birthday Hackathon Submission

This is a self-contained demo that mirrors the FULL production system:
- 5 Specialized AI Agents (Drug Interaction, Personalization, Guideline, Cost, Explanation)
- LangGraph-style orchestration with conditional routing
- BaseAgent pattern with LLM/MCP integration
- Pharmacogenomics (CYP enzyme analysis)
- Beers Criteria for elderly patients
- Polypharmacy detection (5+/10+ medications)
- ML-based novel interaction prediction
- PubMed literature enhancement
- Comprehensive drug interaction database
- Clinical decision support with severity-based prioritization

Architecture mirrors production:
- src/agents/base_agent.py -> BaseAgent abstract class
- src/agents/drug_interaction_agent_enhanced.py -> DrugInteractionAgentEnhanced
- src/agents/personalization_agent.py -> PersonalizationAgent
- src/agents/guideline_compliance_agent.py -> GuidelineComplianceAgent
- src/agents/cost_optimization_agent.py -> CostOptimizationAgent
- src/agents/explanation_agent.py -> ExplanationAgent
- src/orchestration/coordinator_enhanced.py -> MedicationSafetyOrchestrator
"""
import gradio as gr
import os
from typing import Dict, Any, List, Optional, Tuple
from dataclasses import dataclass, field
from enum import Enum
from datetime import datetime
from abc import ABC, abstractmethod
import json
import random

# Try to import LangChain for LLM support (optional for demo)
try:
    from langchain_google_genai import ChatGoogleGenerativeAI
    from langchain_core.messages import HumanMessage, SystemMessage
    HAS_LLM = bool(os.environ.get("GOOGLE_API_KEY"))
except ImportError:
    HAS_LLM = False

# =============================================================================
# MODELS (from src/models/)
# =============================================================================

class InteractionSeverity(str, Enum):
    MINOR = "minor"
    MODERATE = "moderate"
    MAJOR = "major"
    CONTRAINDICATED = "contraindicated"

class EvidenceLevel(str, Enum):
    DEFINITIVE = "definitive"
    PROBABLE = "probable"
    POSSIBLE = "possible"
    THEORETICAL = "theoretical"

@dataclass
class GeneticMarker:
    """Pharmacogenomic marker from src/models/patient.py"""
    gene: str
    variant: str
    phenotype: str  # e.g., "poor_metabolizer", "normal", "ultrarapid"
    implications: List[str] = field(default_factory=list)

@dataclass
class LabResult:
    """Lab result from src/models/patient.py"""
    test_name: str
    value: float
    unit: str
    reference_range: str
    test_date: Optional[datetime] = None
    is_abnormal: bool = False

@dataclass
class Medication:
    name: str
    rxnorm_code: str
    dosage: str
    frequency: str
    route: str = "oral"
    active: bool = True
    drug_class: str = ""  # Added for therapeutic class analysis

@dataclass
class Comorbidity:
    condition: str
    icd10_code: str
    active: bool = True

@dataclass
class Allergy:
    allergen: str
    severity: str
    reaction: str

@dataclass
class PatientProfile:
    patient_id: str
    name: str
    age: int
    sex: str
    weight_kg: float
    height_cm: float
    medications: List[Medication] = field(default_factory=list)
    comorbidities: List[Comorbidity] = field(default_factory=list)
    allergies: List[Allergy] = field(default_factory=list)
    egfr: Optional[float] = None
    liver_function: str = "normal"
    genetic_markers: List[GeneticMarker] = field(default_factory=list)
    lab_results: List[LabResult] = field(default_factory=list)
    
    @property
    def bmi(self) -> float:
        """Calculate BMI"""
        if self.height_cm and self.weight_kg:
            height_m = self.height_cm / 100
            return round(self.weight_kg / (height_m ** 2), 1)
        return 0.0
    
    @property
    def has_renal_impairment(self) -> bool:
        """Check if patient has renal impairment (eGFR < 60)"""
        return self.egfr is not None and self.egfr < 60
    
    @property
    def medication_count(self) -> int:
        """Count of active medications"""
        return len([m for m in self.medications if m.active])

@dataclass
class DrugInteraction:
    drug1_name: str
    drug2_name: str
    severity: InteractionSeverity
    evidence_level: EvidenceLevel
    mechanism: str
    clinical_effect: str
    management_strategy: str
    confidence_score: float = 0.85
    literature_refs: List[str] = field(default_factory=list)  # Added for PubMed citations


# =============================================================================
# MCP TOOL SIMULATION (from src/mcp/healthcare_mcp_server.py)
# =============================================================================

class MCPToolSimulator:
    """
    Simulates the 10 MCP tools from the production healthcare_mcp_server.py
    
    This demonstrates how MCP clients (like Claude Desktop) interact with our server.
    In production, these are exposed via the `mcp` SDK with stdio transport.
    
    Tools:
    1. analyze_medication_safety - Full 5-agent analysis
    2. check_drug_interactions - DDI check only
    3. get_personalized_dosing - Patient-specific dosing
    4. check_guideline_compliance - Clinical guidelines
    5. optimize_medication_costs - Cost savings
    6. get_patient_profile - Patient data
    7. search_clinical_guidelines - BioBERT vector search
    8. explain_medication_decision - Patient-friendly explanation
    9. search_pubmed_literature - MCP Search integration
    10. search_fda_safety_alerts - FDA safety data
    """
    
    def __init__(self):
        self.tool_registry = {
            "analyze_medication_safety": self._analyze_medication_safety,
            "check_drug_interactions": self._check_drug_interactions,
            "get_personalized_dosing": self._get_personalized_dosing,
            "check_guideline_compliance": self._check_guideline_compliance,
            "optimize_medication_costs": self._optimize_medication_costs,
            "get_patient_profile": self._get_patient_profile,
            "search_clinical_guidelines": self._search_clinical_guidelines,
            "explain_medication_decision": self._explain_medication_decision,
            "search_pubmed_literature": self._search_pubmed_literature,
            "search_fda_safety_alerts": self._search_fda_safety_alerts,
        }
        
        # Simulated PubMed data for common queries
        self.pubmed_data = {
            "warfarin aspirin": [
                {
                    "pmid": "27432982",
                    "title": "Dual Antiplatelet Therapy with Aspirin and Clopidogrel: A Systematic Review",
                    "authors": "Kumbhani DJ, et al.",
                    "journal": "JAMA Cardiology",
                    "year": 2020,
                    "key_finding": "Combined therapy significantly increases major bleeding risk (HR 1.73)"
                },
                {
                    "pmid": "29562146",
                    "title": "Warfarin plus Aspirin: Bleeding Risk Meta-Analysis",
                    "authors": "Garcia DA, et al.",
                    "journal": "NEJM",
                    "year": 2021,
                    "key_finding": "Major bleeding increased from 1.2% to 2.8% with combination"
                }
            ],
            "serotonin syndrome ssri tramadol": [
                {
                    "pmid": "31678302",
                    "title": "Serotonin Syndrome: Recognition and Management",
                    "authors": "Boyer EW, Shannon M",
                    "journal": "NEJM",
                    "year": 2019,
                    "key_finding": "SSRI + tramadol combination associated with 4x increased risk"
                }
            ],
            "statin myopathy cyp3a4": [
                {
                    "pmid": "28954892",
                    "title": "Statin-Associated Muscle Symptoms: CYP3A4 Interactions",
                    "authors": "Stroes ES, et al.",
                    "journal": "European Heart Journal",
                    "year": 2022,
                    "key_finding": "CYP3A4 inhibitors increase simvastatin AUC by 10-15 fold"
                }
            ]
        }
        
        # Simulated FDA safety alerts
        self.fda_alerts = {
            "warfarin": [
                {
                    "alert_id": "FDA-2020-1234",
                    "date": "2020-08-15",
                    "type": "safety_alert",
                    "title": "Risk of Major Bleeding with Warfarin",
                    "description": "FDA warns of increased bleeding risk with NSAIDs or antiplatelet agents"
                }
            ],
            "simvastatin": [
                {
                    "alert_id": "FDA-2011-0140",
                    "date": "2011-06-08",
                    "type": "safety_alert",
                    "title": "Simvastatin 80mg Dose Restriction",
                    "description": "FDA restricts 80mg dose due to myopathy risk, especially with CYP3A4 inhibitors"
                }
            ],
            "metformin": [
                {
                    "alert_id": "FDA-2016-0832",
                    "date": "2016-04-08",
                    "type": "safety_alert",
                    "title": "Metformin Use in Renal Impairment",
                    "description": "Updated labeling: can use in mild-moderate renal impairment, contraindicated if eGFR <30"
                }
            ]
        }
    
    async def call_tool(self, tool_name: str, arguments: Dict) -> Dict[str, Any]:
        """
        Simulate calling an MCP tool.
        
        This mirrors how Claude Desktop calls our MCP server via:
        @server.call_tool()
        async def call_tool(name: str, arguments: dict) -> list[TextContent]:
        """
        if tool_name not in self.tool_registry:
            return {"error": f"Unknown tool: {tool_name}", "success": False}
        
        handler = self.tool_registry[tool_name]
        return await handler(arguments)
    
    def list_tools(self) -> List[Dict]:
        """
        Return list of available tools (mirrors @server.list_tools()).
        """
        return [
            {
                "name": "analyze_medication_safety",
                "description": "Comprehensive medication safety analysis using 5 AI agents",
                "parameters": ["patient_id", "query", "include_cost_analysis"]
            },
            {
                "name": "check_drug_interactions",
                "description": "Fast drug-drug interaction check using Neo4j knowledge graph",
                "parameters": ["medications", "patient_allergies"]
            },
            {
                "name": "get_personalized_dosing",
                "description": "Calculate personalized dosing based on patient factors",
                "parameters": ["patient_id", "medication_name", "indication"]
            },
            {
                "name": "check_guideline_compliance",
                "description": "Verify medication regimen against clinical practice guidelines",
                "parameters": ["patient_id", "condition", "proposed_treatment"]
            },
            {
                "name": "optimize_medication_costs",
                "description": "Find cost-effective alternatives maintaining clinical efficacy",
                "parameters": ["current_medications", "insurance_type"]
            },
            {
                "name": "get_patient_profile",
                "description": "Retrieve complete patient profile with medications and allergies",
                "parameters": ["patient_id", "include_history"]
            },
            {
                "name": "search_clinical_guidelines",
                "description": "Semantic search through clinical guidelines using BioBERT",
                "parameters": ["query", "limit"]
            },
            {
                "name": "explain_medication_decision",
                "description": "Generate patient-friendly explanation of recommendations",
                "parameters": ["analysis_summary", "education_level", "language"]
            },
            {
                "name": "search_pubmed_literature",
                "description": "Search PubMed for clinical evidence via MCP Search protocol",
                "parameters": ["query", "study_types", "years", "max_results"]
            },
            {
                "name": "search_fda_safety_alerts",
                "description": "Search FDA safety communications and recalls via MCP Search",
                "parameters": ["drug_name", "alert_types", "years"]
            }
        ]
    
    async def _analyze_medication_safety(self, args: Dict) -> Dict:
        """Tool 1: Full multi-agent analysis (calls orchestrator)."""
        patient_id = args.get("patient_id", "P001")
        patient = DEMO_PATIENTS.get(patient_id)
        
        if not patient:
            return {"error": f"Patient not found: {patient_id}", "success": False}
        
        # This would call the full orchestrator in production
        return {
            "success": True,
            "tool": "analyze_medication_safety",
            "message": f"Full 5-agent analysis queued for patient {patient_id}",
            "agents_to_run": [
                "DrugInteractionAgentEnhanced",
                "PersonalizationAgent", 
                "GuidelineComplianceAgent",
                "CostOptimizationAgent",
                "ExplanationAgent"
            ]
        }
    
    async def _check_drug_interactions(self, args: Dict) -> Dict:
        """Tool 2: Quick DDI check."""
        medications = args.get("medications", [])
        
        # Simulate Neo4j query response
        interactions_found = []
        med_names = [m.get("name", "").lower() for m in medications]
        
        # Check common dangerous pairs
        if "warfarin" in med_names and "aspirin" in med_names:
            interactions_found.append({
                "drug1": "Warfarin",
                "drug2": "Aspirin",
                "severity": "MAJOR",
                "mechanism": "Additive anticoagulant effects"
            })
        
        if "sertraline" in med_names and "tramadol" in med_names:
            interactions_found.append({
                "drug1": "Sertraline",
                "drug2": "Tramadol",
                "severity": "MAJOR",
                "mechanism": "Serotonin syndrome risk"
            })
        
        return {
            "success": True,
            "tool": "check_drug_interactions",
            "medications_analyzed": len(medications),
            "interactions_found": len(interactions_found),
            "interactions": interactions_found,
            "database": "Neo4j knowledge graph"
        }
    
    async def _get_personalized_dosing(self, args: Dict) -> Dict:
        """Tool 3: Personalized dosing calculation."""
        patient_id = args.get("patient_id")
        medication = args.get("medication_name")
        
        patient = DEMO_PATIENTS.get(patient_id)
        if not patient:
            return {"error": f"Patient not found: {patient_id}", "success": False}
        
        adjustments = []
        if patient.egfr and patient.egfr < 60:
            adjustments.append(f"Renal adjustment needed (eGFR: {patient.egfr})")
        if patient.age >= 65:
            adjustments.append("Geriatric dosing considerations")
        if patient.genetic_markers:
            for marker in patient.genetic_markers:
                adjustments.append(f"Pharmacogenomic: {marker.gene} {marker.phenotype}")
        
        return {
            "success": True,
            "tool": "get_personalized_dosing",
            "patient_id": patient_id,
            "medication": medication,
            "adjustments_needed": adjustments,
            "factors_analyzed": ["age", "renal_function", "hepatic_function", "pharmacogenomics"]
        }
    
    async def _check_guideline_compliance(self, args: Dict) -> Dict:
        """Tool 4: Clinical guideline compliance check."""
        condition = args.get("condition", "")
        proposed = args.get("proposed_treatment", [])
        
        guideline_sources = {
            "atrial fibrillation": "AHA/ACC/HRS 2023 AFib Guidelines",
            "heart failure": "ACC/AHA 2022 Heart Failure Guidelines",
            "diabetes": "ADA 2024 Standards of Care",
            "hypertension": "ACC/AHA 2017 Hypertension Guidelines"
        }
        
        source = next((v for k, v in guideline_sources.items() if k in condition.lower()), "Clinical Guidelines")
        
        return {
            "success": True,
            "tool": "check_guideline_compliance",
            "condition": condition,
            "proposed_treatment": proposed,
            "guideline_source": source,
            "compliance_status": "Under review",
            "vector_search": "BioBERT embeddings via Qdrant"
        }
    
    async def _optimize_medication_costs(self, args: Dict) -> Dict:
        """Tool 5: Cost optimization suggestions."""
        medications = args.get("current_medications", [])
        insurance = args.get("insurance_type", "commercial")
        
        savings = []
        for med in medications:
            med_lower = med.lower() if isinstance(med, str) else ""
            if "lipitor" in med_lower:
                savings.append({"current": "Lipitor", "generic": "Atorvastatin", "savings": 285})
            if "crestor" in med_lower:
                savings.append({"current": "Crestor", "generic": "Rosuvastatin", "savings": 260})
        
        return {
            "success": True,
            "tool": "optimize_medication_costs",
            "medications_analyzed": len(medications),
            "insurance_type": insurance,
            "generic_opportunities": savings,
            "total_potential_savings": sum(s["savings"] for s in savings)
        }
    
    async def _get_patient_profile(self, args: Dict) -> Dict:
        """Tool 6: Retrieve patient profile."""
        patient_id = args.get("patient_id")
        patient = DEMO_PATIENTS.get(patient_id)
        
        if not patient:
            return {"error": f"Patient not found: {patient_id}", "success": False}
        
        return {
            "success": True,
            "tool": "get_patient_profile",
            "patient_id": patient.patient_id,
            "demographics": {
                "name": patient.name,
                "age": patient.age,
                "sex": patient.sex,
                "bmi": patient.bmi
            },
            "medications_count": len(patient.medications),
            "allergies_count": len(patient.allergies),
            "comorbidities_count": len(patient.comorbidities),
            "has_genetic_data": len(patient.genetic_markers) > 0
        }
    
    async def _search_clinical_guidelines(self, args: Dict) -> Dict:
        """Tool 7: Semantic search through guidelines."""
        query = args.get("query", "")
        limit = args.get("limit", 5)
        
        return {
            "success": True,
            "tool": "search_clinical_guidelines",
            "query": query,
            "search_method": "BioBERT semantic embeddings",
            "database": "Qdrant vector store",
            "results_count": min(limit, 3),  # Simulated
            "results": [
                {"title": f"Guideline for {query}", "relevance": 0.95},
                {"title": f"Best practices: {query}", "relevance": 0.87}
            ]
        }
    
    async def _explain_medication_decision(self, args: Dict) -> Dict:
        """Tool 8: Generate patient-friendly explanation."""
        summary = args.get("analysis_summary", "")
        level = args.get("education_level", "high_school")
        
        return {
            "success": True,
            "tool": "explain_medication_decision",
            "original_length": len(summary),
            "reading_level": level,
            "explanation": "Your medications have been carefully reviewed by our AI system. We checked for drug interactions, made sure the doses are right for you, and verified everything follows medical guidelines.",
            "key_points": [
                "All medications analyzed for safety",
                "Your specific health factors considered",
                "Recommendations follow evidence-based guidelines"
            ]
        }
    
    async def _search_pubmed_literature(self, args: Dict) -> Dict:
        """Tool 9: Search PubMed via MCP Search protocol."""
        query = args.get("query", "")
        max_results = args.get("max_results", 10)
        
        # Find matching simulated results
        articles = []
        for key, data in self.pubmed_data.items():
            if any(term in query.lower() for term in key.split()):
                articles.extend(data)
        
        return {
            "success": True,
            "tool": "search_pubmed_literature",
            "query": query,
            "protocol": "MCP Search",
            "results_count": len(articles[:max_results]),
            "articles": articles[:max_results],
            "search_url": f"https://pubmed.ncbi.nlm.nih.gov/?term={query.replace(' ', '+')}"
        }
    
    async def _search_fda_safety_alerts(self, args: Dict) -> Dict:
        """Tool 10: Search FDA safety alerts via MCP Search."""
        drug_name = args.get("drug_name", "")
        
        alerts = self.fda_alerts.get(drug_name.lower(), [])
        
        return {
            "success": True,
            "tool": "search_fda_safety_alerts",
            "drug": drug_name,
            "protocol": "MCP Search",
            "alerts_count": len(alerts),
            "alerts": alerts,
            "search_url": f"https://www.fda.gov/drugs/drug-safety-and-availability/search?keys={drug_name}"
        }


# Global MCP tool simulator instance
mcp_tools = MCPToolSimulator()

# =============================================================================
# BASE AGENT (from src/agents/base_agent.py)
# =============================================================================

class BaseAgent(ABC):
    """
    Abstract base class for all healthcare agents.
    Mirrors src/agents/base_agent.py with LLM/MCP integration patterns.
    """
    
    def __init__(self, llm=None, agent_name: str = "BaseAgent"):
        self.llm = llm
        self.agent_name = agent_name
        self.execution_trace: List[Dict] = []
    
    @abstractmethod
    async def execute(self, patient: PatientProfile, **kwargs) -> Dict[str, Any]:
        """Execute agent analysis. Must be implemented by subclasses."""
        pass
    
    def _log_execution(self, action: str, details: Dict):
        """Log execution step for audit trail."""
        self.execution_trace.append({
            "timestamp": datetime.now().isoformat(),
            "agent": self.agent_name,
            "action": action,
            "details": details
        })
    
    async def _call_llm(self, prompt: str, system_prompt: str = "") -> str:
        """Call LLM for analysis. Falls back to rule-based if unavailable."""
        if self.llm and HAS_LLM:
            try:
                messages = []
                if system_prompt:
                    messages.append(SystemMessage(content=system_prompt))
                messages.append(HumanMessage(content=prompt))
                response = await self.llm.ainvoke(messages)
                return response.content
            except Exception as e:
                self._log_execution("llm_error", {"error": str(e)})
                return ""
        return ""
    
    async def execute_with_error_handling(self, patient: PatientProfile, **kwargs) -> Dict[str, Any]:
        """Execute with comprehensive error handling."""
        try:
            self._log_execution("start", {"patient_id": patient.patient_id})
            result = await self.execute(patient, **kwargs)
            self._log_execution("complete", {"success": True})
            return result
        except Exception as e:
            self._log_execution("error", {"error": str(e)})
            return {
                "agent": self.agent_name,
                "error": str(e),
                "success": False
            }


# =============================================================================
# AGENT IMPLEMENTATIONS (from src/agents/)
# =============================================================================

class DrugInteractionAgentEnhanced(BaseAgent):
    """
    Agent 1: Enhanced Drug Interaction Detection
    Mirrors src/agents/drug_interaction_agent_enhanced.py
    
    Features:
    - Known interaction database (Neo4j in production)
    - Metabolic pathway conflict detection (CYP enzymes)
    - ML-based novel interaction prediction
    - Literature enhancement from PubMed
    """
    
    def __init__(self, llm=None):
        super().__init__(llm, "DrugInteractionAgentEnhanced")
        
        # Comprehensive drug interaction database (expanded from production)
        self.interaction_db = {
            # Anticoagulant interactions
            ("warfarin", "aspirin"): DrugInteraction(
                drug1_name="Warfarin", drug2_name="Aspirin",
                severity=InteractionSeverity.MAJOR,
                evidence_level=EvidenceLevel.DEFINITIVE,
                mechanism="Pharmacodynamic: Additive anticoagulant/antiplatelet effects",
                clinical_effect="Significantly increased bleeding risk, including GI hemorrhage and intracranial bleeding",
                management_strategy="If combination necessary: use low-dose aspirin (81mg), monitor INR closely, add PPI for gastroprotection",
                literature_refs=["PMID:27432982", "PMID:29562146"]
            ),
            ("warfarin", "ibuprofen"): DrugInteraction(
                drug1_name="Warfarin", drug2_name="Ibuprofen",
                severity=InteractionSeverity.MAJOR,
                evidence_level=EvidenceLevel.DEFINITIVE,
                mechanism="NSAIDs inhibit platelet function and can cause GI erosions; also CYP2C9 interaction",
                clinical_effect="Increased bleeding risk, GI hemorrhage, INR elevation",
                management_strategy="Avoid combination. If necessary, use lowest NSAID dose for shortest duration with PPI"
            ),
            ("warfarin", "amiodarone"): DrugInteraction(
                drug1_name="Warfarin", drug2_name="Amiodarone",
                severity=InteractionSeverity.MAJOR,
                evidence_level=EvidenceLevel.DEFINITIVE,
                mechanism="CYP2C9 and CYP3A4 inhibition by amiodarone increases warfarin levels",
                clinical_effect="30-50% increase in INR, bleeding risk",
                management_strategy="Reduce warfarin dose by 30-50% when starting amiodarone. Weekly INR for first month"
            ),
            ("warfarin", "metformin"): DrugInteraction(
                drug1_name="Warfarin", drug2_name="Metformin",
                severity=InteractionSeverity.MINOR,
                evidence_level=EvidenceLevel.POSSIBLE,
                mechanism="Theoretical protein binding displacement",
                clinical_effect="Minimal clinical significance",
                management_strategy="No dose adjustment needed, routine INR monitoring sufficient"
            ),
            
            # Serotonin syndrome risks
            ("sertraline", "tramadol"): DrugInteraction(
                drug1_name="Sertraline", drug2_name="Tramadol",
                severity=InteractionSeverity.MAJOR,
                evidence_level=EvidenceLevel.DEFINITIVE,
                mechanism="Pharmacodynamic: Both increase serotonin levels via different mechanisms",
                clinical_effect="Risk of serotonin syndrome (hyperthermia, agitation, tremor, hyperreflexia)",
                management_strategy="Avoid combination if possible. If necessary, use lowest doses and monitor for serotonin syndrome symptoms",
                literature_refs=["PMID:31678302"]
            ),
            ("sertraline", "sumatriptan"): DrugInteraction(
                drug1_name="Sertraline", drug2_name="Sumatriptan",
                severity=InteractionSeverity.MODERATE,
                evidence_level=EvidenceLevel.PROBABLE,
                mechanism="Both drugs increase serotonin levels",
                clinical_effect="Theoretical risk of serotonin syndrome, though rare in practice",
                management_strategy="Monitor for serotonin syndrome symptoms. Use lowest effective triptan dose"
            ),
            ("sertraline", "zolpidem"): DrugInteraction(
                drug1_name="Sertraline", drug2_name="Zolpidem",
                severity=InteractionSeverity.MODERATE,
                evidence_level=EvidenceLevel.PROBABLE,
                mechanism="Additive CNS depression",
                clinical_effect="Enhanced sedation, impaired psychomotor function, increased fall risk",
                management_strategy="Use lowest effective doses, warn about morning drowsiness, fall precautions"
            ),
            
            # ACE inhibitor interactions
            ("lisinopril", "potassium"): DrugInteraction(
                drug1_name="Lisinopril", drug2_name="Potassium Chloride",
                severity=InteractionSeverity.MAJOR,
                evidence_level=EvidenceLevel.DEFINITIVE,
                mechanism="ACE inhibitors reduce aldosterone, decreasing potassium excretion",
                clinical_effect="Risk of hyperkalemia, potentially life-threatening cardiac arrhythmias",
                management_strategy="Monitor potassium levels closely (within 1 week of starting), avoid if K+ >5.0"
            ),
            ("lisinopril", "spironolactone"): DrugInteraction(
                drug1_name="Lisinopril", drug2_name="Spironolactone",
                severity=InteractionSeverity.MAJOR,
                evidence_level=EvidenceLevel.DEFINITIVE,
                mechanism="Both drugs increase serum potassium through different mechanisms",
                clinical_effect="High risk of hyperkalemia",
                management_strategy="If used together, start low dose, monitor K+ weekly initially"
            ),
            
            # Cardiovascular combinations
            ("furosemide", "carvedilol"): DrugInteraction(
                drug1_name="Furosemide", drug2_name="Carvedilol",
                severity=InteractionSeverity.MODERATE,
                evidence_level=EvidenceLevel.PROBABLE,
                mechanism="Additive hypotensive effects; diuretic-induced hypovolemia enhances beta-blocker effect",
                clinical_effect="Postural hypotension, dizziness, syncope risk",
                management_strategy="Monitor BP, especially on initiation. Rise slowly from sitting/lying position"
            ),
            ("metoprolol", "albuterol"): DrugInteraction(
                drug1_name="Metoprolol", drug2_name="Albuterol",
                severity=InteractionSeverity.MODERATE,
                evidence_level=EvidenceLevel.DEFINITIVE,
                mechanism="Pharmacodynamic antagonism: Beta-blocker opposes beta-agonist bronchodilation",
                clinical_effect="Reduced bronchodilator efficacy, potential bronchospasm in susceptible patients",
                management_strategy="Use cardioselective beta-blocker at lowest effective dose. Consider alternative antihypertensive"
            ),
            ("metoprolol", "diltiazem"): DrugInteraction(
                drug1_name="Metoprolol", drug2_name="Diltiazem",
                severity=InteractionSeverity.MAJOR,
                evidence_level=EvidenceLevel.DEFINITIVE,
                mechanism="Both drugs slow AV conduction; diltiazem inhibits CYP2D6 increasing metoprolol levels",
                clinical_effect="Risk of severe bradycardia, heart block, hypotension",
                management_strategy="Avoid combination if possible. If needed, use lowest doses with close monitoring"
            ),
            
            # Statin interactions
            ("simvastatin", "amlodipine"): DrugInteraction(
                drug1_name="Simvastatin", drug2_name="Amlodipine",
                severity=InteractionSeverity.MAJOR,
                evidence_level=EvidenceLevel.DEFINITIVE,
                mechanism="CYP3A4 inhibition by amlodipine increases simvastatin exposure",
                clinical_effect="Increased risk of myopathy and rhabdomyolysis",
                management_strategy="Limit simvastatin to 20mg/day with amlodipine. Consider switching to pravastatin or rosuvastatin"
            ),
            ("simvastatin", "clarithromycin"): DrugInteraction(
                drug1_name="Simvastatin", drug2_name="Clarithromycin",
                severity=InteractionSeverity.CONTRAINDICATED,
                evidence_level=EvidenceLevel.DEFINITIVE,
                mechanism="Strong CYP3A4 inhibition dramatically increases statin levels",
                clinical_effect="High risk of rhabdomyolysis, acute kidney injury",
                management_strategy="CONTRAINDICATED. Hold simvastatin during clarithromycin course"
            ),
            ("atorvastatin", "grapefruit"): DrugInteraction(
                drug1_name="Atorvastatin", drug2_name="Grapefruit",
                severity=InteractionSeverity.MODERATE,
                evidence_level=EvidenceLevel.DEFINITIVE,
                mechanism="Grapefruit inhibits intestinal CYP3A4, increasing statin absorption",
                clinical_effect="Increased statin exposure and myopathy risk",
                management_strategy="Limit grapefruit intake or switch to pravastatin/rosuvastatin"
            ),
            
            # Digoxin interactions
            ("digoxin", "amiodarone"): DrugInteraction(
                drug1_name="Digoxin", drug2_name="Amiodarone",
                severity=InteractionSeverity.MAJOR,
                evidence_level=EvidenceLevel.DEFINITIVE,
                mechanism="Amiodarone inhibits P-glycoprotein, increasing digoxin levels",
                clinical_effect="70-100% increase in digoxin levels, toxicity risk",
                management_strategy="Reduce digoxin dose by 50% when adding amiodarone. Monitor levels"
            ),
            ("digoxin", "verapamil"): DrugInteraction(
                drug1_name="Digoxin", drug2_name="Verapamil",
                severity=InteractionSeverity.MAJOR,
                evidence_level=EvidenceLevel.DEFINITIVE,
                mechanism="P-glycoprotein inhibition; additive AV nodal suppression",
                clinical_effect="Increased digoxin levels, bradycardia, heart block",
                management_strategy="Reduce digoxin dose by 25-50%. Monitor for bradycardia"
            ),
            
            # Diabetes drug interactions
            ("metformin", "contrast"): DrugInteraction(
                drug1_name="Metformin", drug2_name="IV Contrast",
                severity=InteractionSeverity.MAJOR,
                evidence_level=EvidenceLevel.DEFINITIVE,
                mechanism="Contrast-induced nephropathy impairs metformin excretion",
                clinical_effect="Risk of lactic acidosis if renal function declines",
                management_strategy="Hold metformin 48h before and after IV contrast. Check renal function before restarting"
            ),
            ("glipizide", "fluconazole"): DrugInteraction(
                drug1_name="Glipizide", drug2_name="Fluconazole",
                severity=InteractionSeverity.MAJOR,
                evidence_level=EvidenceLevel.DEFINITIVE,
                mechanism="CYP2C9 inhibition increases sulfonylurea levels",
                clinical_effect="Severe hypoglycemia risk",
                management_strategy="Reduce glipizide dose by 50%. Monitor blood glucose closely"
            ),
            
            # Opioid interactions
            ("oxycodone", "benzodiazepine"): DrugInteraction(
                drug1_name="Oxycodone", drug2_name="Benzodiazepines",
                severity=InteractionSeverity.MAJOR,
                evidence_level=EvidenceLevel.DEFINITIVE,
                mechanism="Additive CNS and respiratory depression",
                clinical_effect="Increased risk of sedation, respiratory depression, overdose death",
                management_strategy="Avoid combination. FDA black box warning. If necessary, use lowest doses"
            ),
        }
        
        # Metabolic pathway database for CYP conflict detection
        self.cyp_substrates = {
            "CYP2D6": ["metoprolol", "carvedilol", "codeine", "tramadol", "fluoxetine", "paroxetine"],
            "CYP3A4": ["simvastatin", "atorvastatin", "amlodipine", "diltiazem", "midazolam", "fentanyl"],
            "CYP2C9": ["warfarin", "phenytoin", "glipizide", "losartan", "celecoxib"],
            "CYP2C19": ["omeprazole", "clopidogrel", "diazepam", "citalopram", "escitalopram"],
            "CYP1A2": ["theophylline", "caffeine", "clozapine", "olanzapine"]
        }
        
        self.cyp_inhibitors = {
            "CYP2D6": ["fluoxetine", "paroxetine", "bupropion", "quinidine"],
            "CYP3A4": ["clarithromycin", "ketoconazole", "itraconazole", "ritonavir", "grapefruit", "diltiazem", "verapamil", "amiodarone"],
            "CYP2C9": ["fluconazole", "amiodarone", "metronidazole"],
            "CYP2C19": ["omeprazole", "fluconazole", "fluvoxamine"],
            "CYP1A2": ["ciprofloxacin", "fluvoxamine"]
        }
    
    async def execute(self, patient: PatientProfile, **kwargs) -> Dict[str, Any]:
        """Execute comprehensive drug interaction analysis."""
        self._log_execution("starting_analysis", {"med_count": patient.medication_count})
        
        # Step 1: Check known interactions
        known_interactions = await self._check_known_interactions(patient)
        
        # Step 2: Check metabolic conflicts
        metabolic_conflicts = await self._check_metabolic_interactions(patient)
        
        # Step 3: Predict novel interactions (ML/LLM in production)
        novel_predictions = await self._predict_novel_interactions(patient)
        
        # Step 4: Enhance with literature (PubMed in production)
        literature_enhanced = await self._enhance_with_literature(known_interactions)
        
        # Combine and categorize
        all_interactions = known_interactions + metabolic_conflicts + novel_predictions
        critical_interactions = [i for i in all_interactions 
                                if i.get("severity") in ["major", "contraindicated"]]
        
        return {
            "agent": self.agent_name,
            "interactions": all_interactions,
            "critical_interactions": critical_interactions,
            "metabolic_conflicts": metabolic_conflicts,
            "total_found": len(all_interactions),
            "critical_count": len(critical_interactions),
            "literature_enhanced": literature_enhanced,
            "confidence": 0.92
        }
    
    async def _check_known_interactions(self, patient: PatientProfile) -> List[Dict]:
        """Check against known interaction database."""
        interactions = []
        meds = [m for m in patient.medications if m.active]
        
        for i, med1 in enumerate(meds):
            for med2 in meds[i+1:]:
                key1 = (med1.name.lower(), med2.name.lower())
                key2 = (med2.name.lower(), med1.name.lower())
                
                interaction = self.interaction_db.get(key1) or self.interaction_db.get(key2)
                
                if interaction:
                    interactions.append({
                        "drug1": interaction.drug1_name,
                        "drug2": interaction.drug2_name,
                        "severity": interaction.severity.value,
                        "evidence_level": interaction.evidence_level.value,
                        "mechanism": interaction.mechanism,
                        "clinical_effect": interaction.clinical_effect,
                        "management": interaction.management_strategy,
                        "confidence": interaction.confidence_score,
                        "literature_refs": interaction.literature_refs,
                        "source": "knowledge_base"
                    })
        
        return interactions
    
    async def _check_metabolic_interactions(self, patient: PatientProfile) -> List[Dict]:
        """Detect CYP enzyme-mediated drug interactions."""
        conflicts = []
        med_names = [m.name.lower() for m in patient.medications if m.active]
        
        for enzyme, substrates in self.cyp_substrates.items():
            # Find substrates patient is taking
            patient_substrates = [med for med in med_names 
                                 if any(sub in med for sub in substrates)]
            
            # Find inhibitors patient is taking
            inhibitors = self.cyp_inhibitors.get(enzyme, [])
            patient_inhibitors = [med for med in med_names 
                                 if any(inh in med for inh in inhibitors)]
            
            # Report conflicts
            for substrate in patient_substrates:
                for inhibitor in patient_inhibitors:
                    if substrate != inhibitor:  # Don't report self-interaction
                        conflicts.append({
                            "drug1": substrate.title(),
                            "drug2": inhibitor.title(),
                            "severity": "moderate",
                            "evidence_level": "probable",
                            "mechanism": f"CYP {enzyme} inhibition by {inhibitor.title()} may increase {substrate.title()} levels",
                            "clinical_effect": f"Potential for increased {substrate.title()} exposure and toxicity",
                            "management": f"Monitor for {substrate.title()} toxicity, consider dose reduction",
                            "confidence": 0.75,
                            "source": "metabolic_analysis"
                        })
        
        return conflicts
    
    async def _predict_novel_interactions(self, patient: PatientProfile) -> List[Dict]:
        """Use ML/LLM to predict potential novel interactions not in database."""
        # In production, this calls LLM with structured output
        # For demo, we simulate ML confidence scoring
        
        if len(patient.medications) < 5:
            return []
        
        # Simulate novel interaction detection for polypharmacy
        return [{
            "drug1": "Multi-drug Combination",
            "drug2": f"{patient.medication_count} medications",
            "severity": "moderate",
            "evidence_level": "theoretical",
            "mechanism": "Complex polypharmacy interaction network",
            "clinical_effect": "Cumulative CNS depression, metabolic burden, and fall risk",
            "management": "Comprehensive medication review recommended",
            "confidence": 0.65,
            "source": "ml_prediction"
        }]
    
    async def _enhance_with_literature(self, interactions: List[Dict]) -> Dict:
        """Enhance findings with PubMed literature (simulated)."""
        # In production, this calls PubMed MCP Search
        enhanced_count = sum(1 for i in interactions if i.get("literature_refs"))
        return {
            "total_citations": enhanced_count * 2,  # Simulated
            "recent_publications": enhanced_count,
            "meta_analyses_available": enhanced_count > 0
        }


class PersonalizationAgent(BaseAgent):
    """
    Agent 2: Patient-Specific Personalization
    Mirrors src/agents/personalization_agent.py
    
    Features:
    - Pharmacogenomics analysis (CYP2D6, CYP2C9, CYP2C19, CYP3A4)
    - Renal dose adjustments based on eGFR
    - Hepatic dose adjustments
    - Beers Criteria for elderly (complete list)
    - Age-specific considerations (pediatric, geriatric)
    - Pregnancy/lactation (if applicable)
    """
    
    def __init__(self, llm=None):
        super().__init__(llm, "PersonalizationAgent")
        
        # Comprehensive renal adjustment database
        self.renal_adjustments = {
            "metformin": {"egfr_threshold": 30, "action": "contraindicated", "severity": "critical"},
            "gabapentin": {"egfr_threshold": 60, "action": "dose_reduce_50%", "severity": "high"},
            "pregabalin": {"egfr_threshold": 60, "action": "dose_reduce_50%", "severity": "high"},
            "digoxin": {"egfr_threshold": 50, "action": "dose_reduce_25%", "severity": "high"},
            "enoxaparin": {"egfr_threshold": 30, "action": "dose_reduce_50%", "severity": "critical"},
            "dabigatran": {"egfr_threshold": 30, "action": "contraindicated", "severity": "critical"},
            "rivaroxaban": {"egfr_threshold": 15, "action": "dose_reduce", "severity": "high"},
            "apixaban": {"egfr_threshold": 25, "action": "dose_reduce", "severity": "high"},
            "methotrexate": {"egfr_threshold": 60, "action": "dose_reduce", "severity": "high"},
            "lithium": {"egfr_threshold": 60, "action": "dose_reduce_monitor", "severity": "high"},
            "allopurinol": {"egfr_threshold": 60, "action": "dose_reduce", "severity": "moderate"},
            "colchicine": {"egfr_threshold": 30, "action": "dose_reduce_50%", "severity": "high"},
            "morphine": {"egfr_threshold": 50, "action": "extended_interval", "severity": "high"},
            "codeine": {"egfr_threshold": 50, "action": "avoid", "severity": "high"},
        }
        
        # Hepatic adjustment database
        self.hepatic_adjustments = {
            "acetaminophen": {"max_dose": "2g/day", "severity": "high"},
            "methotrexate": {"action": "contraindicated", "severity": "critical"},
            "simvastatin": {"action": "dose_reduce", "severity": "high"},
            "atorvastatin": {"action": "dose_reduce", "severity": "moderate"},
            "warfarin": {"action": "dose_reduce_monitor", "severity": "high"},
            "tramadol": {"action": "extended_interval", "severity": "moderate"},
        }
        
        # Complete Beers Criteria list (2023 AGS update)
        self.beers_criteria = {
            # First-generation antihistamines
            "diphenhydramine": {"reason": "Highly anticholinergic, sedating", "alternative": "Loratadine, cetirizine"},
            "hydroxyzine": {"reason": "Anticholinergic, sedating", "alternative": "Non-sedating antihistamines"},
            "chlorpheniramine": {"reason": "Anticholinergic", "alternative": "Second-gen antihistamines"},
            "promethazine": {"reason": "Highly anticholinergic, sedating", "alternative": "Ondansetron for nausea"},
            
            # Benzodiazepines
            "diazepam": {"reason": "Long half-life, increased fall risk, cognitive impairment", "alternative": "Non-benzo sleep aids if needed"},
            "alprazolam": {"reason": "Fall risk, cognitive impairment", "alternative": "SSRIs for anxiety"},
            "lorazepam": {"reason": "Fall risk, cognitive impairment", "alternative": "Consider trazodone for insomnia"},
            "clonazepam": {"reason": "Long-acting, fall risk", "alternative": "SSRIs/SNRIs"},
            "temazepam": {"reason": "Fall risk", "alternative": "Sleep hygiene, melatonin"},
            
            # Non-benzo hypnotics
            "zolpidem": {"reason": "ER visits, motor vehicle accidents, falls, fractures", "alternative": "Sleep hygiene, low-dose trazodone"},
            "eszopiclone": {"reason": "Similar concerns to zolpidem", "alternative": "Melatonin, CBT-I"},
            
            # Anticholinergics
            "amitriptyline": {"reason": "Highly anticholinergic, sedating", "alternative": "Nortriptyline if TCA needed"},
            "imipramine": {"reason": "Anticholinergic", "alternative": "SSRIs/SNRIs"},
            "doxepin_high": {"reason": "Anticholinergic at doses >6mg", "alternative": "Doxepin 3-6mg if needed"},
            "oxybutynin": {"reason": "Anticholinergic, cognitive effects", "alternative": "Mirabegron"},
            "tolterodine": {"reason": "Anticholinergic", "alternative": "Mirabegron, behavioral therapy"},
            
            # NSAIDs
            "indomethacin": {"reason": "Highest GI risk, CNS effects", "alternative": "Acetaminophen, topical NSAIDs"},
            "ketorolac": {"reason": "High GI bleeding risk", "alternative": "Acetaminophen"},
            
            # Muscle relaxants
            "cyclobenzaprine": {"reason": "Anticholinergic, sedating, limited efficacy", "alternative": "Physical therapy"},
            "methocarbamol": {"reason": "Sedating, fall risk", "alternative": "Physical therapy"},
            "carisoprodol": {"reason": "Metabolized to meprobamate, addiction risk", "alternative": "Physical therapy"},
            
            # Antipsychotics
            "haloperidol": {"reason": "Increased mortality in dementia", "alternative": "Avoid if possible"},
            "quetiapine": {"reason": "Metabolic effects, sedation, fall risk", "alternative": "Minimize use"},
            
            # Other
            "meperidine": {"reason": "Neurotoxic metabolite, seizure risk", "alternative": "Other opioids if needed"},
            "nitrofurantoin": {"reason": "Pulmonary toxicity, ineffective if CrCl<30", "alternative": "Other antibiotics based on culture"},
        }
        
        # Pharmacogenomics database (CYP enzyme phenotypes)
        self.pharmacogenomics = {
            "CYP2D6": {
                "poor_metabolizer": {
                    "affected_drugs": ["codeine", "tramadol", "oxycodone", "metoprolol", "carvedilol"],
                    "effect": "reduced_efficacy_or_toxicity",
                    "recommendations": {
                        "codeine": "AVOID - minimal to no efficacy, use alternative analgesic",
                        "tramadol": "AVOID - reduced efficacy, consider alternative",
                        "metoprolol": "Reduce dose 50-75%, monitor for bradycardia",
                        "carvedilol": "Reduce dose, monitor closely"
                    }
                },
                "ultrarapid_metabolizer": {
                    "affected_drugs": ["codeine", "tramadol"],
                    "effect": "increased_toxicity",
                    "recommendations": {
                        "codeine": "AVOID - risk of fatal respiratory depression",
                        "tramadol": "AVOID - increased seizure and respiratory risk"
                    }
                }
            },
            "CYP2C9": {
                "poor_metabolizer": {
                    "affected_drugs": ["warfarin", "phenytoin", "celecoxib"],
                    "effect": "increased_drug_levels",
                    "recommendations": {
                        "warfarin": "Reduce initial dose 50%, more frequent INR monitoring",
                        "phenytoin": "Reduce dose, monitor levels closely"
                    }
                }
            },
            "CYP2C19": {
                "poor_metabolizer": {
                    "affected_drugs": ["clopidogrel", "omeprazole", "citalopram"],
                    "effect": "variable_by_drug",
                    "recommendations": {
                        "clopidogrel": "Consider prasugrel or ticagrelor instead",
                        "omeprazole": "Standard dosing okay (actually more effective)",
                        "citalopram": "Reduce dose, max 20mg"
                    }
                },
                "ultrarapid_metabolizer": {
                    "affected_drugs": ["omeprazole", "pantoprazole"],
                    "effect": "reduced_efficacy",
                    "recommendations": {
                        "omeprazole": "May need higher doses or switch to rabeprazole"
                    }
                }
            }
        }
    
    async def execute(self, patient: PatientProfile, **kwargs) -> Dict[str, Any]:
        """Execute comprehensive personalization analysis."""
        self._log_execution("starting_personalization", {
            "age": patient.age,
            "egfr": patient.egfr,
            "liver_function": patient.liver_function
        })
        
        findings = {
            "agent": self.agent_name,
            "renal_adjustments": [],
            "hepatic_adjustments": [],
            "age_concerns": [],
            "pharmacogenomics": [],
            "polypharmacy_alert": None,
            "risk_score": 0.0
        }
        
        # 1. Renal adjustments
        findings["renal_adjustments"] = await self._check_renal_adjustments(patient)
        
        # 2. Hepatic adjustments
        findings["hepatic_adjustments"] = await self._check_hepatic_adjustments(patient)
        
        # 3. Age-related concerns (Beers Criteria for elderly)
        findings["age_concerns"] = await self._analyze_age_factors(patient)
        
        # 4. Pharmacogenomics
        findings["pharmacogenomics"] = await self._analyze_pharmacogenetics(patient)
        
        # 5. Polypharmacy assessment
        findings["polypharmacy_alert"] = await self._check_polypharmacy(patient)
        
        # Calculate risk score
        critical_count = len([a for a in findings["renal_adjustments"] if a.get("severity") == "critical"])
        high_count = len([a for a in findings["renal_adjustments"] if a.get("severity") == "high"])
        high_count += len([a for a in findings["age_concerns"] if a.get("severity") == "high"])
        
        findings["risk_score"] = min(1.0, critical_count * 0.3 + high_count * 0.15)
        
        return findings
    
    async def _check_renal_adjustments(self, patient: PatientProfile) -> List[Dict]:
        """Check for medications needing renal adjustment."""
        adjustments = []
        
        if not patient.egfr:
            return adjustments
        
        for med in patient.medications:
            if not med.active:
                continue
            
            med_lower = med.name.lower()
            for drug, criteria in self.renal_adjustments.items():
                if drug in med_lower and patient.egfr < criteria["egfr_threshold"]:
                    adjustments.append({
                        "medication": med.name,
                        "egfr": patient.egfr,
                        "threshold": criteria["egfr_threshold"],
                        "severity": criteria["severity"],
                        "action": criteria["action"],
                        "recommendation": f"{criteria['action'].replace('_', ' ').title()} - eGFR {patient.egfr} below threshold {criteria['egfr_threshold']}"
                    })
        
        return adjustments
    
    async def _check_hepatic_adjustments(self, patient: PatientProfile) -> List[Dict]:
        """Check for medications needing hepatic adjustment."""
        adjustments = []
        
        if patient.liver_function not in ["mild_impairment", "moderate_impairment", "severe_impairment"]:
            return adjustments
        
        for med in patient.medications:
            if not med.active:
                continue
            
            med_lower = med.name.lower()
            for drug, criteria in self.hepatic_adjustments.items():
                if drug in med_lower:
                    adjustments.append({
                        "medication": med.name,
                        "liver_function": patient.liver_function,
                        "severity": criteria["severity"],
                        "recommendation": criteria.get("action", criteria.get("max_dose", "Review needed"))
                    })
        
        return adjustments
    
    async def _analyze_age_factors(self, patient: PatientProfile) -> List[Dict]:
        """Analyze age-related medication concerns."""
        concerns = []
        
        # Elderly patients (Beers Criteria)
        if patient.age >= 65:
            concerns.append({
                "concern": "Elderly patient (β‰₯65 years)",
                "severity": "info",
                "recommendations": [
                    "Review for fall risk with sedating medications",
                    "Consider renal function decline with age",
                    "Check for anticholinergic burden",
                    "Evaluate for deprescribing opportunities"
                ]
            })
            
            # Check Beers Criteria medications
            for med in patient.medications:
                if not med.active:
                    continue
                
                med_lower = med.name.lower()
                for drug, criteria in self.beers_criteria.items():
                    if drug in med_lower:
                        concerns.append({
                            "medication": med.name,
                            "concern": f"Potentially Inappropriate in Elderly (Beers Criteria)",
                            "reason": criteria["reason"],
                            "alternative": criteria["alternative"],
                            "severity": "high",
                            "source": "AGS Beers Criteria 2023"
                        })
        
        # Very elderly (85+)
        if patient.age >= 85:
            concerns.append({
                "concern": "Very elderly patient (β‰₯85 years)",
                "severity": "high",
                "recommendations": [
                    "Prioritize functional status over disease targets",
                    "Consider prognosis in treatment decisions",
                    "Aggressive deprescribing review",
                    "Enhanced fall prevention"
                ]
            })
        
        return concerns
    
    async def _analyze_pharmacogenetics(self, patient: PatientProfile) -> List[Dict]:
        """Analyze pharmacogenomic implications."""
        findings = []
        
        if not patient.genetic_markers:
            return findings
        
        for marker in patient.genetic_markers:
            gene = marker.gene
            phenotype = marker.phenotype
            
            if gene in self.pharmacogenomics:
                gene_data = self.pharmacogenomics[gene].get(phenotype, {})
                
                for med in patient.medications:
                    if not med.active:
                        continue
                    
                    med_lower = med.name.lower()
                    for affected_drug in gene_data.get("affected_drugs", []):
                        if affected_drug in med_lower:
                            recommendation = gene_data.get("recommendations", {}).get(affected_drug, "Review needed")
                            findings.append({
                                "medication": med.name,
                                "gene": gene,
                                "variant": marker.variant,
                                "phenotype": phenotype,
                                "effect": gene_data.get("effect", "unknown"),
                                "recommendation": recommendation,
                                "severity": "high" if "AVOID" in recommendation.upper() else "moderate"
                            })
        
        return findings
    
    async def _check_polypharmacy(self, patient: PatientProfile) -> Optional[Dict]:
        """Assess polypharmacy risk."""
        active_meds = [m for m in patient.medications if m.active]
        count = len(active_meds)
        
        if count >= 10:
            return {
                "level": "severe",
                "medication_count": count,
                "severity": "high",
                "recommendation": "Comprehensive medication review REQUIRED. Consider deprescribing.",
                "risks": [
                    "Significantly increased drug interaction risk",
                    "Medication non-adherence likely",
                    "Increased fall risk",
                    "Cognitive impairment risk",
                    "Hospitalization risk increased 3-fold"
                ]
            }
        elif count >= 5:
            return {
                "level": "moderate",
                "medication_count": count,
                "severity": "moderate",
                "recommendation": "Medication review recommended. Evaluate each medication's necessity.",
                "risks": [
                    "Increased drug interaction probability",
                    "Potential adherence challenges",
                    "Consider simplifying regimen"
                ]
            }
        
        return None


class GuidelineComplianceAgent(BaseAgent):
    """
    Agent 3: Clinical Guideline Compliance
    Mirrors src/agents/guideline_compliance_agent.py
    
    Features:
    - Evidence-based guideline checking (AHA/ACC, ADA, ESC)
    - Condition-specific therapy recommendations
    - Polypharmacy detection (5+, 10+ thresholds)
    - Compliance scoring
    - Vector store search for guidelines (simulated)
    """
    
    def __init__(self, llm=None):
        super().__init__(llm, "GuidelineComplianceAgent")
        
        # Comprehensive clinical guidelines database
        self.guidelines = {
            "atrial fibrillation": {
                "required_classes": ["anticoagulant"],
                "first_line": ["apixaban", "rivaroxaban", "dabigatran", "edoxaban"],
                "alternative": ["warfarin"],
                "contraindicated_with": ["mechanical_heart_valve"],
                "source": "AHA/ACC/HRS 2023 AFib Guidelines",
                "key_recommendations": [
                    "CHA2DS2-VASc scoring for stroke risk",
                    "DOACs preferred over warfarin unless mechanical valve or moderate-severe mitral stenosis",
                    "Rate vs rhythm control based on symptoms"
                ]
            },
            "heart failure": {
                "required_classes": ["ace_inhibitor_or_arb_or_arni", "beta_blocker", "diuretic", "sglt2i"],
                "first_line": ["sacubitril-valsartan", "lisinopril", "losartan", "carvedilol", "metoprolol succinate", "bisoprolol", "furosemide", "empagliflozin", "dapagliflozin"],
                "mra_if_severe": ["spironolactone", "eplerenone"],
                "source": "ACC/AHA 2022 Heart Failure Guidelines",
                "key_recommendations": [
                    "GDMT optimization with 4 pillars: ACEI/ARB/ARNI, BB, MRA, SGLT2i",
                    "SGLT2i now class I recommendation regardless of diabetes",
                    "Target doses of evidence-based therapies"
                ]
            },
            "type 2 diabetes": {
                "required_classes": ["antidiabetic"],
                "first_line": ["metformin"],
                "with_cv_disease": ["empagliflozin", "dapagliflozin", "semaglutide", "liraglutide"],
                "with_ckd": ["empagliflozin", "dapagliflozin", "finerenone"],
                "source": "ADA 2024 Standards of Care",
                "key_recommendations": [
                    "A1c target typically <7% (individualized)",
                    "SGLT2i or GLP-1 RA for patients with ASCVD, HF, or CKD",
                    "Weight management integral to treatment"
                ]
            },
            "hypertension": {
                "required_classes": ["antihypertensive"],
                "first_line": ["lisinopril", "amlodipine", "losartan", "hydrochlorothiazide", "chlorthalidone"],
                "with_diabetes": ["lisinopril", "losartan"],
                "with_ckd": ["lisinopril", "losartan"],
                "source": "ACC/AHA 2017 Hypertension Guidelines",
                "key_recommendations": [
                    "BP target <130/80 for high-risk patients",
                    "ACEi/ARB preferred with diabetes or CKD",
                    "Two-drug combination often needed"
                ]
            },
            "coronary artery disease": {
                "required_classes": ["antiplatelet", "statin", "beta_blocker_if_prior_mi"],
                "antiplatelet": ["aspirin", "clopidogrel", "ticagrelor", "prasugrel"],
                "statins": ["atorvastatin", "rosuvastatin"],
                "source": "ACC/AHA CAD Guidelines 2023",
                "key_recommendations": [
                    "High-intensity statin therapy",
                    "Aspirin for secondary prevention",
                    "DAPT post-PCI per guidelines"
                ]
            },
            "chronic kidney disease": {
                "required_classes": ["ace_inhibitor_or_arb", "sglt2i_if_appropriate"],
                "first_line": ["lisinopril", "losartan", "dapagliflozin", "empagliflozin"],
                "avoid": ["nsaids", "high_dose_vitamin_c"],
                "source": "KDIGO 2024 CKD Guidelines",
                "key_recommendations": [
                    "ACEi/ARB for albuminuric CKD",
                    "SGLT2i for eGFR β‰₯20 with albuminuria",
                    "BP target <120 systolic if tolerated"
                ]
            }
        }
        
        # Drug class mappings for compliance checking
        self.drug_classes = {
            "anticoagulant": ["warfarin", "apixaban", "rivaroxaban", "dabigatran", "edoxaban", "enoxaparin", "heparin"],
            "antiplatelet": ["aspirin", "clopidogrel", "ticagrelor", "prasugrel"],
            "ace_inhibitor": ["lisinopril", "enalapril", "ramipril", "benazepril", "captopril"],
            "arb": ["losartan", "valsartan", "irbesartan", "olmesartan", "candesartan"],
            "beta_blocker": ["metoprolol", "carvedilol", "bisoprolol", "atenolol", "propranolol"],
            "statin": ["atorvastatin", "rosuvastatin", "simvastatin", "pravastatin", "lovastatin"],
            "sglt2i": ["empagliflozin", "dapagliflozin", "canagliflozin", "ertugliflozin"],
            "glp1_ra": ["semaglutide", "liraglutide", "dulaglutide", "exenatide"],
            "diuretic": ["furosemide", "hydrochlorothiazide", "chlorthalidone", "bumetanide", "torsemide"],
            "mra": ["spironolactone", "eplerenone"],
            "antidiabetic": ["metformin", "glipizide", "glyburide", "pioglitazone", "sitagliptin", "empagliflozin", "semaglutide"]
        }
    
    async def execute(self, patient: PatientProfile, **kwargs) -> Dict[str, Any]:
        """Execute guideline compliance analysis."""
        self._log_execution("checking_guidelines", {
            "conditions": [c.condition for c in patient.comorbidities]
        })
        
        findings = {
            "agent": self.agent_name,
            "compliant_therapies": [],
            "missing_therapies": [],
            "guideline_recommendations": [],
            "compliance_score": 1.0,
            "polypharmacy_check": None
        }
        
        # Get patient's medication classes
        patient_med_classes = await self._map_medications_to_classes(patient)
        
        # Check each condition against guidelines
        for comorbidity in patient.comorbidities:
            if not comorbidity.active:
                continue
            
            condition_findings = await self._check_condition_guidelines(
                patient, comorbidity.condition, patient_med_classes
            )
            
            findings["compliant_therapies"].extend(condition_findings.get("compliant", []))
            findings["missing_therapies"].extend(condition_findings.get("missing", []))
            findings["guideline_recommendations"].extend(condition_findings.get("recommendations", []))
        
        # Polypharmacy check
        findings["polypharmacy_check"] = await self._check_polypharmacy(patient)
        
        # Calculate compliance score
        total_conditions = len([c for c in patient.comorbidities if c.active])
        compliant_count = len(findings["compliant_therapies"])
        
        if total_conditions > 0:
            findings["compliance_score"] = min(1.0, compliant_count / max(total_conditions, 1))
        
        return findings
    
    async def _map_medications_to_classes(self, patient: PatientProfile) -> Dict[str, List[str]]:
        """Map patient's medications to therapeutic classes."""
        patient_classes = {}
        
        for med in patient.medications:
            if not med.active:
                continue
            
            med_lower = med.name.lower()
            for drug_class, drugs in self.drug_classes.items():
                if any(drug in med_lower for drug in drugs):
                    if drug_class not in patient_classes:
                        patient_classes[drug_class] = []
                    patient_classes[drug_class].append(med.name)
        
        return patient_classes
    
    async def _check_condition_guidelines(
        self, patient: PatientProfile, condition: str, patient_classes: Dict
    ) -> Dict:
        """Check if patient's regimen complies with guidelines for condition."""
        result = {"compliant": [], "missing": [], "recommendations": []}
        condition_lower = condition.lower()
        
        for guideline_condition, guideline in self.guidelines.items():
            if guideline_condition in condition_lower or condition_lower in guideline_condition:
                # Check for required therapy classes
                all_meds = guideline.get("first_line", []) + guideline.get("alternative", [])
                med_names_lower = [m.name.lower() for m in patient.medications if m.active]
                
                has_therapy = any(
                    any(drug in med for drug in all_meds)
                    for med in med_names_lower
                )
                
                if has_therapy:
                    result["compliant"].append({
                        "condition": condition,
                        "status": "compliant",
                        "source": guideline["source"]
                    })
                else:
                    result["missing"].append({
                        "condition": condition,
                        "recommended_drugs": guideline.get("first_line", [])[:3],
                        "source": guideline["source"],
                        "severity": "moderate"
                    })
                
                # Add key recommendations
                for rec in guideline.get("key_recommendations", [])[:2]:
                    result["recommendations"].append({
                        "condition": condition,
                        "recommendation": rec,
                        "source": guideline["source"]
                    })
                
                break  # Found matching guideline
        
        return result
    
    async def _check_polypharmacy(self, patient: PatientProfile) -> Dict:
        """Check for polypharmacy concerns."""
        active_count = len([m for m in patient.medications if m.active])
        
        if active_count >= 10:
            return {
                "status": "severe_polypharmacy",
                "count": active_count,
                "severity": "high",
                "recommendation": "Deprescribing review strongly recommended"
            }
        elif active_count >= 5:
            return {
                "status": "polypharmacy",
                "count": active_count,
                "severity": "moderate",
                "recommendation": "Consider medication review for optimization"
            }
        
        return {
            "status": "acceptable",
            "count": active_count,
            "severity": "low"
        }


class CostOptimizationAgent(BaseAgent):
    """
    Agent 4: Cost Optimization
    Mirrors src/agents/cost_optimization_agent.py
    
    Features:
    - Brand to generic substitution
    - Therapeutic alternatives (same class, lower cost)
    - Formulary optimization
    - Estimated cost calculations
    """
    
    def __init__(self, llm=None):
        super().__init__(llm, "CostOptimizationAgent")
        
        # Comprehensive brand to generic mappings with pricing
        self.generic_alternatives = {
            "lipitor": {"generic": "Atorvastatin", "brand_monthly": 300, "generic_monthly": 15, "savings": 285},
            "crestor": {"generic": "Rosuvastatin", "brand_monthly": 280, "generic_monthly": 20, "savings": 260},
            "zocor": {"generic": "Simvastatin", "brand_monthly": 200, "generic_monthly": 10, "savings": 190},
            "plavix": {"generic": "Clopidogrel", "brand_monthly": 230, "generic_monthly": 12, "savings": 218},
            "nexium": {"generic": "Esomeprazole", "brand_monthly": 250, "generic_monthly": 20, "savings": 230},
            "prilosec": {"generic": "Omeprazole", "brand_monthly": 180, "generic_monthly": 8, "savings": 172},
            "synthroid": {"generic": "Levothyroxine", "brand_monthly": 80, "generic_monthly": 10, "savings": 70},
            "glucophage": {"generic": "Metformin", "brand_monthly": 120, "generic_monthly": 8, "savings": 112},
            "zoloft": {"generic": "Sertraline", "brand_monthly": 200, "generic_monthly": 15, "savings": 185},
            "prozac": {"generic": "Fluoxetine", "brand_monthly": 180, "generic_monthly": 10, "savings": 170},
            "ambien": {"generic": "Zolpidem", "brand_monthly": 150, "generic_monthly": 15, "savings": 135},
            "norvasc": {"generic": "Amlodipine", "brand_monthly": 160, "generic_monthly": 12, "savings": 148},
            "prinivil": {"generic": "Lisinopril", "brand_monthly": 140, "generic_monthly": 8, "savings": 132},
            "zestril": {"generic": "Lisinopril", "brand_monthly": 140, "generic_monthly": 8, "savings": 132},
            "lopressor": {"generic": "Metoprolol Tartrate", "brand_monthly": 120, "generic_monthly": 10, "savings": 110},
            "toprol_xl": {"generic": "Metoprolol Succinate", "brand_monthly": 180, "generic_monthly": 25, "savings": 155},
            "lasix": {"generic": "Furosemide", "brand_monthly": 100, "generic_monthly": 8, "savings": 92},
            "coumadin": {"generic": "Warfarin", "brand_monthly": 90, "generic_monthly": 10, "savings": 80},
            "xanax": {"generic": "Alprazolam", "brand_monthly": 180, "generic_monthly": 15, "savings": 165},
            "valium": {"generic": "Diazepam", "brand_monthly": 150, "generic_monthly": 10, "savings": 140},
            "klonopin": {"generic": "Clonazepam", "brand_monthly": 170, "generic_monthly": 12, "savings": 158},
        }
        
        # Therapeutic class alternatives (equivalent efficacy, lower cost)
        self.therapeutic_alternatives = {
            # Statins (atorvastatin/rosuvastatin often preferred for efficacy/cost)
            "crestor": {
                "alternative": "Atorvastatin 40-80mg",
                "reason": "Similar LDL reduction, lower cost",
                "class": "statin"
            },
            "livalo": {
                "alternative": "Atorvastatin or Rosuvastatin",
                "reason": "Better studied, lower cost",
                "class": "statin"
            },
            # DOACs (consider warfarin in some contexts)
            "eliquis": {
                "alternative": "Warfarin (if monitoring feasible)",
                "reason": "Significantly lower cost, reversal agent available",
                "class": "anticoagulant",
                "caution": "Requires INR monitoring"
            },
            "xarelto": {
                "alternative": "Warfarin or Eliquis (if cost similar)",
                "reason": "Cost consideration, twice-daily Eliquis may be preferable",
                "class": "anticoagulant"
            },
            # PPIs (omeprazole typically first-line)
            "protonix": {
                "alternative": "Omeprazole",
                "reason": "Equivalent efficacy, significantly lower cost",
                "class": "ppi"
            },
            "dexilant": {
                "alternative": "Omeprazole or Esomeprazole",
                "reason": "Equivalent for most indications, much lower cost",
                "class": "ppi"
            },
            # Antihypertensives
            "benicar": {
                "alternative": "Losartan",
                "reason": "Similar efficacy, lower cost, better studied",
                "class": "arb"
            },
            # Sleep aids
            "lunesta": {
                "alternative": "Zolpidem or sleep hygiene",
                "reason": "Lower cost, similar efficacy",
                "class": "sleep_aid"
            },
        }
        
        # Insurance formulary tiers (simplified)
        self.formulary_info = {
            "medicare": {
                "preferred_generics": ["metformin", "lisinopril", "amlodipine", "atorvastatin", "omeprazole"],
                "high_cost_brands": ["eliquis", "jardiance", "ozempic", "humira"]
            },
            "commercial": {
                "preferred_generics": ["atorvastatin", "metoprolol", "lisinopril", "sertraline"],
                "step_therapy_required": ["ozempic", "trulicity", "humira"]
            }
        }
    
    async def execute(self, patient: PatientProfile, **kwargs) -> Dict[str, Any]:
        """Execute cost optimization analysis."""
        self._log_execution("analyzing_costs", {"med_count": patient.medication_count})
        
        findings = {
            "agent": self.agent_name,
            "generic_opportunities": [],
            "therapeutic_alternatives": [],
            "formulary_recommendations": [],
            "potential_monthly_savings": 0.0,
            "potential_annual_savings": 0.0
        }
        
        # 1. Check for generic alternatives
        findings["generic_opportunities"] = await self._check_generic_availability(patient)
        
        # 2. Check for therapeutic alternatives
        findings["therapeutic_alternatives"] = await self._find_therapeutic_alternatives(patient)
        
        # 3. Calculate total savings
        generic_savings = sum(opp["monthly_savings"] for opp in findings["generic_opportunities"])
        findings["potential_monthly_savings"] = generic_savings
        findings["potential_annual_savings"] = generic_savings * 12
        
        return findings
    
    async def _check_generic_availability(self, patient: PatientProfile) -> List[Dict]:
        """Check for available generic substitutions."""
        opportunities = []
        
        for med in patient.medications:
            if not med.active:
                continue
            
            med_lower = med.name.lower().replace(" ", "_").replace("-", "_")
            
            for brand, info in self.generic_alternatives.items():
                if brand in med_lower or med_lower in brand:
                    opportunities.append({
                        "current_medication": med.name,
                        "generic_alternative": info["generic"],
                        "brand_monthly_cost": info["brand_monthly"],
                        "generic_monthly_cost": info["generic_monthly"],
                        "monthly_savings": info["savings"],
                        "annual_savings": info["savings"] * 12,
                        "recommendation": f"Switch to {info['generic']} to save ${info['savings']}/month"
                    })
        
        return opportunities
    
    async def _find_therapeutic_alternatives(self, patient: PatientProfile) -> List[Dict]:
        """Find cost-effective therapeutic alternatives."""
        alternatives = []
        
        for med in patient.medications:
            if not med.active:
                continue
            
            med_lower = med.name.lower()
            
            for brand, info in self.therapeutic_alternatives.items():
                if brand in med_lower:
                    alternatives.append({
                        "current_medication": med.name,
                        "alternative": info["alternative"],
                        "reason": info["reason"],
                        "therapeutic_class": info["class"],
                        "caution": info.get("caution", None)
                    })
        
        return alternatives


class ExplanationAgent(BaseAgent):
    """
    Agent 5: Clinical Summary and Explanation Generation
    Mirrors src/agents/explanation_agent.py
    
    Features:
    - Executive summary for clinicians
    - Patient-friendly explanations (adjustable reading level)
    - Prioritized recommendations
    - Safety score calculation
    - Actionable next steps
    """
    
    def __init__(self, llm=None):
        super().__init__(llm, "ExplanationAgent")
    
    async def execute(self, patient: PatientProfile, **kwargs) -> Dict[str, Any]:
        """Generate comprehensive explanation from all agent findings."""
        interaction_findings = kwargs.get("interaction_findings", {})
        personalization_findings = kwargs.get("personalization_findings", {})
        guideline_findings = kwargs.get("guideline_findings", {})
        cost_findings = kwargs.get("cost_findings", {})
        
        return await self.generate(
            patient,
            interaction_findings,
            personalization_findings,
            guideline_findings,
            cost_findings
        )
    
    async def generate(
        self,
        patient: PatientProfile,
        interaction_findings: Dict,
        personalization_findings: Dict,
        guideline_findings: Dict,
        cost_findings: Dict
    ) -> Dict[str, Any]:
        """Synthesize all agent findings into actionable recommendations."""
        self._log_execution("generating_summary", {"patient_id": patient.patient_id})
        
        # Collect and prioritize recommendations
        recommendations = []
        
        # Priority 1: Critical drug interactions
        for interaction in interaction_findings.get("critical_interactions", []):
            recommendations.append({
                "priority": 1,
                "category": "CRITICAL DRUG INTERACTION",
                "title": f"{interaction['drug1']} + {interaction['drug2']}",
                "severity": "critical",
                "description": interaction["clinical_effect"],
                "action": interaction["management"],
                "evidence": interaction.get("evidence_level", "definitive"),
                "literature": interaction.get("literature_refs", [])
            })
        
        # Priority 1: Critical renal contraindications
        for adj in personalization_findings.get("renal_adjustments", []):
            if adj.get("severity") == "critical":
                recommendations.append({
                    "priority": 1,
                    "category": "RENAL CONTRAINDICATION",
                    "title": f"{adj['medication']} - eGFR {adj['egfr']}",
                    "severity": "critical",
                    "description": f"eGFR {adj['egfr']} below threshold {adj['threshold']}",
                    "action": adj["recommendation"]
                })
        
        # Priority 1: Pharmacogenomic alerts
        for pgx in personalization_findings.get("pharmacogenomics", []):
            if "AVOID" in pgx.get("recommendation", "").upper():
                recommendations.append({
                    "priority": 1,
                    "category": "PHARMACOGENOMIC ALERT",
                    "title": f"{pgx['medication']} - {pgx['gene']} {pgx['phenotype']}",
                    "severity": "critical",
                    "description": f"Patient is {pgx['phenotype']} for {pgx['gene']}",
                    "action": pgx["recommendation"]
                })
        
        # Priority 2: Major (non-critical) interactions
        for interaction in interaction_findings.get("interactions", []):
            if interaction["severity"] == "major":
                # Check if already in critical
                is_critical = any(
                    rec["title"] == f"{interaction['drug1']} + {interaction['drug2']}"
                    for rec in recommendations if rec["priority"] == 1
                )
                if not is_critical:
                    recommendations.append({
                        "priority": 2,
                        "category": "Major Drug Interaction",
                        "title": f"{interaction['drug1']} + {interaction['drug2']}",
                        "severity": "high",
                        "description": interaction["clinical_effect"],
                        "action": interaction["management"]
                    })
        
        # Priority 2: Beers Criteria medications (elderly)
        for concern in personalization_findings.get("age_concerns", []):
            if concern.get("severity") == "high" and "medication" in concern:
                recommendations.append({
                    "priority": 2,
                    "category": "Beers Criteria",
                    "title": f"{concern['medication']} - Inappropriate in Elderly",
                    "severity": "high",
                    "description": concern.get("reason", "Potentially inappropriate"),
                    "action": f"Consider: {concern.get('alternative', 'safer alternative')}"
                })
        
        # Priority 2: High renal adjustments (non-critical)
        for adj in personalization_findings.get("renal_adjustments", []):
            if adj.get("severity") == "high":
                recommendations.append({
                    "priority": 2,
                    "category": "Renal Dose Adjustment",
                    "title": f"{adj['medication']} - Dose Adjustment Needed",
                    "severity": "high",
                    "description": f"eGFR {adj['egfr']} requires adjustment",
                    "action": adj["recommendation"]
                })
        
        # Priority 2: Missing guideline-recommended therapies
        for missing in guideline_findings.get("missing_therapies", []):
            recommendations.append({
                "priority": 2,
                "category": "Guideline Gap",
                "title": f"Consider therapy for {missing['condition']}",
                "severity": "moderate",
                "description": f"Recommended: {', '.join(missing.get('recommended_drugs', [])[:3])}",
                "action": f"Per {missing.get('source', 'clinical guidelines')}"
            })
        
        # Priority 2: Severe polypharmacy
        polypharm = personalization_findings.get("polypharmacy_alert")
        if polypharm and polypharm.get("level") == "severe":
            recommendations.append({
                "priority": 2,
                "category": "Polypharmacy Alert",
                "title": f"{polypharm['medication_count']} Active Medications",
                "severity": "high",
                "description": "Significantly increased risk of adverse events",
                "action": polypharm["recommendation"]
            })
        
        # Priority 3: Moderate interactions
        for interaction in interaction_findings.get("interactions", []):
            if interaction["severity"] == "moderate":
                recommendations.append({
                    "priority": 3,
                    "category": "Moderate Interaction",
                    "title": f"{interaction['drug1']} + {interaction['drug2']}",
                    "severity": "moderate",
                    "description": interaction["clinical_effect"],
                    "action": interaction["management"]
                })
        
        # Priority 3: Cost optimization opportunities
        for opp in cost_findings.get("generic_opportunities", []):
            recommendations.append({
                "priority": 3,
                "category": "Cost Savings Opportunity",
                "title": f"Switch to {opp['generic_alternative']}",
                "severity": "low",
                "description": f"Save ${opp['monthly_savings']}/month (${opp['annual_savings']}/year)",
                "action": f"Consider generic substitution for {opp['current_medication']}"
            })
        
        # Sort by priority
        recommendations.sort(key=lambda x: (x["priority"], -1 if x["severity"] == "critical" else 0))
        
        # Calculate safety score
        critical_count = len([r for r in recommendations if r["priority"] == 1])
        high_count = len([r for r in recommendations if r["priority"] == 2 and r["severity"] == "high"])
        moderate_count = len([r for r in recommendations if r["priority"] == 2 and r["severity"] == "moderate"])
        
        safety_score = 100 - (critical_count * 25) - (high_count * 10) - (moderate_count * 3)
        safety_score = max(0, min(100, safety_score))
        
        # Determine if human review required
        requires_human_review = (
            critical_count > 0 or
            high_count >= 2 or
            any(adj.get("severity") == "critical" for adj in personalization_findings.get("renal_adjustments", []))
        )
        
        # Generate executive summary
        executive_summary = await self._generate_executive_summary(
            patient, recommendations, safety_score, requires_human_review
        )
        
        # Generate patient-friendly summary
        patient_summary = await self._generate_patient_summary(
            patient, recommendations, safety_score
        )
        
        return {
            "agent": self.agent_name,
            "recommendations": recommendations,
            "safety_score": safety_score,
            "requires_human_review": requires_human_review,
            "executive_summary": executive_summary,
            "patient_summary": patient_summary,
            "summary_stats": {
                "total_recommendations": len(recommendations),
                "critical_items": critical_count,
                "high_priority_items": high_count,
                "moderate_items": moderate_count,
                "cost_savings": cost_findings.get("potential_monthly_savings", 0)
            }
        }
    
    async def _generate_executive_summary(
        self, patient: PatientProfile, recommendations: List[Dict], 
        safety_score: int, requires_human_review: bool
    ) -> str:
        """Generate executive summary for clinicians."""
        critical_recs = [r for r in recommendations if r["priority"] == 1]
        high_recs = [r for r in recommendations if r["priority"] == 2]
        
        summary_parts = [
            f"**Patient:** {patient.name} ({patient.age}y {patient.sex})",
            f"**Medications:** {patient.medication_count} active",
            f"**Safety Score:** {safety_score}/100"
        ]
        
        if requires_human_review:
            summary_parts.append("\n**⚠️ REQUIRES CLINICAL REVIEW**")
        
        if critical_recs:
            summary_parts.append(f"\n**Critical Issues ({len(critical_recs)}):**")
            for rec in critical_recs[:3]:
                summary_parts.append(f"  β€’ {rec['title']}: {rec['action'][:50]}...")
        
        if high_recs:
            summary_parts.append(f"\n**High Priority ({len(high_recs)}):**")
            for rec in high_recs[:3]:
                summary_parts.append(f"  β€’ {rec['title']}")
        
        return "\n".join(summary_parts)
    
    async def _generate_patient_summary(
        self, patient: PatientProfile, recommendations: List[Dict], safety_score: int
    ) -> str:
        """Generate patient-friendly summary."""
        if safety_score >= 80:
            status = "Your medications have been reviewed and appear to be safe for you."
        elif safety_score >= 60:
            status = "Some concerns were found that your doctor should review with you."
        else:
            status = "Important concerns were found. Please discuss with your healthcare provider soon."
        
        critical_count = len([r for r in recommendations if r["priority"] == 1])
        
        summary = f"{status}\n\n"
        
        if critical_count > 0:
            summary += f"**{critical_count} important issue(s)** need your doctor's attention.\n"
        
        summary += "\nYour care team will discuss any needed changes with you."
        
        return summary


# =============================================================================
# ORCHESTRATOR (from src/orchestration/coordinator_enhanced.py)
# =============================================================================

class MedicationSafetyOrchestrator:
    """
    LangGraph-Style Medication Safety Coordinator
    Mirrors src/orchestration/coordinator_enhanced.py
    
    Features:
    - StateGraph-style workflow with conditional routing
    - Severity-based routing (critical -> human_review, parallel_analysis, low_risk)
    - 5 specialized agent nodes
    - Execution tracing and audit logging
    - Consensus building across agents
    
    Production uses LangGraph StateGraph with:
    - add_node() for each agent
    - add_conditional_edges() for routing based on severity
    - Parallel execution for independent agents
    """
    
    def __init__(self):
        # Initialize all agents (mirrors production agent initialization)
        self.drug_agent = DrugInteractionAgentEnhanced()
        self.personalization_agent = PersonalizationAgent()
        self.guideline_agent = GuidelineComplianceAgent()
        self.cost_agent = CostOptimizationAgent()
        self.explanation_agent = ExplanationAgent()
        
        # Workflow state
        self.execution_trace = []
    
    async def analyze(self, patient: PatientProfile) -> Dict[str, Any]:
        """
        Run full multi-agent analysis pipeline with conditional routing.
        
        Mirrors LangGraph workflow:
        1. START -> interaction_check
        2. interaction_check -> conditional_route
        3. conditional_route -> 
           - "critical" -> human_review_node
           - "parallel_analysis" -> [personalization, guideline, cost] in parallel
           - "low_risk" -> standard_analysis
        4. All paths -> explanation
        5. explanation -> END
        """
        
        results = {
            "patient_id": patient.patient_id,
            "patient_name": patient.name,
            "timestamp": datetime.now().isoformat(),
            "agents_run": [],
            "execution_path": [],
            "workflow_type": "langgraph_conditional_routing"
        }
        
        # ===================================================================
        # Node 1: Drug Interaction Analysis (Entry Point)
        # ===================================================================
        results["execution_path"].append("START -> interaction_check")
        interaction_results = await self.drug_agent.execute_with_error_handling(patient)
        results["drug_interactions"] = interaction_results
        results["agents_run"].append("DrugInteractionAgentEnhanced")
        
        # ===================================================================
        # Conditional Routing Based on Severity
        # ===================================================================
        route = self._route_after_interaction_check(interaction_results)
        results["execution_path"].append(f"interaction_check -> {route}")
        results["routing_decision"] = route
        
        # ===================================================================
        # Node 2: Personalization (runs in all paths)
        # ===================================================================
        results["execution_path"].append("PersonalizationAgent")
        personalization_results = await self.personalization_agent.execute_with_error_handling(patient)
        results["personalization"] = personalization_results
        results["agents_run"].append("PersonalizationAgent")
        
        # ===================================================================
        # Node 3: Guideline Compliance (conditional - if comorbidities exist)
        # ===================================================================
        if patient.comorbidities and route != "low_risk":
            results["execution_path"].append("GuidelineComplianceAgent")
            guideline_results = await self.guideline_agent.execute_with_error_handling(patient)
            results["guidelines"] = guideline_results
            results["agents_run"].append("GuidelineComplianceAgent")
        else:
            guideline_results = {
                "compliant_therapies": [], 
                "missing_therapies": [], 
                "compliance_score": 1.0,
                "skipped": route == "low_risk" or not patient.comorbidities
            }
            results["guidelines"] = guideline_results
            results["execution_path"].append("GuidelineComplianceAgent (skipped - " + 
                ("low_risk" if route == "low_risk" else "no comorbidities") + ")")
        
        # ===================================================================
        # Node 4: Cost Optimization (runs in parallel_analysis and standard paths)
        # ===================================================================
        if route != "critical":  # Cost not priority in critical path
            results["execution_path"].append("CostOptimizationAgent")
            cost_results = await self.cost_agent.execute_with_error_handling(patient)
            results["cost_optimization"] = cost_results
            results["agents_run"].append("CostOptimizationAgent")
        else:
            cost_results = {
                "generic_opportunities": [],
                "therapeutic_alternatives": [],
                "potential_monthly_savings": 0,
                "skipped": "critical_path"
            }
            results["cost_optimization"] = cost_results
            results["execution_path"].append("CostOptimizationAgent (skipped - critical path)")
        
        # ===================================================================
        # Special Node: Human Review Flag (for critical findings)
        # ===================================================================
        if route == "critical":
            results["execution_path"].append("human_review_node (FLAGGED)")
            results["human_review_required"] = True
            results["human_review_reasons"] = self._get_critical_reasons(
                interaction_results, personalization_results
            )
        else:
            results["human_review_required"] = False
        
        # ===================================================================
        # Node 5: Explanation Agent (Final Synthesis)
        # ===================================================================
        if route == "critical":
            results["execution_path"].append("ExplanationAgent (DETAILED - Critical findings)")
        else:
            results["execution_path"].append("ExplanationAgent (Standard)")
        
        explanation_results = await self.explanation_agent.generate(
            patient,
            interaction_results,
            personalization_results,
            guideline_results,
            cost_results
        )
        results["explanation"] = explanation_results
        results["agents_run"].append("ExplanationAgent")
        
        results["execution_path"].append("END")
        
        # ===================================================================
        # Build Consensus
        # ===================================================================
        results["consensus"] = self._build_consensus(
            interaction_results,
            personalization_results,
            guideline_results,
            explanation_results
        )
        
        return results
    
    def _route_after_interaction_check(self, interaction_results: Dict) -> str:
        """
        Conditional routing logic (mirrors LangGraph conditional_edges).
        
        Returns:
            "critical" - Route to human review, skip cost optimization
            "parallel_analysis" - Run personalization, guideline, cost in parallel
            "low_risk" - Streamlined analysis path
        """
        critical_count = interaction_results.get("critical_count", 0)
        total_interactions = interaction_results.get("total_found", 0)
        
        # Check for contraindicated combinations
        has_contraindicated = any(
            i.get("severity") == "contraindicated" 
            for i in interaction_results.get("interactions", [])
        )
        
        if has_contraindicated or critical_count >= 2:
            return "critical"
        elif critical_count >= 1 or total_interactions >= 3:
            return "parallel_analysis"
        else:
            return "low_risk"
    
    def _get_critical_reasons(
        self, interaction_results: Dict, personalization_results: Dict
    ) -> List[str]:
        """Get reasons for critical routing."""
        reasons = []
        
        for interaction in interaction_results.get("critical_interactions", []):
            reasons.append(
                f"Critical interaction: {interaction['drug1']} + {interaction['drug2']}"
            )
        
        for adj in personalization_results.get("renal_adjustments", []):
            if adj.get("severity") == "critical":
                reasons.append(
                    f"Renal contraindication: {adj['medication']} with eGFR {adj['egfr']}"
                )
        
        return reasons
    
    def _build_consensus(
        self, interaction: Dict, personalization: Dict, guideline: Dict, explanation: Dict
    ) -> Dict:
        """Build consensus across all agent findings."""
        return {
            "safety_score": explanation.get("safety_score", 0),
            "requires_human_review": explanation.get("requires_human_review", False),
            "total_concerns": explanation.get("summary_stats", {}).get("total_recommendations", 0),
            "critical_concerns": explanation.get("summary_stats", {}).get("critical_items", 0),
            "high_priority_concerns": explanation.get("summary_stats", {}).get("high_priority_items", 0),
            "guideline_compliance": guideline.get("compliance_score", 1.0) if not guideline.get("skipped") else "N/A",
            "cost_savings_available": explanation.get("summary_stats", {}).get("cost_savings", 0),
            "agent_agreement": self._calculate_agent_agreement(interaction, personalization, guideline)
        }
    
    def _calculate_agent_agreement(
        self, interaction: Dict, personalization: Dict, guideline: Dict
    ) -> float:
        """Calculate how much agents agree on risk level."""
        # Simple heuristic: if multiple agents flag issues, agreement is high
        flags = 0
        if interaction.get("critical_count", 0) > 0:
            flags += 1
        if personalization.get("risk_score", 0) > 0.3:
            flags += 1
        if guideline.get("compliance_score", 1) < 0.8:
            flags += 1
        
        # Agreement is high if either all flag or none flag
        if flags == 0 or flags == 3:
            return 0.95
        elif flags == 1:
            return 0.75
        else:
            return 0.85


# =============================================================================
# DEMO DATA (simulating src/repositories/ - Enhanced with full production data)
# =============================================================================

DEMO_PATIENTS = {
    "P001": PatientProfile(
        patient_id="P001",
        name="John Smith",
        age=67,
        sex="male",
        weight_kg=82,
        height_cm=175,
        egfr=58,  # Mild-moderate CKD
        liver_function="normal",
        medications=[
            Medication("Warfarin", "11289", "5mg", "daily", drug_class="anticoagulant"),
            Medication("Metformin", "6809", "1000mg", "twice daily", drug_class="antidiabetic"),
            Medication("Lisinopril", "29046", "20mg", "daily", drug_class="ace_inhibitor"),
            Medication("Aspirin", "1191", "81mg", "daily", drug_class="antiplatelet"),
        ],
        comorbidities=[
            Comorbidity("Hypertension", "I10"),
            Comorbidity("Type 2 Diabetes", "E11.9"),
            Comorbidity("Atrial Fibrillation", "I48.91"),
        ],
        allergies=[
            Allergy("Penicillin", "severe", "anaphylaxis"),
            Allergy("Sulfa drugs", "moderate", "rash"),
        ],
        genetic_markers=[
            GeneticMarker("CYP2C9", "*1/*3", "intermediate_metabolizer", 
                         ["Warfarin: May require lower doses"]),
        ],
        lab_results=[
            LabResult("INR", 2.8, "ratio", "2.0-3.0"),
            LabResult("Serum Creatinine", 1.4, "mg/dL", "0.7-1.3", is_abnormal=True),
            LabResult("HbA1c", 7.2, "%", "<7.0%", is_abnormal=True),
        ]
    ),
    "P002": PatientProfile(
        patient_id="P002",
        name="Maria Garcia",
        age=45,
        sex="female",
        weight_kg=68,
        height_cm=163,
        egfr=95,
        liver_function="normal",
        medications=[
            Medication("Sertraline", "36437", "100mg", "daily", drug_class="ssri"),
            Medication("Tramadol", "10689", "50mg", "as needed", drug_class="opioid"),
            Medication("Zolpidem", "39993", "10mg", "at bedtime", drug_class="hypnotic"),
        ],
        comorbidities=[
            Comorbidity("Major Depressive Disorder", "F33.1"),
            Comorbidity("Chronic Pain Syndrome", "G89.29"),
            Comorbidity("Insomnia", "G47.00"),
        ],
        allergies=[],
        genetic_markers=[
            GeneticMarker("CYP2D6", "*1/*4", "intermediate_metabolizer",
                         ["Tramadol: Reduced efficacy possible"]),
        ],
        lab_results=[]
    ),
    "P003": PatientProfile(
        patient_id="P003",
        name="Robert Chen",
        age=72,
        sex="male",
        weight_kg=75,
        height_cm=170,
        egfr=38,  # Stage 3b CKD
        liver_function="mild_impairment",
        medications=[
            Medication("Furosemide", "4603", "40mg", "daily", drug_class="diuretic"),
            Medication("Carvedilol", "20352", "25mg", "twice daily", drug_class="beta_blocker"),
            Medication("Potassium Chloride", "6252", "20mEq", "daily", drug_class="electrolyte"),
            Medication("Lisinopril", "29046", "10mg", "daily", drug_class="ace_inhibitor"),
            Medication("Albuterol", "435", "2 puffs", "as needed", drug_class="bronchodilator"),
            Medication("Metoprolol", "6918", "25mg", "twice daily", drug_class="beta_blocker"),
            Medication("Digoxin", "3407", "0.125mg", "daily", drug_class="cardiac_glycoside"),
            Medication("Spironolactone", "9997", "25mg", "daily", drug_class="mra"),
        ],
        comorbidities=[
            Comorbidity("Heart Failure", "I50.9"),
            Comorbidity("COPD", "J44.9"),
            Comorbidity("Chronic Kidney Disease Stage 3b", "N18.4"),
            Comorbidity("Atrial Fibrillation", "I48.91"),
        ],
        allergies=[
            Allergy("Iodine contrast", "severe", "anaphylactoid reaction"),
        ],
        genetic_markers=[],
        lab_results=[
            LabResult("Potassium", 5.2, "mEq/L", "3.5-5.0", is_abnormal=True),
            LabResult("Digoxin Level", 1.8, "ng/mL", "0.8-2.0"),
            LabResult("BNP", 450, "pg/mL", "<100", is_abnormal=True),
        ]
    ),
    "P004": PatientProfile(
        patient_id="P004",
        name="Sarah Johnson",
        age=55,
        sex="female",
        weight_kg=90,
        height_cm=165,
        egfr=72,
        liver_function="normal",
        medications=[
            Medication("Simvastatin", "36567", "40mg", "daily", drug_class="statin"),
            Medication("Amlodipine", "17767", "10mg", "daily", drug_class="ccb"),
            Medication("Metoprolol", "6918", "50mg", "twice daily", drug_class="beta_blocker"),
            Medication("Omeprazole", "7646", "20mg", "daily", drug_class="ppi"),
        ],
        comorbidities=[
            Comorbidity("Hypertension", "I10"),
            Comorbidity("Hyperlipidemia", "E78.5"),
            Comorbidity("GERD", "K21.0"),
        ],
        allergies=[],
        genetic_markers=[],
        lab_results=[
            LabResult("LDL Cholesterol", 95, "mg/dL", "<100"),
            LabResult("Total Cholesterol", 185, "mg/dL", "<200"),
        ]
    ),
    "P005": PatientProfile(
        patient_id="P005",
        name="James Wilson",
        age=78,
        sex="male",
        weight_kg=70,
        height_cm=168,
        egfr=45,  # Stage 3a CKD
        liver_function="normal",
        medications=[
            Medication("Codeine/Acetaminophen", "2670", "30/300mg", "every 6 hours", drug_class="opioid"),
            Medication("Diazepam", "3322", "5mg", "at bedtime", drug_class="benzodiazepine"),
            Medication("Diphenhydramine", "3498", "25mg", "at bedtime", drug_class="antihistamine"),
            Medication("Gabapentin", "25480", "600mg", "three times daily", drug_class="anticonvulsant"),
            Medication("Oxybutynin", "7628", "5mg", "twice daily", drug_class="anticholinergic"),
            Medication("Amitriptyline", "704", "25mg", "at bedtime", drug_class="tca"),
        ],
        comorbidities=[
            Comorbidity("Chronic Pain", "G89.29"),
            Comorbidity("Insomnia", "G47.00"),
            Comorbidity("Overactive Bladder", "N32.81"),
            Comorbidity("Peripheral Neuropathy", "G62.9"),
        ],
        allergies=[],
        genetic_markers=[
            GeneticMarker("CYP2D6", "*4/*4", "poor_metabolizer",
                         ["Codeine: AVOID - no efficacy", "Tramadol: AVOID"]),
        ],
        lab_results=[]
    ),
}


# =============================================================================
# GRADIO UI
# =============================================================================

orchestrator = MedicationSafetyOrchestrator()

def format_results(results: Dict[str, Any]) -> str:
    """Format analysis results as markdown."""
    output = []
    
    # Header
    output.append(f"# πŸ₯ MedGuard Analysis Report\n")
    output.append(f"**Patient:** {results['patient_name']} (ID: {results['patient_id']})")
    output.append(f"**Generated:** {results['timestamp'][:19]}")
    output.append(f"**Workflow:** {results.get('workflow_type', 'langgraph_conditional_routing')}\n")
    
    # Consensus Summary
    consensus = results["consensus"]
    safety_score = consensus["safety_score"]
    
    if safety_score >= 80:
        score_emoji = "βœ…"
        score_label = "LOW RISK"
    elif safety_score >= 60:
        score_emoji = "⚠️"
        score_label = "MODERATE RISK"
    elif safety_score >= 40:
        score_emoji = "πŸ”Ά"
        score_label = "HIGH RISK"
    else:
        score_emoji = "πŸ”΄"
        score_label = "CRITICAL RISK"
    
    output.append(f"## {score_emoji} Safety Score: {safety_score}/100 ({score_label})\n")
    
    if consensus.get("requires_human_review") or results.get("human_review_required"):
        output.append("> ⚠️ **REQUIRES IMMEDIATE CLINICAL REVIEW**\n")
        if results.get("human_review_reasons"):
            output.append("**Reasons:**")
            for reason in results["human_review_reasons"]:
                output.append(f"  - {reason}")
            output.append("")
    
    # Agent Execution Path (LangGraph style) - Text format for compatibility
    output.append("### πŸ”„ LangGraph Execution Path\n")
    output.append("```")
    for i, step in enumerate(results["execution_path"]):
        prefix = "  " * (1 if "->" in step or "β†’" in step else 0)
        # Clean step for display
        clean_step = step.replace("β†’", "->")
        if i == 0:
            output.append(f"[1] {clean_step}")
        else:
            output.append(f"[{i+1}] {clean_step}")
    output.append("```")
    output.append(f"\n**Routing Decision:** `{results.get('routing_decision', 'parallel_analysis')}`\n")
    
    # Executive Summary (from ExplanationAgent)
    if results.get("explanation", {}).get("executive_summary"):
        output.append("---\n## πŸ“‹ Executive Summary\n")
        output.append(results["explanation"]["executive_summary"])
        output.append("")
    
    # Recommendations
    recommendations = results.get("explanation", {}).get("recommendations", [])
    if recommendations:
        output.append("---\n## 🎯 Prioritized Recommendations\n")
        
        for rec in recommendations:
            priority_emoji = {"critical": "πŸ”΄", "high": "🟠", "moderate": "🟑", "low": "🟒"}.get(rec.get("severity"), "ℹ️")
            priority_label = {1: "CRITICAL", 2: "HIGH", 3: "MODERATE"}.get(rec["priority"], "INFO")
            
            output.append(f"### {priority_emoji} {rec['category']}: {rec['title']}")
            output.append(f"**Priority:** {priority_label} | **Severity:** {rec.get('severity', 'unknown').upper()}")
            output.append(f"**Issue:** {rec['description']}")
            output.append(f"**Action:** {rec['action']}")
            if rec.get("literature"):
                output.append(f"**Evidence:** {', '.join(rec['literature'])}")
            output.append("")
    
    # Drug Interactions Detail
    interactions = results.get("drug_interactions", {}).get("interactions", [])
    if interactions:
        output.append("---\n## πŸ’Š Drug Interaction Details\n")
        for interaction in interactions:
            severity_emoji = {"contraindicated": "β›”", "major": "πŸ”΄", "moderate": "🟠", "minor": "🟑"}.get(interaction.get("severity"), "")
            output.append(f"### {severity_emoji} {interaction['drug1']} + {interaction['drug2']}")
            output.append(f"- **Severity:** {interaction.get('severity', 'unknown').upper()}")
            output.append(f"- **Evidence Level:** {interaction.get('evidence_level', 'unknown')}")
            output.append(f"- **Mechanism:** {interaction.get('mechanism', 'N/A')}")
            output.append(f"- **Clinical Effect:** {interaction.get('clinical_effect', 'N/A')}")
            output.append(f"- **Management:** {interaction.get('management', 'N/A')}")
            if interaction.get("source") == "metabolic_analysis":
                output.append(f"- **Source:** CYP Enzyme Analysis")
            output.append("")
    
    # Personalization Findings
    personalization = results.get("personalization", {})
    has_personalization = (
        personalization.get("renal_adjustments") or 
        personalization.get("age_concerns") or
        personalization.get("pharmacogenomics") or
        personalization.get("polypharmacy_alert")
    )
    
    if has_personalization:
        output.append("---\n## πŸ‘€ Patient-Specific Factors\n")
        
        # Renal adjustments
        for adj in personalization.get("renal_adjustments", []):
            severity_emoji = "πŸ”΄" if adj.get("severity") == "critical" else "🟠"
            output.append(f"### {severity_emoji} Renal Adjustment: {adj['medication']}")
            output.append(f"- **Patient eGFR:** {adj['egfr']} mL/min/1.73mΒ²")
            output.append(f"- **Threshold:** {adj['threshold']} mL/min/1.73mΒ²")
            output.append(f"- **Action:** {adj['recommendation']}\n")
        
        # Pharmacogenomics
        for pgx in personalization.get("pharmacogenomics", []):
            output.append(f"### 🧬 Pharmacogenomic Alert: {pgx['medication']}")
            output.append(f"- **Gene:** {pgx['gene']} ({pgx['variant']})")
            output.append(f"- **Phenotype:** {pgx['phenotype']}")
            output.append(f"- **Effect:** {pgx.get('effect', 'variable')}")
            output.append(f"- **Recommendation:** {pgx['recommendation']}\n")
        
        # Age concerns (Beers Criteria)
        for concern in personalization.get("age_concerns", []):
            if concern.get("medication"):
                output.append(f"### πŸ‘΄ Beers Criteria: {concern['medication']}")
                output.append(f"- **Concern:** {concern.get('concern', 'Potentially inappropriate')}")
                output.append(f"- **Reason:** {concern.get('reason', 'N/A')}")
                output.append(f"- **Alternative:** {concern.get('alternative', 'See guidelines')}\n")
            elif concern.get("recommendations"):
                output.append(f"### πŸ‘΄ {concern.get('concern', 'Age-Related Considerations')}")
                for rec in concern.get("recommendations", []):
                    output.append(f"- {rec}")
                output.append("")
        
        # Polypharmacy
        polypharm = personalization.get("polypharmacy_alert")
        if polypharm and polypharm.get("level") != "acceptable":
            output.append(f"### πŸ’Š Polypharmacy Alert")
            output.append(f"- **Medication Count:** {polypharm['medication_count']}")
            output.append(f"- **Level:** {polypharm['level'].title()}")
            output.append(f"- **Recommendation:** {polypharm['recommendation']}")
            if polypharm.get("risks"):
                output.append("- **Risks:**")
                for risk in polypharm["risks"][:3]:
                    output.append(f"  - {risk}")
            output.append("")
    
    # Guideline Compliance
    guidelines = results.get("guidelines", {})
    if not guidelines.get("skipped"):
        output.append("---\n## πŸ“š Guideline Compliance\n")
        
        compliance_score = guidelines.get("compliance_score", 1.0)
        output.append(f"**Compliance Score:** {compliance_score:.0%}\n")
        
        for therapy in guidelines.get("compliant_therapies", []):
            output.append(f"βœ… **{therapy['condition']}** - Compliant per {therapy.get('source', 'guidelines')}")
        
        for missing in guidelines.get("missing_therapies", []):
            output.append(f"⚠️ **{missing['condition']}** - Consider adding guideline-recommended therapy")
            output.append(f"   Recommended: {', '.join(missing.get('recommended_drugs', []))}")
            output.append(f"   Source: {missing.get('source', 'Clinical guidelines')}")
        
        for rec in guidelines.get("guideline_recommendations", [])[:2]:
            output.append(f"\nπŸ’‘ **{rec['condition']}:** {rec['recommendation']}")
        
        output.append("")
    
    # Cost Optimization
    cost = results.get("cost_optimization", {})
    if cost.get("potential_monthly_savings", 0) > 0 or cost.get("generic_opportunities"):
        output.append("---\n## πŸ’° Cost Optimization Opportunities\n")
        
        if cost.get("potential_monthly_savings", 0) > 0:
            output.append(f"**Potential Monthly Savings:** ${cost['potential_monthly_savings']:.2f}")
            output.append(f"**Potential Annual Savings:** ${cost.get('potential_annual_savings', 0):.2f}\n")
        
        for opp in cost.get("generic_opportunities", []):
            output.append(f"πŸ’Š **{opp['current_medication']}** β†’ **{opp['generic_alternative']}**")
            output.append(f"   Save ${opp['monthly_savings']}/month (${opp.get('annual_savings', 0)}/year)")
        
        for alt in cost.get("therapeutic_alternatives", [])[:2]:
            output.append(f"\nπŸ”„ **Therapeutic Alternative:** {alt['current_medication']}")
            output.append(f"   Consider: {alt['alternative']}")
            output.append(f"   Reason: {alt['reason']}")
        
        output.append("")
    
    # Consensus Summary
    output.append("---\n## πŸ“Š Consensus Summary\n")
    output.append(f"| Metric | Value |")
    output.append(f"|--------|-------|")
    output.append(f"| Safety Score | {consensus['safety_score']}/100 |")
    output.append(f"| Human Review Required | {'Yes ⚠️' if consensus.get('requires_human_review') else 'No βœ“'} |")
    output.append(f"| Critical Concerns | {consensus.get('critical_concerns', 0)} |")
    output.append(f"| High Priority Concerns | {consensus.get('high_priority_concerns', 0)} |")
    output.append(f"| Total Recommendations | {consensus.get('total_concerns', 0)} |")
    if consensus.get('guideline_compliance') != 'N/A':
        output.append(f"| Guideline Compliance | {consensus.get('guideline_compliance', 1.0):.0%} |")
    output.append(f"| Agent Agreement | {consensus.get('agent_agreement', 0.85):.0%} |")
    output.append(f"| Cost Savings Available | ${consensus.get('cost_savings_available', 0):.0f}/month |")
    
    # Footer
    output.append("\n---")
    output.append("*Generated by MedGuard Multi-Agent System*")
    output.append("*MCP 1st Birthday Hackathon Submission*")
    output.append(f"*Agents: {len(results.get('agents_run', []))} | Workflow: LangGraph Conditional Routing*")
    
    return "\n".join(output)


async def analyze_patient(patient_id: str) -> str:
    """Run analysis on selected patient."""
    patient = DEMO_PATIENTS.get(patient_id)
    if not patient:
        return "Patient not found"
    
    results = await orchestrator.analyze(patient)
    return format_results(results)


def run_analysis(patient_id: str) -> str:
    """Synchronous wrapper for Gradio."""
    import asyncio
    return asyncio.run(analyze_patient(patient_id))


async def call_mcp_tool(tool_name: str, patient_id: str, extra_params: str) -> str:
    """Call an MCP tool and format the response."""
    import json
    
    # Build arguments based on tool
    args = {"patient_id": patient_id}
    
    # Parse extra params if provided
    if extra_params.strip():
        try:
            extra = json.loads(extra_params)
            args.update(extra)
        except json.JSONDecodeError:
            # Treat as simple query string
            args["query"] = extra_params
    
    # Add tool-specific defaults
    if tool_name == "check_drug_interactions":
        patient = DEMO_PATIENTS.get(patient_id)
        if patient:
            args["medications"] = [{"name": m.name} for m in patient.medications]
    
    if tool_name == "optimize_medication_costs":
        patient = DEMO_PATIENTS.get(patient_id)
        if patient:
            args["current_medications"] = [m.name for m in patient.medications]
    
    if tool_name == "search_pubmed_literature":
        args["query"] = extra_params or "warfarin aspirin bleeding"
    
    if tool_name == "search_fda_safety_alerts":
        args["drug_name"] = extra_params or "warfarin"
    
    if tool_name == "search_clinical_guidelines":
        args["query"] = extra_params or "atrial fibrillation anticoagulation"
    
    # Call the tool
    result = await mcp_tools.call_tool(tool_name, args)
    
    # Format output as markdown
    output = [f"# πŸ”§ MCP Tool: `{tool_name}`\n"]
    output.append(f"**Patient:** {patient_id}")
    output.append(f"**Timestamp:** {datetime.now().isoformat()[:19]}\n")
    output.append("## Request")
    output.append("```json")
    output.append(json.dumps(args, indent=2, default=str))
    output.append("```\n")
    output.append("## Response")
    output.append("```json")
    output.append(json.dumps(result, indent=2, default=str))
    output.append("```\n")
    
    if result.get("success"):
        output.append("βœ… **Tool executed successfully**")
    else:
        output.append(f"❌ **Error:** {result.get('error', 'Unknown error')}")
    
    return "\n".join(output)


def run_mcp_tool(tool_name: str, patient_id: str, extra_params: str) -> str:
    """Synchronous wrapper for MCP tool calls."""
    import asyncio
    return asyncio.run(call_mcp_tool(tool_name, patient_id, extra_params))


def get_mcp_tools_list() -> str:
    """Return formatted list of MCP tools."""
    tools = mcp_tools.list_tools()
    
    output = ["# πŸ”§ MCP Server Tools\n"]
    output.append("These tools are exposed via the MCP protocol for Claude Desktop and other MCP clients.\n")
    output.append("| # | Tool Name | Description |")
    output.append("|---|-----------|-------------|")
    
    for i, tool in enumerate(tools, 1):
        output.append(f"| {i} | `{tool['name']}` | {tool['description'][:60]}... |")
    
    output.append("\n---\n")
    output.append("### MCP Protocol Details\n")
    output.append("- **Transport:** stdio (for Claude Desktop) or SSE (for web clients)")
    output.append("- **SDK:** Python `mcp` package")
    output.append("- **Resources:** 3 (guidelines, drug database, safety alerts)")
    output.append("- **Server Name:** `healthcare-multi-agent-system`")
    
    return "\n".join(output)


# Build Gradio Interface
with gr.Blocks(title="MedGuard - AI Medication Safety") as app:
    
    gr.Markdown("""
    # πŸ₯ MedGuard
    ## AI-Powered Medication Safety Analysis
    
    **Multi-Agent System for Drug Interaction Detection and Clinical Decision Support**
    
    *MCP 1st Birthday Hackathon Submission - Track 1: Building MCP*
    """)
    
    with gr.Tabs():
        # =====================================================================
        # TAB 1: MULTI-AGENT ANALYSIS
        # =====================================================================
        with gr.TabItem("πŸ”¬ Multi-Agent Analysis", id="analysis"):
            gr.Markdown("""
            This demo showcases a **production-ready** healthcare AI system with:
            - **5 Specialized AI Agents** coordinated via LangGraph-style orchestration
            - **Conditional routing** based on severity (critical β†’ human review path)
            - **Evidence-based drug interaction detection** (25+ known interactions)
            - **Pharmacogenomics analysis** (CYP2D6, CYP2C9, CYP2C19, CYP3A4)
            """)
            
            with gr.Row():
                with gr.Column(scale=1):
                    gr.Markdown("### Select Patient")
                    
                    patient_dropdown = gr.Dropdown(
                        choices=[
                            ("P001 - John Smith (67y, AFib/DM/HTN, CKD Stage 3, CYP2C9 variant)", "P001"),
                            ("P002 - Maria Garcia (45y, Depression/Pain/Insomnia, Serotonin risk)", "P002"),
                            ("P003 - Robert Chen (72y, HF/COPD/CKD 3b, 8 meds, hyperkalemia)", "P003"),
                            ("P004 - Sarah Johnson (55y, HTN/HLD/GERD, Statin interaction)", "P004"),
                            ("P005 - James Wilson (78y, Polypharmacy, Beers Criteria, CYP2D6 PM)", "P005"),
                        ],
                        label="Patient",
                        value="P001"
                    )
                    
                    analyze_btn = gr.Button("πŸ”¬ Run Multi-Agent Analysis", variant="primary", size="lg")
                    
                    gr.Markdown("""
                    ### πŸ€– Agent Architecture
                    
                    | Agent | Role |
                    |-------|------|
                    | **DrugInteractionAgent** | DDI detection, CYP conflicts, ML prediction |
                    | **PersonalizationAgent** | Renal/hepatic, pharmacogenomics, Beers |
                    | **GuidelineAgent** | Clinical guideline compliance |
                    | **CostAgent** | Generic substitution, formulary |
                    | **ExplanationAgent** | Synthesis and prioritization |
                    
                    ### πŸ”„ LangGraph Orchestration
                    
                    ```
                    START β†’ interaction_check β†’ [route]
                      β”œβ”€ "critical" β†’ human_review β†’ explanation
                      β”œβ”€ "parallel" β†’ [personalization, guideline, cost] β†’ explanation
                      └─ "low_risk" β†’ streamlined_analysis β†’ explanation
                    β†’ END
                    ```
                    """)
                    
                with gr.Column(scale=2):
                    analysis_output = gr.Markdown(
                        value="""
## πŸ‘‹ Welcome to MedGuard

Select a patient and click **Run Multi-Agent Analysis** to begin.

### Demo Patients

Each patient demonstrates different aspects of the system:

| Patient | Key Features |
|---------|--------------|
| **P001 - John Smith** | Warfarin + Aspirin (major DDI), CKD, CYP2C9 variant |
| **P002 - Maria Garcia** | Sertraline + Tramadol (serotonin syndrome risk) |
| **P003 - Robert Chen** | 8 medications, hyperkalemia risk, HF + COPD |
| **P004 - Sarah Johnson** | Simvastatin + Amlodipine (CYP3A4 interaction) |
| **P005 - James Wilson** | 6 Beers Criteria meds, CYP2D6 poor metabolizer |

---

### What the System Analyzes

1. **Drug-Drug Interactions** - Known interactions + CYP metabolic conflicts
2. **Patient Factors** - Renal function, age, pharmacogenomics
3. **Guideline Compliance** - AHA/ACC, ADA, ESC evidence-based standards
4. **Cost Optimization** - Generic alternatives and formulary savings
5. **Prioritized Recommendations** - Critical β†’ High β†’ Moderate severity
                        """,
                        label="Analysis Results"
                    )
            
            # Event handler for analysis tab
            analyze_btn.click(
                fn=run_analysis,
                inputs=[patient_dropdown],
                outputs=[analysis_output]
            )
        
        # =====================================================================
        # TAB 2: MCP TOOLS DEMO
        # =====================================================================
        with gr.TabItem("πŸ”§ MCP Tools Demo", id="mcp_tools"):
            gr.Markdown("""
            ## MCP Server Tools
            
            This tab demonstrates the **10 MCP tools** exposed by the healthcare server.
            These tools are callable via the Model Context Protocol by Claude Desktop and other MCP clients.
            
            **MCP Server Features:**
            - **Transport:** stdio (Claude Desktop) or SSE (web clients)
            - **SDK:** Python `mcp` package
            - **Resources:** 3 (clinical guidelines, drug database, FDA alerts)
            """)
            
            with gr.Row():
                with gr.Column(scale=1):
                    mcp_tools_list_btn = gr.Button("πŸ“‹ List All MCP Tools", variant="secondary")
                    
                    gr.Markdown("### Call Individual Tool")
                    
                    tool_dropdown = gr.Dropdown(
                        choices=[
                            ("analyze_medication_safety", "analyze_medication_safety"),
                            ("check_drug_interactions", "check_drug_interactions"),
                            ("get_personalized_dosing", "get_personalized_dosing"),
                            ("check_guideline_compliance", "check_guideline_compliance"),
                            ("optimize_medication_costs", "optimize_medication_costs"),
                            ("get_patient_profile", "get_patient_profile"),
                            ("search_clinical_guidelines", "search_clinical_guidelines"),
                            ("explain_medication_decision", "explain_medication_decision"),
                            ("search_pubmed_literature", "search_pubmed_literature"),
                            ("search_fda_safety_alerts", "search_fda_safety_alerts"),
                        ],
                        label="Select MCP Tool",
                        value="check_drug_interactions"
                    )
                    
                    tool_patient_dropdown = gr.Dropdown(
                        choices=[
                            ("P001 - John Smith", "P001"),
                            ("P002 - Maria Garcia", "P002"),
                            ("P003 - Robert Chen", "P003"),
                            ("P004 - Sarah Johnson", "P004"),
                            ("P005 - James Wilson", "P005"),
                        ],
                        label="Patient Context",
                        value="P001"
                    )
                    
                    extra_params = gr.Textbox(
                        label="Extra Parameters (optional)",
                        placeholder="JSON or query string (e.g., 'warfarin bleeding' for PubMed)",
                        lines=2
                    )
                    
                    call_tool_btn = gr.Button("πŸš€ Call MCP Tool", variant="primary")
                    
                    gr.Markdown("""
                    ### Tool Descriptions
                    
                    | Tool | Purpose |
                    |------|---------|
                    | `analyze_medication_safety` | Full 5-agent pipeline |
                    | `check_drug_interactions` | DDI detection only |
                    | `get_personalized_dosing` | Patient-specific adjustments |
                    | `check_guideline_compliance` | Evidence-based compliance |
                    | `optimize_medication_costs` | Generic alternatives |
                    | `get_patient_profile` | Demographics & history |
                    | `search_clinical_guidelines` | BioBERT vector search |
                    | `explain_medication_decision` | Patient-friendly explanation |
                    | `search_pubmed_literature` | **MCP Search integration** |
                    | `search_fda_safety_alerts` | **MCP Search integration** |
                    """)
                
                with gr.Column(scale=2):
                    mcp_output = gr.Markdown(
                        value="""
## πŸ”§ MCP Tools Demo

This tab allows you to **call individual MCP tools** to see how they work.

### How MCP Integration Works

1. **Claude Desktop** connects to the MCP server via stdio
2. **Tools are discoverable** via the `tools/list` protocol method
3. **Claude can call tools** using `tools/call` with JSON arguments
4. **Responses are structured** for easy parsing by LLMs

### Example Claude Desktop Interaction

```
User: Check drug interactions for patient P001

Claude: I'll use the check_drug_interactions MCP tool.
[Calls tool with patient_id="P001"]

Result: Found 2 interactions:
- Warfarin + Aspirin: Major bleeding risk
- Warfarin + CYP2C9 variant: Dose adjustment needed
```

### Try It!

1. Select a tool from the dropdown
2. Choose a patient context  
3. Click **Call MCP Tool** to see the raw response
                        """,
                        label="MCP Tool Output"
                    )
            
            # Event handlers for MCP tools tab
            mcp_tools_list_btn.click(
                fn=get_mcp_tools_list,
                inputs=[],
                outputs=[mcp_output]
            )
            
            call_tool_btn.click(
                fn=run_mcp_tool,
                inputs=[tool_dropdown, tool_patient_dropdown, extra_params],
                outputs=[mcp_output]
            )
        
        # =====================================================================
        # TAB 3: ARCHITECTURE
        # =====================================================================
        with gr.TabItem("πŸ—οΈ Architecture", id="architecture"):
            gr.Markdown("""
            ## Production Architecture
            
            ### πŸ—οΈ Technology Stack
            
            | Component | Technology |
            |-----------|------------|
            | **MCP Server** | Python `mcp` SDK with stdio transport, 10 tools + 3 resources |
            | **Orchestration** | LangGraph StateGraph with conditional severity routing |
            | **LLM** | Google Gemini 1.5 Flash (primary) / Claude (fallback) |
            | **Knowledge Graph** | Neo4j for drug interaction network |
            | **Vector Search** | Qdrant + BioBERT embeddings |
            | **API** | FastAPI with HIPAA-compliant audit logging |
            | **Frontend** | Gradio (demo) + React Admin (production) |
            | **Databases** | PostgreSQL + Redis for session management |
            
            ---
            
            ### πŸ”„ LangGraph Workflow
            
            ```
            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
            β”‚                    MedicationSafetyOrchestrator                β”‚
            β”‚                                                                β”‚
            β”‚   START                                                        β”‚
            β”‚     β”‚                                                          β”‚
            β”‚     β–Ό                                                          β”‚
            β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                                  β”‚
            β”‚   β”‚ DrugInteractionAgent    │◄── Entry point                   β”‚
            β”‚   β”‚ (CYP analysis, DDI, ML) β”‚                                  β”‚
            β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                                  β”‚
            β”‚               β”‚                                                β”‚
            β”‚               β–Ό                                                β”‚
            β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                                  β”‚
            β”‚   β”‚   CONDITIONAL ROUTER    β”‚                                  β”‚
            β”‚   β”‚   Based on severity     β”‚                                  β”‚
            β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                                  β”‚
            β”‚               β”‚                                                β”‚
            β”‚    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                                     β”‚
            β”‚    β”‚          β”‚          β”‚                                     β”‚
            β”‚    β–Ό          β–Ό          β–Ό                                     β”‚
            β”‚ "critical" "parallel" "low_risk"                               β”‚
            β”‚    β”‚          β”‚          β”‚                                     β”‚
            β”‚    β–Ό          β”‚          β”‚                                     β”‚
            β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚          β”‚                                     β”‚
            β”‚ β”‚ Human  β”‚    β”‚          β”‚                                     β”‚
            β”‚ β”‚ Review β”‚    β”‚          β”‚                                     β”‚
            β”‚ β”‚ Flag   β”‚    β”‚          β”‚                                     β”‚
            β”‚ β””β”€β”€β”€β”¬β”€β”€β”€β”€β”˜    β”‚          β”‚                                     β”‚
            β”‚     β”‚    β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”     β”‚                                     β”‚
            β”‚     β”‚    β”‚ Run in  β”‚     β”‚                                     β”‚
            β”‚     β”‚    β”‚ Parallelβ”‚     β”‚                                     β”‚
            β”‚     β”‚    β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜     β”‚                                     β”‚
            β”‚     β”‚         β”‚          β”‚                                     β”‚
            β”‚     β–Ό         β–Ό          β–Ό                                     β”‚
            β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                                  β”‚
            β”‚   β”‚ PersonalizationAgent    β”‚                                  β”‚
            β”‚   β”‚ GuidelineComplianceAgentβ”‚                                  β”‚
            β”‚   β”‚ CostOptimizationAgent   β”‚                                  β”‚
            β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                                  β”‚
            β”‚               β”‚                                                β”‚
            β”‚               β–Ό                                                β”‚
            β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                                  β”‚
            β”‚   β”‚   ExplanationAgent      │◄── Final synthesis               β”‚
            β”‚   β”‚   (Prioritized recs)    β”‚                                  β”‚
            β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                                  β”‚
            β”‚               β”‚                                                β”‚
            β”‚               β–Ό                                                β”‚
            β”‚             END                                                β”‚
            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
            ```
            
            ---
            
            ### 🎯 MCP Server Tools
            
            | # | Tool Name | Description |
            |---|-----------|-------------|
            | 1 | `analyze_medication_safety` | Full multi-agent analysis pipeline |
            | 2 | `check_drug_interactions` | Drug-drug interaction detection |
            | 3 | `get_personalized_dosing` | Patient-specific dose adjustments |
            | 4 | `check_guideline_compliance` | Clinical guideline compliance check |
            | 5 | `optimize_medication_costs` | Cost optimization with generics |
            | 6 | `get_patient_profile` | Patient demographics and history |
            | 7 | `search_clinical_guidelines` | Vector search clinical guidelines |
            | 8 | `explain_medication_decision` | Patient-friendly explanation |
            | 9 | `search_pubmed_literature` | PubMed literature search (MCP Search) |
            | 10 | `search_fda_safety_alerts` | FDA safety alert search (MCP Search) |
            
            ---
            
            ### πŸ“ MCP Resources
            
            | Resource URI | Description |
            |--------------|-------------|
            | `guidelines://clinical-practice` | Clinical practice guidelines database |
            | `database://drug-interactions` | Drug interaction knowledge base |
            | `alerts://fda-safety` | FDA safety communications |
            
            ---
            
            ### 🎯 Hackathon Tracks
            
            - **Track 1 (Building MCP):** βœ… Production-ready MCP server with 10 tools + 3 resources
            - **Track 2 (Consumer Use):** βœ… Claude Desktop integration working
            
            **GitHub:** [mcp1stbirthday_hack](https://github.com/SmartGridsML/mcp1stbirthday_hack)
            """)
    
    gr.Markdown("""
    ---
    *Generated by MedGuard Multi-Agent System | MCP 1st Birthday Hackathon Submission*
    """)

# Launch
if __name__ == "__main__":
    app.launch()