File size: 45,919 Bytes
b124f9d
 
 
 
 
 
acb0f46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39e909d
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
# Patch for Python 3.13: audioop removed; stub it so pydub/gradio can import
import sys, types
for _m in ("audioop", "pyaudioop"):
    if _m not in sys.modules:
        sys.modules[_m] = types.ModuleType(_m)

import gradio as gr
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, FancyBboxPatch, Patch
from datetime import datetime, timedelta
import zipfile
import os
import io
import tempfile
import shutil

# ─── Try importing rarfile ───────────────────────────────────────────────────
try:
    import rarfile
    HAS_RARFILE = True
except ImportError:
    HAS_RARFILE = False

# ─── Colour palette ──────────────────────────────────────────────────────────
COLOR_TREATMENT    = '#1f4788'
COLOR_OFF_TREATMENT = '#808080'
RESPONSE_COLORS    = {'CR': '#00CC00', 'PR': '#5a9bd4', 'SD': '#f0c929', 'PD': '#c41e3a'}
WATERFALL_COLORS   = {'CR': '#1f4788', 'PR': '#5a9bd4', 'SD': '#f0c929', 'PD': '#c41e3a'}


# ════════════════════════════════════════════════════════════════════════════
#  FILE HANDLING
# ════════════════════════════════════════════════════════════════════════════

def extract_archive(path: str, dest_dir: str) -> list[str]:
    """Extract zip/rar; return list of extracted file paths."""
    extracted = []
    ext = os.path.splitext(path)[1].lower()

    if ext == '.zip':
        with zipfile.ZipFile(path, 'r') as zf:
            zf.extractall(dest_dir)
            extracted = [os.path.join(dest_dir, n) for n in zf.namelist()]

    elif ext == '.rar':
        if HAS_RARFILE:
            with rarfile.RarFile(path, 'r') as rf:
                rf.extractall(dest_dir)
                extracted = [os.path.join(dest_dir, n) for n in rf.namelist()]
        else:
            # Convert: rename to zip and try β€” works only for unencrypted RAR2
            zip_path = path.replace('.rar', '_converted.zip')
            shutil.copy(path, zip_path)
            try:
                with zipfile.ZipFile(zip_path, 'r') as zf:
                    zf.extractall(dest_dir)
                    extracted = [os.path.join(dest_dir, n) for n in zf.namelist()]
            except Exception:
                raise ValueError(
                    "RAR extraction failed. Please install the 'rarfile' package "
                    "or convert the archive to ZIP before uploading."
                )

    return extracted


def resolve_excel_file(upload_path: str) -> str:
    """
    Given an uploaded file path, return path to the Excel file to process.
    Handles: .xlsx, .xls, .csv, .zip, .rar
    """
    tmp_dir = tempfile.mkdtemp()
    ext = os.path.splitext(upload_path)[1].lower()

    if ext in ('.xlsx', '.xls'):
        return upload_path

    if ext == '.csv':
        # Wrap CSV into a dict so downstream code still works
        return upload_path          # handled separately in load_sheets

    if ext in ('.zip', '.rar'):
        files = extract_archive(upload_path, tmp_dir)
        for f in files:
            if os.path.splitext(f)[1].lower() in ('.xlsx', '.xls'):
                return f
        raise ValueError("No Excel file found inside the archive.")

    raise ValueError(f"Unsupported file format: {ext}")


def load_sheets(excel_path: str, cohort_number: int) -> dict:
    """Load all required sheets from the Excel file."""
    SHEET_NAMES = ['DM', 'EX1', 'EX2', 'EX3', 'EX4', 'EX5',
                   'ET', 'EOS', 'RS', 'ACCM', 'MH', 'BLTUT', 'BLTUNT', 'TUT']
    sheets = {}
    for sheet in SHEET_NAMES:
        try:
            df = pd.read_excel(excel_path, sheet_name=sheet)
            sheets[sheet] = df
        except Exception:
            sheets[sheet] = pd.DataFrame()

    # Clean duplicate header rows
    for sheet_name in sheets:
        df = sheets[sheet_name]
        if 'Subject Id' in df.columns:
            sheets[sheet_name] = df[df['Subject Id'] != 'SubjectId'].reset_index(drop=True)

    # Filter to specified cohort
    if 'Cohort - Code' in sheets['DM'].columns:
        sheets['DM']['Cohort - Code'] = pd.to_numeric(sheets['DM']['Cohort - Code'], errors='coerce')
        sheets['DM'] = sheets['DM'][sheets['DM']['Cohort - Code'] == cohort_number].reset_index(drop=True)

    return sheets


# ════════════════════════════════════════════════════════════════════════════
#  HELPER FUNCTIONS
# ════════════════════════════════════════════════════════════════════════════

def parse_date_safe(date_val):
    if pd.isna(date_val) or str(date_val).upper() in ['', 'UNK', 'UNKNOWN']:
        return pd.NaT
    if isinstance(date_val, (datetime, pd.Timestamp)):
        return pd.to_datetime(date_val)
    try:
        return pd.to_datetime(str(date_val))
    except Exception:
        return pd.NaT


def calculate_months(start_date, end_date):
    if pd.isna(start_date) or pd.isna(end_date):
        return 0
    return ((end_date - start_date).days + 1) / 30.4


def get_trtsdt(subject_id, sheets):
    all_dates = []
    for ex in ['EX1', 'EX2', 'EX3', 'EX4', 'EX5']:
        df = sheets.get(ex, pd.DataFrame())
        if df.empty:
            continue
        pt = df[df['Subject Id'] == subject_id].copy()
        if pt.empty:
            continue
        perf_col = next((c for c in pt.columns if 'PERF' in c.upper() or c.lower() in ['performed', 'done']), None)
        if perf_col:
            pt = pt[pt[perf_col].astype(str).str.lower() == 'yes']
        if pt.empty:
            continue
        for date_col in ['Start date', 'STDAT', 'Date', 'Event date']:
            if date_col in pt.columns:
                d = parse_date_safe(pt[date_col].iloc[0])
                if not pd.isna(d):
                    all_dates.append(d)
                break
    return min(all_dates) if all_dates else pd.NaT


def get_trtedt(subject_id, sheets):
    all_dates = []
    for ex in ['EX1', 'EX2', 'EX3', 'EX4', 'EX5']:
        df = sheets.get(ex, pd.DataFrame())
        if df.empty:
            continue
        pt = df[df['Subject Id'] == subject_id].copy()
        if pt.empty:
            continue
        perf_col = next((c for c in pt.columns if 'PERF' in c.upper() or c.lower() in ['performed', 'done']), None)
        if perf_col:
            pt = pt[pt[perf_col].astype(str).str.lower() == 'yes']
        if pt.empty:
            continue
        for date_col in ['Start date', 'STDAT', 'Date', 'Event date']:
            if date_col in pt.columns:
                for val in pt[date_col]:
                    d = parse_date_safe(val)
                    if not pd.isna(d):
                        all_dates.append(d)
                break
    return max(all_dates) if all_dates else pd.NaT


# ════════════════════════════════════════════════════════════════════════════
#  PATIENT PROCESSING
# ════════════════════════════════════════════════════════════════════════════

def process_patients(sheets: dict) -> list:
    swimmer_data = []

    for _, dm_row in sheets['DM'].iterrows():
        subject_id = dm_row['Subject Id']
        if pd.isna(subject_id):
            continue

        start_date = get_trtsdt(subject_id, sheets)

        if pd.isna(start_date):
            pt_ex3 = sheets['EX3'][sheets['EX3']['Subject Id'] == subject_id]
            for col in ['Date', 'Start date', 'Event date']:
                if col in pt_ex3.columns and len(pt_ex3) > 0:
                    start_date = parse_date_safe(pt_ex3[col].iloc[0])
                    if not pd.isna(start_date):
                        break

        if pd.isna(start_date):
            pt_bltut = sheets['BLTUT'][sheets['BLTUT']['Subject Id'] == subject_id]
            baseline_sum = np.nan
            if len(pt_bltut) > 0 and 'Sum of diameters' in pt_bltut.columns:
                baseline_sum = pd.to_numeric(pt_bltut['Sum of diameters'].iloc[0], errors='coerce')
            swimmer_data.append({
                'patient_id': subject_id, 'treatment_months': 0, 'responses': [],
                'best_response': 'NE', 'still_on_treatment': False, 'endpoint_type': 'none',
                'category': 'Replaced', 'liver_mets': False, 'off_treatment_end': None,
                'baseline_sum': baseline_sum, 'baseline_date': pd.NaT,
                'nadir': np.nan, 'best_pct_change': np.nan,
                'trtsdt': pd.NaT, 'trtedt': pd.NaT
            })
            continue

        end_date = get_trtedt(subject_id, sheets)

        still_on_treatment = True
        endpoint_type = 'none'

        pt_et = sheets['ET'][sheets['ET']['Subject Id'] == subject_id]
        date_col_et   = 'Date of last treatment'
        reason_col_et = 'Primary reason for treatment discontinuation'

        if len(pt_et) > 0:
            if date_col_et in pt_et.columns:
                et_date_val = pt_et.iloc[0][date_col_et]
                if not pd.isna(et_date_val) and str(et_date_val).strip() not in ['', 'nan', 'NaT']:
                    still_on_treatment = False
            if reason_col_et in pt_et.columns:
                reason_val = str(pt_et.iloc[0][reason_col_et]).strip()
                if reason_val not in ['', 'nan', 'NaT']:
                    endpoint_type = reason_val
                    still_on_treatment = False

        if pd.isna(end_date):
            pt_eos = sheets['EOS'][sheets['EOS']['Subject Id'] == subject_id]
            if len(pt_eos) > 0 and 'Date of study discontinuation' in pt_eos.columns:
                end_date = parse_date_safe(pt_eos['Date of study discontinuation'].iloc[0])
        if pd.isna(end_date):
            end_date = start_date + timedelta(days=30)

        treatment_months = calculate_months(start_date, end_date)

        responses = []
        pt_rs = sheets['RS'][sheets['RS']['Subject Id'] == subject_id]
        ovrldat_col  = next((c for c in pt_rs.columns if 'OVRLDAT' in c.upper() or c == 'Overall response date'), None)
        ovrlresp_col = next((c for c in pt_rs.columns if 'OVRLRESP' in c.upper() or c == 'Overall response'), None)

        for _, row in pt_rs.iterrows():
            resp_date = parse_date_safe(row.get(ovrldat_col, pd.NaT)) if ovrldat_col else pd.NaT
            if pd.isna(resp_date):
                continue
            months = calculate_months(start_date, resp_date)
            resp_abbrev = None
            if ovrlresp_col:
                resp_val = str(row.get(ovrlresp_col, '')).upper().strip()
                if 'COMPLETE' in resp_val or resp_val == 'CR':
                    resp_abbrev = 'CR'
                elif 'PARTIAL' in resp_val or resp_val == 'PR':
                    resp_abbrev = 'PR'
                elif 'STABLE' in resp_val or resp_val == 'SD':
                    resp_abbrev = 'SD'
                elif 'PROGRESSIVE' in resp_val or resp_val == 'PD':
                    resp_abbrev = 'PD'
                else:
                    code = str(row.get('Overall response - Code', ''))
                    resp_abbrev = {'1': 'CR', '2': 'PR', '3': 'SD', '4': 'PD'}.get(code, None)
            if resp_abbrev:
                responses.append({'months': months, 'response': resp_abbrev, 'date': resp_date})

        # Liver mets
        liver_mets = False
        liver_keywords = ['liver', 'hepatic']
        liver_exclusions = ['lymph', 'lym ', 'ln ', ' ln', 'hilus', 'hilum', 'periportal',
                            'paraaort', 'interaort', 'coeliac', 'celiac', 'hilar', 'portal vein']

        for df_name in ['BLTUT', 'BLTUNT']:
            pt_df = sheets[df_name][sheets[df_name]['Subject Id'] == subject_id]
            if pt_df.empty:
                continue
            loc_cols = [c for c in pt_df.columns
                        if c == 'Location' or (c.startswith('Location.') and c[9:].isdigit())]
            for _, row in pt_df.iterrows():
                for col in loc_cols:
                    val = str(row.get(col, '')).lower()
                    if any(kw in val for kw in liver_keywords):
                        if not any(excl in val for excl in liver_exclusions):
                            liver_mets = True
                            break
                if liver_mets:
                    break

        # Baseline tumor
        pt_bltut = sheets['BLTUT'][sheets['BLTUT']['Subject Id'] == subject_id]
        baseline_sum = nadir = best_pct_change = np.nan
        baseline_date = pd.NaT

        if len(pt_bltut) > 0 and 'Sum of diameters' in pt_bltut.columns:
            baseline_sum = pd.to_numeric(pt_bltut['Sum of diameters'].iloc[0], errors='coerce')
            for c in pt_bltut.columns:
                if 'date of assessment' in c.lower():
                    baseline_date = parse_date_safe(pt_bltut[c].iloc[0])
                    if not pd.isna(baseline_date):
                        break
            if not pd.isna(baseline_sum) and baseline_sum > 0:
                pt_tut = sheets['TUT'][sheets['TUT']['Subject Id'] == subject_id]
                if len(pt_tut) > 0 and 'Sum of diameters' in pt_tut.columns:
                    sums = pd.to_numeric(pt_tut['Sum of diameters'], errors='coerce').dropna()
                    if len(sums) > 0:
                        nadir = sums.min()
                        best_pct_change = ((nadir - baseline_sum) / baseline_sum) * 100

        best_response = 'NE'
        if responses:
            rank = {'CR': 1, 'PR': 2, 'SD': 3, 'PD': 4}
            best_response = min(responses, key=lambda x: rank.get(x['response'], 999))['response']

        has_baseline   = not pd.isna(baseline_sum) and baseline_sum > 0
        has_treatment  = not pd.isna(start_date)
        has_assessment = len(responses) >= 1
        category = 'Evaluable' if (has_baseline and has_treatment and has_assessment) else 'Replaced'

        off_treatment_end = None
        if not still_on_treatment and responses:
            last_resp = max(responses, key=lambda x: x['date'])
            last_months = calculate_months(start_date, last_resp['date'])
            if last_months > treatment_months:
                off_treatment_end = last_months + 1

        swimmer_data.append({
            'patient_id':         subject_id,
            'treatment_months':   treatment_months,
            'responses':          responses,
            'best_response':      best_response,
            'still_on_treatment': still_on_treatment,
            'endpoint_type':      endpoint_type,
            'category':           category,
            'liver_mets':         liver_mets,
            'off_treatment_end':  off_treatment_end,
            'baseline_sum':       baseline_sum,
            'baseline_date':      baseline_date,
            'nadir':              nadir,
            'best_pct_change':    best_pct_change,
            'trtsdt':             start_date,
            'trtedt':             end_date,
        })

    return swimmer_data


def build_dataframes(swimmer_data: list):
    response_counts = []
    for patient in swimmer_data:
        for resp in patient['responses']:
            response_counts.append({
                'patient_id':        patient['patient_id'],
                'months_from_start': resp['months'],
                'response':          resp['response'],
            })

    response_df = pd.DataFrame(response_counts)
    if len(response_df) > 0:
        assessment_counts = response_df.groupby('patient_id').size().reset_index(name='n_assessments')
    else:
        assessment_counts = pd.DataFrame(columns=['patient_id', 'n_assessments'])

    swimmer_df = pd.DataFrame(swimmer_data)
    swimmer_df = swimmer_df.merge(assessment_counts, on='patient_id', how='left')
    swimmer_df['n_assessments'] = swimmer_df['n_assessments'].fillna(0).astype(int)
    swimmer_df = swimmer_df.sort_values(['n_assessments', 'patient_id'],
                                        ascending=[False, True]).reset_index(drop=True)

    # Special reorder: 16-006 after 18-006
    idx_16 = swimmer_df[swimmer_df['patient_id'].astype(str).str.contains('16-006', na=False)].index
    idx_18 = swimmer_df[swimmer_df['patient_id'].astype(str).str.contains('18-006', na=False)].index
    if len(idx_16) > 0 and len(idx_18) > 0 and idx_16[0] < idx_18[0]:
        row = swimmer_df.loc[idx_16[0]].copy()
        swimmer_df = swimmer_df.drop(idx_16[0]).reset_index(drop=True)
        new_idx = swimmer_df[swimmer_df['patient_id'].astype(str).str.contains('18-006', na=False)].index[0]
        swimmer_df = pd.concat([swimmer_df.iloc[:new_idx+1],
                                 pd.DataFrame([row]),
                                 swimmer_df.iloc[new_idx+1:]]).reset_index(drop=True)

    swimmer_df['y_pos'] = range(len(swimmer_df)-1, -1, -1)
    return swimmer_df, response_df


# ════════════════════════════════════════════════════════════════════════════
#  PLOT FUNCTIONS
# ════════════════════════════════════════════════════════════════════════════

def create_swimmer_plot(swimmer_df, response_df, study_title, cohort_number):
    evaluable_count = (swimmer_df['category'] == 'Evaluable').sum()
    replaced_count  = (swimmer_df['category'] == 'Replaced').sum()

    max_months = swimmer_df['treatment_months'].max()
    if swimmer_df['off_treatment_end'].notna().any():
        max_months = max(max_months, swimmer_df['off_treatment_end'].max())
    max_months += 2

    fig, ax = plt.subplots(figsize=(16, max(10, len(swimmer_df) * 0.38)))
    fig.patch.set_facecolor('#f8f9fb')
    ax.set_facecolor('#f8f9fb')

    ax.set_xlim(-5, max_months)
    ax.set_ylim(-0.5, len(swimmer_df) - 0.5)
    ax.set_xlabel('Months', fontsize=12, fontweight='bold', color='#1a1a2e')
    ax.set_title(
        f'Swimmer Plot β€” {study_title} Cohort {cohort_number}\nAll Patients  |  PDAC',
        fontsize=14, fontweight='bold', color='#1a1a2e', pad=20
    )
    ax.set_xticks(range(0, int(np.ceil(max_months)) + 1, 3))
    ax.set_yticks(swimmer_df['y_pos'])
    y_colors = ['#1a1a2e' if cat == 'Evaluable' else '#c41e3a' for cat in swimmer_df['category']]
    ax.set_yticklabels(swimmer_df['patient_id'], fontsize=7, fontweight='bold')
    for tick_label, color in zip(ax.get_yticklabels(), y_colors):
        tick_label.set_color(color)
    ax.grid(axis='x', color='#aab4be', linestyle='--', linewidth=0.5, alpha=0.4)

    for _, row in swimmer_df.iterrows():
        y = row['y_pos']
        ax.add_patch(Rectangle((0, y - 0.28), row['treatment_months'], 0.56,
                                facecolor=COLOR_TREATMENT, edgecolor='none'))
        if pd.notna(row['off_treatment_end']) and not row['still_on_treatment']:
            ax.add_patch(Rectangle(
                (row['treatment_months'], y - 0.28),
                row['off_treatment_end'] - row['treatment_months'], 0.56,
                facecolor=COLOR_OFF_TREATMENT, edgecolor='none'))
        if row['still_on_treatment']:
            ax.plot(row['treatment_months'], y, marker='>', markersize=16,
                    color=COLOR_TREATMENT, markerfacecolor=COLOR_TREATMENT,
                    markeredgewidth=0, zorder=5)

    if len(response_df) > 0:
        for _, resp_row in response_df.iterrows():
            if resp_row['response'] in RESPONSE_COLORS:
                y_pos = swimmer_df[swimmer_df['patient_id'] == resp_row['patient_id']]['y_pos'].values
                if len(y_pos) > 0:
                    color  = RESPONSE_COLORS[resp_row['response']]
                    marker = {'CR': 'o', 'PR': 's', 'SD': '^', 'PD': 'D'}[resp_row['response']]
                    size   = {'CR': 11, 'PR': 10, 'SD': 11, 'PD': 9}[resp_row['response']]
                    ax.plot(resp_row['months_from_start'], y_pos[0], marker=marker,
                            markersize=size, markerfacecolor=color,
                            markeredgecolor=color, markeredgewidth=1.5, zorder=4)

    for _, row in swimmer_df.iterrows():
        y = row['y_pos']
        endpoint_x = row['off_treatment_end'] if pd.notna(row['off_treatment_end']) else row['treatment_months']
        if pd.notna(row['endpoint_type']):
            if row['endpoint_type'] == 'death':
                ax.plot(endpoint_x, y, marker='x', markersize=11, markeredgewidth=2.5,
                        color='black', markerfacecolor='none', linestyle='None', zorder=6)
            elif row['endpoint_type'] == 'lost_to_followup':
                ax.plot(endpoint_x, y, marker='x', markersize=11, markeredgewidth=2.5,
                        color='#c41e3a', markerfacecolor='none', linestyle='None', zorder=6)

    if evaluable_count > 0 and replaced_count > 0:
        separator_y = len(swimmer_df) - evaluable_count - 0.5
        ax.axhline(y=separator_y, color='#1a1a2e', linewidth=2.5, zorder=1)

    col_x = [-3.5, -1.5]
    ax.text(col_x[0], len(swimmer_df) + 0.5, 'RECIST\nResponse',
            ha='center', va='bottom', fontsize=8, fontweight='bold', color='#1a1a2e')
    ax.text(col_x[1], len(swimmer_df) + 0.5, 'Liver\nmets',
            ha='center', va='bottom', fontsize=8, fontweight='bold', color='#1a1a2e')

    for _, row in swimmer_df.iterrows():
        y = row['y_pos']
        resp_color = RESPONSE_COLORS.get(row['best_response'], '#888')
        ax.text(col_x[0], y, row['best_response'],
                ha='center', va='center', fontsize=7, fontweight='bold', color=resp_color)
        liver_text = 'Y' if row['liver_mets'] else 'N'
        ax.text(col_x[1], y, liver_text, ha='center', va='center', fontsize=7)

    legend_elements = [
        Patch(color=COLOR_TREATMENT, label='On Treatment'),
        Patch(color=COLOR_OFF_TREATMENT, label='Off Treatment / On Study Follow-Up'),
        plt.Line2D([0],[0], marker='>', color='w', markerfacecolor=COLOR_TREATMENT,
                   markersize=16, label='Still on Treatment', linestyle='None', markeredgewidth=0),
        plt.Line2D([0],[0], marker='o', color='w', markerfacecolor=RESPONSE_COLORS['CR'],
                   markeredgecolor=RESPONSE_COLORS['CR'], markersize=11, markeredgewidth=1.5, label='CR', linestyle='None'),
        plt.Line2D([0],[0], marker='s', color='w', markerfacecolor=RESPONSE_COLORS['PR'],
                   markeredgecolor=RESPONSE_COLORS['PR'], markersize=10, markeredgewidth=1.5, label='PR', linestyle='None'),
        plt.Line2D([0],[0], marker='^', color='w', markerfacecolor=RESPONSE_COLORS['SD'],
                   markeredgecolor=RESPONSE_COLORS['SD'], markersize=11, markeredgewidth=1.5, label='SD', linestyle='None'),
        plt.Line2D([0],[0], marker='D', color='w', markerfacecolor=RESPONSE_COLORS['PD'],
                   markeredgecolor=RESPONSE_COLORS['PD'], markersize=9,  markeredgewidth=1.5, label='PD', linestyle='None'),
        plt.Line2D([0],[0], marker='x', color='black', markersize=11, markeredgewidth=2.5,
                   markerfacecolor='none', label='Death', linestyle='None'),
        plt.Line2D([0],[0], marker='x', color='#c41e3a', markersize=11, markeredgewidth=2.5,
                   markerfacecolor='none', label='Withdraw Consent / Lost to Follow Up', linestyle='None'),
    ]
    legend = ax.legend(handles=legend_elements, loc='center left', bbox_to_anchor=(1.02, 0.5),
                       fontsize=9, title='Legend', title_fontsize=10,
                       frameon=True, fancybox=False, borderpad=1, labelspacing=1.2)
    legend.get_frame().set_linewidth(1.5)
    legend.get_frame().set_edgecolor('#1a1a2e')

    summary_text = (f"Summary\n"
                    f"Evaluable      {evaluable_count:2d}\n"
                    f"Replaced       {replaced_count:2d}\n"
                    f"Total Enrolled {len(swimmer_df):2d}")
    summary_x = max_months - 8.0
    ax.add_patch(FancyBboxPatch((summary_x, 0.5), 7.5, 6.5,
                                boxstyle="round,pad=0.2",
                                facecolor='#1f4788', edgecolor='#1a1a2e',
                                linewidth=2, zorder=10))
    ax.text(summary_x + 3.75, 4.0, summary_text,
            ha='center', va='center', fontsize=13, fontweight='bold',
            color='white', family='monospace', zorder=11)

    plt.tight_layout()
    plt.subplots_adjust(right=0.82)

    buf = io.BytesIO()
    plt.savefig(buf, format='png', dpi=180, bbox_inches='tight')
    plt.close(fig)
    buf.seek(0)
    return buf


def create_waterfall_plot(data, title_suffix, study_title, cohort_number):
    if len(data) == 0:
        return None

    fig, ax = plt.subplots(figsize=(max(12, len(data) * 0.35), 8))
    fig.patch.set_facecolor('#f8f9fb')
    ax.set_facecolor('#f8f9fb')

    y_max = max(100, data['best_pct_change'].max() + 10)
    y_min = min(-100, data['best_pct_change'].min() - 10)
    ax.set_xlim(0.5, len(data) + 0.5)
    ax.set_ylim(y_min, y_max)
    ax.set_ylabel('Best % Change from Baseline in Target Lesion', fontsize=11,
                  fontweight='bold', color='#1a1a2e')

    resp_counts = data['best_response'].value_counts()
    title = (f"{study_title}  |  Cohort {cohort_number}  |  Waterfall Plot {title_suffix}\n"
             f"N={len(data)}    CR: {resp_counts.get('CR',0)}    PR: {resp_counts.get('PR',0)}"
             f"    SD: {resp_counts.get('SD',0)}    PD: {resp_counts.get('PD',0)}")
    ax.set_title(title, fontsize=12, fontweight='bold', color='#1a1a2e', pad=20)

    ax.axhline(y=0,   color='#1a1a2e', linewidth=2,   zorder=1)
    ax.axhline(y=20,  color='#1a1a2e', linewidth=1.5, linestyle='--', zorder=1)
    ax.axhline(y=-30, color='#1a1a2e', linewidth=1.5, linestyle='--', zorder=1)
    ax.grid(axis='y', color='#aab4be', linestyle='--', linewidth=0.5, alpha=0.4)

    x_pos = np.arange(1, len(data) + 1)
    colors = data['best_response'].map(WATERFALL_COLORS).fillna('#888')
    ax.bar(x_pos, data['best_pct_change'], width=0.8,
           color=colors, edgecolor='#1a1a2e', linewidth=1.2, zorder=2)
    ax.set_xticks(x_pos)
    ax.set_xticklabels(data['patient_id'], rotation=90, fontsize=7)

    legend_elements = [Patch(facecolor=WATERFALL_COLORS[r], edgecolor='#1a1a2e', label=r)
                       for r in ['CR', 'PR', 'SD', 'PD']]
    leg = ax.legend(handles=legend_elements, loc='upper right',
                    title='Best Response', title_fontsize=10, fontsize=9,
                    frameon=True, fancybox=False, edgecolor='#1a1a2e')
    leg.get_frame().set_linewidth(1.5)

    info_y = y_min - (y_max - y_min) * 0.15
    ax.text(-2.0, info_y, 'Liver\nmets', ha='left', va='top', fontsize=8, fontweight='bold')
    for i, (_, row) in enumerate(data.iterrows()):
        ax.text(x_pos[i], info_y, 'Y' if row['liver_mets'] else 'N',
                ha='center', va='center', fontsize=7)

    plt.tight_layout()
    buf = io.BytesIO()
    plt.savefig(buf, format='png', dpi=180, bbox_inches='tight')
    plt.close(fig)
    buf.seek(0)
    return buf


def create_spider_plot(swimmer_data, swimmer_df, sheets, study_title, cohort_number):
    cohort_ids = set(swimmer_df['patient_id'].unique())
    spider_rows = []

    for subject_id in cohort_ids:
        pt_record    = next((p for p in swimmer_data if p['patient_id'] == subject_id), None)
        baseline_date = pt_record.get('baseline_date', pd.NaT) if pt_record else pd.NaT
        baseline_sum  = pt_record.get('baseline_sum', np.nan) if pt_record else np.nan

        if pd.isna(baseline_sum) or baseline_sum == 0 or pd.isna(baseline_date):
            continue

        spider_rows.append({'patient_id': subject_id, 'months': 0, 'pct_change': 0})

        pt_tut = sheets['TUT'][sheets['TUT']['Subject Id'] == subject_id]
        tudat_col = next((c for c in pt_tut.columns if 'date of assessment' in c.lower()), None)
        if not tudat_col:
            tudat_col = next((c for c in pt_tut.columns if 'TUDAT' in c.upper()), None)

        for _, row in pt_tut.iterrows():
            current_sum  = pd.to_numeric(row.get('Sum of diameters', np.nan), errors='coerce')
            current_date = parse_date_safe(row.get(tudat_col, pd.NaT)) if tudat_col else pd.NaT
            if pd.isna(current_sum) or pd.isna(current_date):
                continue
            months     = ((current_date - baseline_date).days + 1) / 30.4
            pct_change = ((current_sum - baseline_sum) / baseline_sum) * 100
            spider_rows.append({'patient_id': subject_id, 'months': months, 'pct_change': pct_change})

    if not spider_rows:
        return None

    spider_df = pd.DataFrame(spider_rows)
    max_months_spider = spider_df['months'].max()
    max_month_ceil = int(np.ceil(max_months_spider / 3) * 3)

    fig, ax = plt.subplots(figsize=(10, 6))
    fig.patch.set_facecolor('#f8f9fb')
    ax.set_facecolor('#f8f9fb')

    ax.set_xlim(0, max_month_ceil)
    ax.set_ylim(-100, 100)
    ax.set_xlabel('Months', fontsize=11, fontweight='bold', color='#1a1a2e')
    ax.set_ylabel('Change from Baseline in Target Lesion, %', fontsize=11,
                  fontweight='bold', color='#1a1a2e')
    ax.set_title(
        f'{study_title}  |  Cohort {cohort_number}  |  Change in Target Lesion Size Over Time',
        fontsize=12, fontweight='bold', color='#1a1a2e'
    )
    ax.set_xticks(range(0, max_month_ceil + 1, 3))
    ax.set_yticks(range(-100, 101, 20))
    ax.set_yticklabels([f'{y}%' for y in range(-100, 101, 20)])
    ax.axhline(y=0,   color='#1a1a2e', linewidth=1.5)
    ax.axhline(y=-30, color='#1a1a2e', linewidth=1.5, linestyle='--')
    ax.axhline(y=20,  color='#1a1a2e', linewidth=1.5, linestyle='--')
    ax.grid(True, color='#aab4be', linestyle='-', linewidth=0.5, alpha=0.3)

    for pid in spider_df['patient_id'].unique():
        pt_data = spider_df[spider_df['patient_id'] == pid].sort_values('months')
        ax.plot(pt_data['months'], pt_data['pct_change'], color='#1f4788', linewidth=1.2, alpha=0.75)

    ax.text(max_months_spider * 0.95, 25, '+20%: Cut-off for progressive disease',
            ha='right', va='bottom', fontsize=9, color='#555')
    ax.text(max_months_spider * 0.95, -35, '-30%: Cut-off for partial response',
            ha='right', va='top', fontsize=9, color='#555')

    plt.tight_layout()
    buf = io.BytesIO()
    plt.savefig(buf, format='png', dpi=180, bbox_inches='tight')
    plt.close(fig)
    buf.seek(0)
    return buf


# ════════════════════════════════════════════════════════════════════════════
#  MAIN PIPELINE
# ════════════════════════════════════════════════════════════════════════════

def run_pipeline(
    file_obj,
    study_title,
    cohort_number,
    make_swimmer,
    make_waterfall_eval,
    make_waterfall_all,
    make_spider,
):
    if file_obj is None:
        return [None] * 4 + ["Please upload a data file."]

    if not any([make_swimmer, make_waterfall_eval, make_waterfall_all, make_spider]):
        return [None] * 4 + ["Please select at least one plot to generate."]

    study_title   = study_title.strip() or "GOBLET"
    cohort_number = int(cohort_number)

    try:
        upload_path = file_obj.name if hasattr(file_obj, 'name') else str(file_obj)
        excel_path  = resolve_excel_file(upload_path)

        sheets = load_sheets(excel_path, cohort_number)

        n_patients = len(sheets['DM'])
        if n_patients == 0:
            return [None]*4 + [f"No patients found for Cohort {cohort_number}. Check that the 'Cohort - Code' column exists and contains the value {cohort_number}."]

        swimmer_data = process_patients(sheets)

        swimmer_df, response_df = build_dataframes(swimmer_data)

        out_swimmer  = None
        out_wf_eval  = None
        out_wf_all   = None
        out_spider   = None

        if make_swimmer:
            buf = create_swimmer_plot(swimmer_df, response_df, study_title, cohort_number)
            out_swimmer = _buf_to_tmp(buf, "swimmer.png")

        waterfall_df = swimmer_df[
            swimmer_df['baseline_sum'].notna() &
            swimmer_df['nadir'].notna() &
            (swimmer_df['baseline_sum'] != 0)
        ].copy().sort_values('best_pct_change', ascending=False).reset_index(drop=True)

        if make_waterfall_eval:
            eval_data = waterfall_df[waterfall_df['category'] == 'Evaluable']
            buf = create_waterfall_plot(eval_data, 'β€” Evaluable Patients', study_title, cohort_number)
            if buf:
                out_wf_eval = _buf_to_tmp(buf, "waterfall_evaluable.png")

        if make_waterfall_all:
            buf = create_waterfall_plot(waterfall_df, 'β€” All Patients', study_title, cohort_number)
            if buf:
                out_wf_all = _buf_to_tmp(buf, "waterfall_all.png")

        if make_spider:
            buf = create_spider_plot(swimmer_data, swimmer_df, sheets, study_title, cohort_number)
            if buf:
                out_spider = _buf_to_tmp(buf, "spider.png")

        evaluable = (swimmer_df['category'] == 'Evaluable').sum()
        replaced  = (swimmer_df['category'] == 'Replaced').sum()
        status = (
            f"Done.  Total patients: {len(swimmer_df)}  |  "
            f"Evaluable: {evaluable}  |  Replaced: {replaced}"
        )
        return out_swimmer, out_wf_eval, out_wf_all, out_spider, status

    except Exception as e:
        import traceback
        return [None]*4 + [f"Error: {str(e)}\n\n{traceback.format_exc()}"]


def _buf_to_tmp(buf: io.BytesIO, filename: str) -> str:
    tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
    tmp.write(buf.read())
    tmp.flush()
    tmp.close()
    return tmp.name


# ════════════════════════════════════════════════════════════════════════════
#  GRADIO UI
# ════════════════════════════════════════════════════════════════════════════

CSS = """
/* ── Root variables ─────────────────────────────── */
:root {
    --clr-bg:         #f0f4f8;
    --clr-surface:    #ffffff;
    --clr-border:     #c8d6e5;
    --clr-primary:    #1f4788;
    --clr-accent:     #2a7de1;
    --clr-text:       #1a1a2e;
    --clr-muted:      #5a6a7e;
    --clr-success:    #00875a;
    --clr-danger:     #c41e3a;
    --radius:         10px;
    --shadow:         0 2px 16px 0 rgba(31,71,136,0.10);
}

body, .gradio-container {
    background: var(--clr-bg) !important;
    font-family: 'IBM Plex Sans', 'Segoe UI', sans-serif !important;
}

/* ── Header ─────────────────────────────────────── */
.app-header {
    background: linear-gradient(120deg, #1a2a4a 0%, #1f4788 60%, #2a7de1 100%);
    border-radius: var(--radius);
    padding: 36px 40px 28px;
    margin-bottom: 28px;
    box-shadow: var(--shadow);
    position: relative;
    overflow: hidden;
}
.app-header::before {
    content: '';
    position: absolute;
    top: -40px; right: -40px;
    width: 220px; height: 220px;
    border-radius: 50%;
    background: rgba(42,125,225,0.18);
    pointer-events: none;
}
.app-header h1 {
    color: #ffffff;
    font-size: 1.9rem;
    font-weight: 700;
    letter-spacing: -0.5px;
    margin: 0 0 4px;
}
.app-header p {
    color: rgba(255,255,255,0.72);
    font-size: 0.92rem;
    margin: 0;
    letter-spacing: 0.2px;
}
.app-header .tag {
    display: inline-block;
    background: rgba(255,255,255,0.15);
    border: 1px solid rgba(255,255,255,0.3);
    color: #fff;
    font-size: 0.72rem;
    font-weight: 600;
    letter-spacing: 1.2px;
    text-transform: uppercase;
    padding: 3px 10px;
    border-radius: 20px;
    margin-bottom: 14px;
}

/* ── Panels ─────────────────────────────────────── */
.panel-card {
    background: var(--clr-surface);
    border: 1px solid var(--clr-border);
    border-radius: var(--radius);
    padding: 24px;
    box-shadow: var(--shadow);
}
.section-label {
    font-size: 0.72rem;
    font-weight: 700;
    letter-spacing: 1.4px;
    text-transform: uppercase;
    color: var(--clr-primary);
    margin-bottom: 14px;
    border-left: 3px solid var(--clr-accent);
    padding-left: 8px;
}

/* ── Inputs ─────────────────────────────────────── */
label > span, .gr-form label span {
    font-size: 0.82rem !important;
    font-weight: 600 !important;
    color: var(--clr-text) !important;
    letter-spacing: 0.1px;
}
input[type="text"], input[type="number"] {
    border: 1.5px solid var(--clr-border) !important;
    border-radius: 7px !important;
    font-size: 0.9rem !important;
    background: #f8fafd !important;
    transition: border-color 0.2s;
}
input[type="text"]:focus, input[type="number"]:focus {
    border-color: var(--clr-accent) !important;
    outline: none !important;
    box-shadow: 0 0 0 3px rgba(42,125,225,0.12) !important;
}

/* ── File upload ─────────────────────────────────── */
.gr-file-upload {
    border: 2px dashed var(--clr-border) !important;
    border-radius: var(--radius) !important;
    background: #f5f8fd !important;
    transition: border-color 0.2s, background 0.2s;
}
.gr-file-upload:hover {
    border-color: var(--clr-accent) !important;
    background: #eef4ff !important;
}

/* ── Checkboxes ─────────────────────────────────── */
.gr-checkbox-group label {
    font-size: 0.85rem !important;
    color: var(--clr-text) !important;
}

/* ── Button ─────────────────────────────────────── */
button.primary, .gr-button-primary {
    background: linear-gradient(135deg, #1f4788 0%, #2a7de1 100%) !important;
    border: none !important;
    border-radius: 8px !important;
    color: #fff !important;
    font-weight: 700 !important;
    font-size: 0.92rem !important;
    letter-spacing: 0.4px;
    padding: 12px 28px !important;
    box-shadow: 0 4px 14px rgba(31,71,136,0.25) !important;
    transition: transform 0.15s, box-shadow 0.15s;
    cursor: pointer;
}
button.primary:hover, .gr-button-primary:hover {
    transform: translateY(-1px);
    box-shadow: 0 6px 20px rgba(31,71,136,0.35) !important;
}

/* ── Status bar ─────────────────────────────────── */
.status-box textarea {
    background: #f0f7ff !important;
    border: 1.5px solid #b8d0f0 !important;
    border-radius: 8px !important;
    color: var(--clr-primary) !important;
    font-size: 0.85rem !important;
    font-family: 'IBM Plex Mono', monospace !important;
}

/* ── Image outputs ──────────────────────────────── */
.gr-image {
    border-radius: var(--radius) !important;
    border: 1px solid var(--clr-border) !important;
    box-shadow: var(--shadow) !important;
    overflow: hidden;
}

/* ── Tab labels ─────────────────────────────────── */
.tab-nav button {
    font-size: 0.82rem !important;
    font-weight: 600 !important;
    letter-spacing: 0.3px;
    color: var(--clr-muted) !important;
}
.tab-nav button.selected {
    color: var(--clr-primary) !important;
    border-bottom: 2.5px solid var(--clr-accent) !important;
}

/* ── Footer ─────────────────────────────────────── */
.app-footer {
    text-align: center;
    padding: 18px;
    color: var(--clr-muted);
    font-size: 0.78rem;
    letter-spacing: 0.2px;
    margin-top: 18px;
}
"""

HEADER_HTML = """
<div class="app-header">
  <div class="tag">Clinical Oncology Tooling</div>
  <h1>GOBLET Visualizer Agent</h1>
  <p>Upload your clinical trial dataset and generate publication-quality oncology plots instantly.</p>
</div>
"""

FOOTER_HTML = """
<div class="app-footer">
  GOBLET Visualizer Agent &nbsp;|&nbsp; Swimmer &middot; Waterfall &middot; Spider Plots &nbsp;|&nbsp;
  Data is processed locally and never stored.
</div>
"""

with gr.Blocks(css=CSS, title="GOBLET Visualizer Agent") as demo:

    gr.HTML(HEADER_HTML)

    with gr.Row():
        # ── Left panel: inputs ────────────────────────────
        with gr.Column(scale=1, min_width=300):
            with gr.Group(elem_classes="panel-card"):
                gr.HTML('<div class="section-label">Dataset Upload</div>')
                file_input = gr.File(
                    label="Upload File",
                    file_types=[".xlsx", ".xls", ".csv", ".zip", ".rar"],
                    file_count="single",
                )
                gr.HTML(
                    '<p style="font-size:0.78rem;color:#5a6a7e;margin:6px 0 0;">'
                    'Accepted formats: Excel (.xlsx/.xls), CSV, ZIP, RAR</p>'
                )

            with gr.Group(elem_classes="panel-card"):
                gr.HTML('<div class="section-label">Study Parameters</div>')
                study_title_input = gr.Textbox(
                    label="Study Title",
                    placeholder="e.g. GOBLET",
                    value="GOBLET",
                )
                cohort_input = gr.Number(
                    label="Cohort Number",
                    value=4,
                    minimum=1,
                    precision=0,
                )

            with gr.Group(elem_classes="panel-card"):
                gr.HTML('<div class="section-label">Select Plots</div>')
                plot_selector = gr.CheckboxGroup(
                    choices=[
                        "Swimmer Plot",
                        "Waterfall β€” Evaluable Patients",
                        "Waterfall β€” All Patients",
                        "Spider Plot",
                    ],
                    value=[
                        "Swimmer Plot",
                        "Waterfall β€” Evaluable Patients",
                        "Waterfall β€” All Patients",
                        "Spider Plot",
                    ],
                    label="",
                )

            generate_btn = gr.Button("Generate Plots", variant="primary", size="lg")

            status_box = gr.Textbox(
                label="Status",
                interactive=False,
                lines=2,
                elem_classes="status-box",
            )

        # ── Right panel: outputs ──────────────────────────
        with gr.Column(scale=2):
            with gr.Tabs():
                with gr.Tab("Swimmer Plot"):
                    swimmer_out = gr.Image(label="Swimmer Plot", type="filepath")
                with gr.Tab("Waterfall β€” Evaluable"):
                    wf_eval_out = gr.Image(label="Waterfall (Evaluable)", type="filepath")
                with gr.Tab("Waterfall β€” All"):
                    wf_all_out  = gr.Image(label="Waterfall (All Patients)", type="filepath")
                with gr.Tab("Spider Plot"):
                    spider_out  = gr.Image(label="Spider Plot", type="filepath")

    gr.HTML(FOOTER_HTML)

    # ── Wire up ───────────────────────────────────────────
    def _run(file_obj, study_title, cohort_number, selected_plots):
        make_swimmer       = "Swimmer Plot"                   in selected_plots
        make_wf_eval       = "Waterfall β€” Evaluable Patients" in selected_plots
        make_wf_all        = "Waterfall β€” All Patients"       in selected_plots
        make_spider        = "Spider Plot"                    in selected_plots
        return run_pipeline(
            file_obj, study_title, cohort_number,
            make_swimmer, make_wf_eval, make_wf_all, make_spider
        )

    generate_btn.click(
        fn=_run,
        inputs=[file_input, study_title_input, cohort_input, plot_selector],
        outputs=[swimmer_out, wf_eval_out, wf_all_out, spider_out, status_box],
    )


if __name__ == "__main__":
    demo.launch()