File size: 23,242 Bytes
37b0eb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1bc27d
 
37b0eb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
PLOT ENGINE
Generates Swimmer, Waterfall, and Spider plots
from standardized mapped data.
All input comes via the column_mapper output β€” no hardcoded column names.
"""

import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg')  # Non-interactive backend for server use
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch
from matplotlib.lines import Line2D
import io
from datetime import datetime


# ── Constants ──────────────────────────────────────────────────────────────

COLOR_TREATMENT     = '#1f4788'
COLOR_OFF_TREATMENT = '#808080'
RESPONSE_COLORS     = {
    'CR': '#00CC00',
    'PR': '#5a9bd4',
    'SD': '#f0c929',
    'PD': '#c41e3a',
    'NE': '#aaaaaa',
}
RESPONSE_MARKERS = {
    'CR': 'o',
    'PR': 's',
    'SD': '^',
    'PD': 'D',
}
RESPONSE_RANK = {'CR': 1, 'PR': 2, 'SD': 3, 'PD': 4}


# ── Helpers ─────────────────────────────────────────────────────────────────

def parse_date(val):
    if pd.isna(val) or str(val).strip() == '':
        return pd.NaT
    if isinstance(val, pd.Timestamp):
        return val
    s = str(val).strip()
    if 'UNK' in s.upper():
        return pd.NaT
    try:
        return pd.to_datetime(s)
    except Exception:
        return pd.NaT


def to_months(start, end):
    if pd.isna(start) or pd.isna(end):
        return 0.0
    return max(0.0, (end - start).days / 30.44)


def normalize_response(val) -> str | None:
    s = str(val).upper().strip()
    if 'COMPLETE' in s or s in ('CR', '1'):
        return 'CR'
    if 'PARTIAL' in s or s in ('PR', '2'):
        return 'PR'
    if 'STABLE' in s or s in ('SD', '3'):
        return 'SD'
    if 'PROGRESS' in s or s in ('PD', '4'):
        return 'PD'
    return None


def fig_to_bytes(fig) -> bytes:
    buf = io.BytesIO()
    fig.savefig(buf, format='png', dpi=150, bbox_inches='tight', facecolor='white')
    buf.seek(0)
    plt.close(fig)
    return buf.read()


# ── Data Builder ─────────────────────────────────────────────────────────────

def build_patient_records(dataframes: dict, mapping: dict) -> list[dict]:
    """
    Build a list of per-patient dicts using the Gemini-produced column mapping.
    This is the only place where mapping keys are used β€” the rest of the engine
    works on the normalized patient records.
    """

    def get_col(table_name, col_name):
        if table_name in dataframes and col_name in dataframes[table_name].columns:
            return dataframes[table_name]
        return None

    def resolve(variable):
        """Return (table_name, column_name) or (None, None)."""
        entry = mapping.get(variable)
        if entry is None:
            return None, None
        if isinstance(entry, list):
            entry = entry[0]
        return entry.get('table'), entry.get('column')

    # Subject list
    subj_table, subj_col = resolve('SUBJECT_ID')
    if subj_table is None or subj_table not in dataframes:
        raise ValueError("Cannot find SUBJECT_ID mapping in any table.")
    subjects = dataframes[subj_table][subj_col].dropna().unique()

    ts_table, ts_col   = resolve('TREATMENT_START')
    te_table, te_col   = resolve('TREATMENT_END')
    rd_table, rd_col   = resolve('RESPONSE_DATE')
    rv_table, rv_col   = resolve('RESPONSE_VALUE')
    bl_table, bl_col   = resolve('BASELINE_SUM')
    bd_table, bd_col   = resolve('BASELINE_DATE')
    fu_table, fu_col   = resolve('FOLLOWUP_SUM')
    fd_table, fd_col   = resolve('FOLLOWUP_DATE')
    er_table, er_col   = resolve('END_REASON')
    mh_table, mh_col   = resolve('MEDICAL_HISTORY')

    # Lesion location β€” may be a list of mappings
    ll_entries = mapping.get('LESION_LOCATION', [])
    if isinstance(ll_entries, dict):
        ll_entries = [ll_entries]

    records = []

    for subj in subjects:
        rec = {'patient_id': subj}

        # --- Treatment start ---
        start_date = pd.NaT
        if ts_table and ts_table in dataframes and ts_col:
            df = dataframes[ts_table]
            rows = df[df[subj_col] == subj]
            if len(rows) > 0:
                start_date = parse_date(rows.iloc[0][ts_col])

        if pd.isna(start_date):
            continue  # Cannot place patient on timeline without start date

        # --- Treatment end ---
        end_date = pd.NaT
        if te_table and te_table in dataframes and te_col:
            df = dataframes[te_table]
            rows = df[df[subj_col] == subj]
            if len(rows) > 0:
                end_date = parse_date(rows.iloc[0][te_col])

        still_on_treatment = False
        if pd.isna(end_date):
            # Fall back: use last treatment start as proxy
            if ts_table and ts_table in dataframes and ts_col:
                df = dataframes[ts_table]
                rows = df[df[subj_col] == subj]
                if len(rows) > 0:
                    last = parse_date(rows.iloc[-1][ts_col])
                    if not pd.isna(last):
                        end_date = last
                        still_on_treatment = True
        if pd.isna(end_date):
            end_date = start_date + pd.Timedelta(days=30)

        treatment_months = to_months(start_date, end_date)

        # --- Responses ---
        responses = []
        if rd_table and rd_table in dataframes and rd_col and rv_col:
            df = dataframes[rd_table]
            rows = df[df[subj_col] == subj]
            for _, row in rows.iterrows():
                rdate = parse_date(row.get(rd_col))
                rval  = normalize_response(row.get(rv_col, ''))
                if pd.isna(rdate) or rval is None:
                    continue
                responses.append({
                    'months':   to_months(start_date, rdate),
                    'response': rval,
                    'date':     rdate,
                })

        best_response = 'NE'
        if responses:
            best_response = min(
                [r['response'] for r in responses],
                key=lambda x: RESPONSE_RANK.get(x, 9)
            )

        # --- End reason ---
        endpoint_type = None
        if er_table and er_table in dataframes and er_col:
            df = dataframes[er_table]
            rows = df[df[subj_col] == subj]
            if len(rows) > 0:
                reason = str(rows.iloc[0].get(er_col, '')).lower()
                if 'death' in reason:
                    endpoint_type = 'death'
                elif 'withdraw' in reason or 'consent' in reason:
                    endpoint_type = 'lost_to_followup'

        # --- Baseline tumor sum ---
        baseline_sum = None
        baseline_date = pd.NaT
        if bl_table and bl_table in dataframes and bl_col:
            df = dataframes[bl_table]
            rows = df[df[subj_col] == subj]
            if len(rows) > 0:
                try:
                    baseline_sum = float(rows.iloc[0][bl_col])
                    if bd_col and bd_col in rows.columns:
                        baseline_date = parse_date(rows.iloc[0][bd_col])
                except Exception:
                    baseline_sum = None

        if pd.isna(baseline_date):
            baseline_date = start_date

        # --- Follow-up tumor sums ---
        followup_records = []
        if fu_table and fu_table in dataframes and fu_col:
            df = dataframes[fu_table]
            rows = df[df[subj_col] == subj]
            for _, row in rows.iterrows():
                try:
                    fsum = float(row[fu_col])
                except Exception:
                    continue
                fdate = parse_date(row.get(fd_col)) if fd_col else pd.NaT
                followup_records.append({'sum': fsum, 'date': fdate})

        # --- Metastasis flags ---
        liver_mets = False
        brain_mets = False

        if mh_table and mh_table in dataframes and mh_col:
            df = dataframes[mh_table]
            rows = df[df[subj_col] == subj]
            for _, row in rows.iterrows():
                term = str(row.get(mh_col, '')).lower()
                if 'liver' in term or 'hepatic' in term:
                    liver_mets = True
                if 'brain' in term or 'cerebral' in term:
                    brain_mets = True

        for ll_entry in ll_entries:
            ll_t = ll_entry.get('table')
            ll_c = ll_entry.get('column')
            if ll_t and ll_t in dataframes and ll_c:
                df = dataframes[ll_t]
                rows = df[df[subj_col] == subj]
                for _, row in rows.iterrows():
                    loc = str(row.get(ll_c, '')).lower()
                    if 'liver' in loc:
                        liver_mets = True
                    if 'brain' in loc:
                        brain_mets = True

        # --- Evaluable flag ---
        has_baseline   = baseline_sum is not None and baseline_sum > 0
        has_followup   = len(followup_records) > 0
        has_response   = len(responses) >= 1
        evaluable      = has_baseline and has_followup and has_response

        # --- Off-treatment period ---
        off_start = off_end = None
        if not still_on_treatment and responses:
            valid_dates = [r['date'] for r in responses if not pd.isna(r['date'])]
            last_resp_date = max(valid_dates) if valid_dates else pd.NaT
            if not pd.isna(last_resp_date) and last_resp_date > end_date:
                off_start = treatment_months
                off_end   = to_months(start_date, last_resp_date)

        records.append({
            'patient_id':        subj,
            'start_date':        start_date,
            'baseline_date':     baseline_date,
            'treatment_months':  treatment_months,
            'responses':         responses,
            'best_response':     best_response,
            'still_on_treatment':still_on_treatment,
            'endpoint_type':     endpoint_type,
            'baseline_sum':      baseline_sum,
            'followup_records':  followup_records,
            'liver_mets':        liver_mets,
            'brain_mets':        brain_mets,
            'evaluable':         evaluable,
            'off_start':         off_start,
            'off_end':           off_end,
        })

    records.sort(key=lambda x: (not x['evaluable'], -x['treatment_months']))
    return records


# ── Swimmer Plot ─────────────────────────────────────────────────────────────

def swimmer_plot(records: list[dict], cohort_label: str = '') -> bytes:
    n = len(records)
    if n == 0:
        raise ValueError("No patient records to plot.")

    evaluable_n = sum(1 for r in records if r['evaluable'])
    replaced_n  = n - evaluable_n

    fig, ax = plt.subplots(figsize=(20, max(10, n * 0.35)))

    for i, pt in enumerate(records):
        y = n - i - 1

        ax.barh(y, pt['treatment_months'], height=0.6,
                color=COLOR_TREATMENT, edgecolor='none', zorder=2)

        if pt['off_start'] and pt['off_end']:
            ax.barh(y, pt['off_end'] - pt['off_start'], height=0.6,
                    left=pt['off_start'], color=COLOR_OFF_TREATMENT,
                    edgecolor='none', zorder=2)

        if pt['still_on_treatment']:
            ax.add_patch(FancyArrowPatch(
                (pt['treatment_months'], y),
                (pt['treatment_months'] + 1, y),
                arrowstyle='->', mutation_scale=20,
                linewidth=2.5, color=COLOR_TREATMENT, zorder=5
            ))

        for resp in pt['responses']:
            if resp['response'] in RESPONSE_COLORS:
                ax.scatter(resp['months'], y, s=150,
                           marker=RESPONSE_MARKERS.get(resp['response'], 'o'),
                           c=RESPONSE_COLORS[resp['response']],
                           edgecolors=RESPONSE_COLORS[resp['response']],
                           linewidths=1.5, zorder=4)

        ep_x = pt['off_end'] or pt['treatment_months']
        if pt['endpoint_type'] == 'death':
            ax.scatter(ep_x, y, marker='x', s=250, c='black',
                       linewidths=2, zorder=6)
        elif pt['endpoint_type'] == 'lost_to_followup':
            ax.scatter(ep_x, y, marker='x', s=220, c='#c41e3a',
                       linewidths=2, zorder=6)

    # Axes
    all_months = [p['treatment_months'] for p in records]
    all_months += [p['off_end'] for p in records if p['off_end']]
    x_max = max(all_months) + 2

    ax.set_xlim(-5, x_max)
    ax.set_xticks(range(0, int(x_max) + 1, 3))
    ax.set_xlabel('Months', fontsize=14, fontweight='bold')

    y_labels = [str(p['patient_id']) for p in records]
    ax.set_yticks(range(n))
    ax.set_yticklabels(reversed(y_labels), fontsize=9)
    for tick, pt in zip(ax.get_yticklabels(), records):
        tick.set_color('black' if pt['evaluable'] else 'red')
        tick.set_fontweight('bold')

    ax.set_ylim(-0.5, n - 0.5)

    if evaluable_n > 0 and replaced_n > 0:
        ax.axhline(y=n - evaluable_n - 0.5, color='black',
                   linewidth=2.5, linestyle='-', zorder=7)

    # Annotation columns
    ax.text(-3.5, n + 0.3, 'RECIST\nResponse',
            fontsize=9, fontweight='bold', ha='center', va='bottom')
    ax.text(-1.5, n + 0.3, 'Liver\nmets',
            fontsize=9, fontweight='bold', ha='center', va='bottom')

    for i, pt in enumerate(records):
        y = n - i - 1
        rc = RESPONSE_COLORS.get(pt['best_response'], 'gray')
        ax.text(-3.5, y, pt['best_response'], fontsize=8,
                ha='center', va='center', fontweight='bold', color=rc)
        ax.text(-1.5, y, 'Y' if pt['liver_mets'] else 'N',
                fontsize=8, ha='center', va='center')

    # Title
    ax.set_title(
        f"Swimmer Plot{': ' + cohort_label if cohort_label else ''}\n"
        f"All Patients",
        fontsize=16, fontweight='bold', pad=25
    )

    # Legend
    legend_elements = [
        Line2D([0], [0], color=COLOR_TREATMENT, lw=10, label='On Treatment'),
        Line2D([0], [0], color=COLOR_OFF_TREATMENT, lw=10,
               label='Off Treatment / On Study Follow-Up'),
        Line2D([0], [0], marker='>', color=COLOR_TREATMENT,
               markersize=10, label='Still on Treatment', linestyle='None'),
        *[
            Line2D([0], [0], marker=RESPONSE_MARKERS[r], color='w',
                   markerfacecolor=RESPONSE_COLORS[r], markersize=12,
                   markeredgecolor=RESPONSE_COLORS[r], markeredgewidth=1.5,
                   label=r, linestyle='None')
            for r in ['CR', 'PR', 'SD', 'PD']
        ],
        Line2D([0], [0], marker='x', color='black', markersize=13,
               markeredgewidth=2, label='Death', linestyle='None'),
        Line2D([0], [0], marker='x', color='#c41e3a', markersize=12,
               markeredgewidth=2, label='Withdraw / Lost to Follow-Up',
               linestyle='None'),
    ]
    legend = ax.legend(handles=legend_elements, loc='center left',
                       bbox_to_anchor=(1.01, 0.5), frameon=True,
                       fontsize=11, title='Legend', title_fontsize=12,
                       edgecolor='black', fancybox=False)
    legend.get_frame().set_linewidth(1.5)

    # Summary box
    summary = (f"Summary\n"
               f"Evaluable      {evaluable_n:2d}\n"
               f"Replaced       {replaced_n:2d}\n"
               f"Total Enrolled {n:2d}")
    ax.text(0.975, 0.02, summary, transform=ax.transAxes,
            fontsize=11, va='bottom', ha='right',
            bbox=dict(boxstyle='round,pad=0.5', facecolor='#2b5f8a',
                      edgecolor='black', linewidth=1.5),
            color='white', weight='bold', family='monospace')

    ax.grid(True, axis='x', alpha=0.3, linestyle='--', linewidth=0.7)
    ax.set_axisbelow(True)
    for spine in ax.spines.values():
        spine.set_linewidth(1.5)

    plt.tight_layout()
    return fig_to_bytes(fig)


# ── Waterfall Plot ───────────────────────────────────────────────────────────

def waterfall_plot(records: list[dict], title_suffix: str = '',
                   evaluable_only: bool = False) -> bytes:
    data = []
    for pt in records:
        if evaluable_only and not pt['evaluable']:
            continue
        bs = pt['baseline_sum']
        fu = pt['followup_records']
        if bs is None or bs == 0 or not fu:
            continue
        nadir    = min(f['sum'] for f in fu)
        pct      = ((nadir - bs) / bs) * 100
        data.append({**pt, 'pct_change': pct})

    if not data:
        raise ValueError("No data available for waterfall plot.")

    data.sort(key=lambda x: x['pct_change'], reverse=True)
    n = len(data)

    fig, ax = plt.subplots(figsize=(max(16, n * 0.45), 10))

    color_map = {
        'CR': '#1f4788', 'PR': '#5a9bd4',
        'SD': '#f0c929', 'PD': '#c41e3a',
    }

    for i, pt in enumerate(data):
        ax.bar(i, pt['pct_change'],
               color=color_map.get(pt['best_response'], 'gray'),
               edgecolor='black', linewidth=1.2, width=0.8)

    ax.axhline(y=0,   color='black', linewidth=2,   zorder=3)
    ax.axhline(y=20,  color='black', linewidth=1.5, linestyle='--', zorder=3)
    ax.axhline(y=-30, color='black', linewidth=1.5, linestyle='--', zorder=3)

    y_vals = [pt['pct_change'] for pt in data]
    y_max  = max(100, max(y_vals) + 10)
    y_min  = min(-100, min(y_vals) - 10)
    ax.set_ylim(y_min, y_max)
    ax.set_ylabel('Best % change from baseline in target lesion',
                  fontsize=14, fontweight='bold')

    ax.set_xlim(-0.5, n - 0.5)
    ax.set_xticks(range(n))
    ax.set_xticklabels([str(p['patient_id']) for p in data],
                       rotation=90, fontsize=9)

    counts = {r: sum(1 for p in data if p['best_response'] == r)
              for r in ['CR', 'PR', 'SD', 'PD']}
    ax.set_title(
        f"Waterfall Plot Best Response{' - ' + title_suffix if title_suffix else ''}\n"
        f"N={n}  CR:{counts['CR']} PR:{counts['PR']} "
        f"SD:{counts['SD']} PD:{counts['PD']}",
        fontsize=16, fontweight='bold', pad=20
    )

    legend_elements = [
        Line2D([0], [0], marker='s', color='w',
               markerfacecolor=color_map[r], markersize=15,
               markeredgecolor='black', markeredgewidth=1.5, label=r)
        for r in ['CR', 'PR', 'SD', 'PD']
    ]
    ax.legend(handles=legend_elements, loc='upper right', frameon=True,
              fontsize=12, title='Best Response', title_fontsize=13,
              edgecolor='black', fancybox=False).get_frame().set_linewidth(1.5)

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

    ax.grid(True, axis='y', alpha=0.3, linestyle='--', linewidth=0.7)
    ax.set_axisbelow(True)
    for spine in ax.spines.values():
        spine.set_linewidth(1.5)

    plt.tight_layout()
    return fig_to_bytes(fig)


# ── Spider Plot ──────────────────────────────────────────────────────────────

def spider_plot(records: list[dict], cohort_label: str = '') -> bytes:
    fig, ax = plt.subplots(figsize=(14, 8))

    plotted = 0
    for pt in records:
        bs = pt['baseline_sum']
        fu = pt['followup_records']
        if bs is None or bs == 0 or not fu:
            continue

        bd = pt['baseline_date']
        if pd.isna(bd):
            bd = pt['start_date']

        months_list = [0.0]
        pct_list    = [0.0]

        for f in sorted(fu, key=lambda x: x['date'] if not pd.isna(x['date']) else pd.Timestamp.min):
            if pd.isna(f['date']):
                continue
            m   = to_months(bd, f['date'])
            pct = ((f['sum'] - bs) / bs) * 100
            months_list.append(m)
            pct_list.append(pct)

        if len(months_list) > 1:
            ax.plot(months_list, pct_list,
                    color='black', alpha=0.75, linewidth=1.2, zorder=2)
            plotted += 1

    if plotted == 0:
        raise ValueError("No spider plot data available.")

    ax.axhline(y=0,   color='black', linewidth=1.5, zorder=3)
    ax.axhline(y=-30, color='black', linewidth=1.5, linestyle='--', zorder=3)
    ax.axhline(y=20,  color='black', linewidth=1.5, linestyle='--', zorder=3)

    x_max = ax.get_xlim()[1]
    ax.text(x_max * 0.97, 25,  '+20%: Cut-off for progressive disease',
            ha='right', va='bottom', fontsize=10)
    ax.text(x_max * 0.97, -35, '-30%: Cut-off for partial response',
            ha='right', va='top', fontsize=10)

    ax.set_ylim(-100, 100)
    ax.set_yticks(range(-100, 101, 20))
    ax.set_yticklabels([f'{y}%' for y in range(-100, 101, 20)])
    ax.set_ylabel('Change from baseline in target lesion, %',
                  fontsize=13, fontweight='bold')
    ax.set_xlabel('Months', fontsize=13, fontweight='bold')

    ax.set_title(
        f"Change in Target Lesion Size Over Time"
        f"{': ' + cohort_label if cohort_label else ''}",
        fontsize=15, fontweight='bold', pad=20
    )

    ax.grid(True, alpha=0.3, linestyle='-', linewidth=0.5)
    ax.set_axisbelow(True)
    for spine in ax.spines.values():
        spine.set_linewidth(1.5)

    plt.tight_layout()
    return fig_to_bytes(fig)


# ── Processed CSV Export ─────────────────────────────────────────────────────

def export_processed_csv(records: list[dict]) -> pd.DataFrame:
    """Return a flat DataFrame summarizing per-patient processed data."""
    rows = []
    for pt in records:
        fu = pt['followup_records']
        bs = pt['baseline_sum']
        best_pct = None
        if bs and bs > 0 and fu:
            nadir    = min(f['sum'] for f in fu)
            best_pct = round(((nadir - bs) / bs) * 100, 2)

        rows.append({
            'patient_id':        pt['patient_id'],
            'treatment_months':  round(pt['treatment_months'], 2),
            'best_response':     pt['best_response'],
            'evaluable':         pt['evaluable'],
            'still_on_treatment':pt['still_on_treatment'],
            'endpoint_type':     pt['endpoint_type'] or '',
            'liver_mets':        pt['liver_mets'],
            'brain_mets':        pt['brain_mets'],
            'baseline_sum_mm':   bs,
            'best_pct_change':   best_pct,
            'n_response_assessments': len(pt['responses']),
        })

    return pd.DataFrame(rows)