File size: 30,545 Bytes
7a4e1ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import tempfile
import os
import datetime
import re
import time
import concurrent.futures
from therapist import (
    run_therapy_individual,
    run_therapy_group,
    run_therapy_relationship
)

def select_group_row(evt: gr.SelectData, df):
    row_idx = evt.index[0]
    if hasattr(df, "iloc"):
        circle_name = df.iloc[row_idx, 0]
        bugs = df.iloc[row_idx, 1]
    else:
        circle_name = df[row_idx][0]
        bugs = df[row_idx][1]
    return circle_name, bugs

def add_group_to_history(circle_name, bugs, df):
    if not bugs or not bugs.strip():
        return df
    name = circle_name.strip() if circle_name and circle_name.strip() else "Custom Circle"
    new_row = [name, bugs.strip()]
    if hasattr(df, "values") and hasattr(df, "tolist"):
        df_list = df.values.tolist()
    else:
        df_list = list(df)
    exists = False
    for r in df_list:
        if r[0] == name and r[1] == bugs.strip():
            exists = True
            break
    if not exists:
        df_list.append(new_row)
    if hasattr(df, "iloc"):
        try:
            import pandas as pd
            return pd.DataFrame(df_list, columns=df.columns)
        except ImportError:
            pass
    return df_list

def select_couples_row(evt: gr.SelectData, df):
    row_idx = evt.index[0]
    if hasattr(df, "iloc"):
        a = df.iloc[row_idx, 0]
        b = df.iloc[row_idx, 1]
        conflict = df.iloc[row_idx, 2]
    else:
        a = df[row_idx][0]
        b = df[row_idx][1]
        conflict = df[row_idx][2]
    return a, b, conflict

def add_couples_to_history(a, b, conflict, df):
    if not a or not b or not conflict:
        return df
    new_row = [a.strip(), b.strip(), conflict.strip()]
    if hasattr(df, "values") and hasattr(df, "tolist"):
        df_list = df.values.tolist()
    else:
        df_list = list(df)
    exists = False
    for r in df_list:
        if r[0] == a.strip() and r[1] == b.strip() and r[2] == conflict.strip():
            exists = True
            break
    if not exists:
        df_list.append(new_row)
    if hasattr(df, "iloc"):
        try:
            import pandas as pd
            return pd.DataFrame(df_list, columns=df.columns)
        except ImportError:
            pass
    return df_list

# Monochromatic case-file design system (typewriter-inspired typography)
custom_css = """
@import url('https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap');

body, .gradio-container {
    background-color: #0A0A0A !important;
    font-family: 'Geist', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
    color: #A3A3A3 !important;
    letter-spacing: -0.01em;
}

.gradio-container {
    max-width: 960px !important;
    margin: 0 auto !important;
    padding: 60px 20px !important;
}

/* Header */
.clinical-title {
    font-family: 'Geist', sans-serif !important;
    font-weight: 500 !important;
    color: #F5F5F5 !important;
    font-size: 2.2rem !important;
    letter-spacing: -0.03em;
    margin-bottom: 6px !important;
    text-align: center;
}

.clinical-subtitle {
    color: #737373 !important;
    font-size: 1rem !important;
    margin-bottom: 48px !important;
    font-weight: 400 !important;
    text-align: center;
}

/* Tabs */
.tabs {
    background: transparent !important;
    border-bottom: 1px solid #262626 !important;
    margin-bottom: 32px !important;
}

.tab-nav {
    border: none !important;
    display: flex !important;
    gap: 32px !important;
}

.tab-nav button {
    font-family: 'Geist', sans-serif !important;
    font-size: 0.95rem !important;
    font-weight: 500 !important;
    color: #737373 !important;
    background: transparent !important;
    border: none !important;
    border-bottom: 2px solid transparent !important;
    padding: 8px 0 !important;
    border-radius: 0 !important;
    transition: all 0.15s ease !important;
}

.tab-nav button:hover {
    color: #E5E5E5 !important;
}

.tab-nav button.selected {
    color: #F5F5F5 !important;
    border-bottom: 2px solid #F5F5F5 !important;
}

/* Patient Case File (Typewriter look) */
.patient-file-container {
    background-color: #111111 !important;
    border: 1px solid #262626 !important;
    border-radius: 8px !important;
    padding: 28px !important;
    color: #CCCCCC !important;
    font-size: 0.95rem !important;
    line-height: 1.8 !important;
    font-family: 'Courier New', Courier, monospace !important;
}

.patient-file-container h1, .patient-file-container h2 {
    color: #F5F5F5 !important;
    font-family: 'Courier New', Courier, monospace !important;
    font-weight: bold !important;
    border-bottom: 1px dashed #262626 !important;
    padding-bottom: 6px !important;
    margin-top: 28px !important;
    margin-bottom: 14px !important;
    font-size: 1.25rem !important;
    letter-spacing: -0.01em;
}

.patient-file-container h1:first-of-type {
    margin-top: 0 !important;
}

.patient-file-container p, .patient-file-container li {
    font-family: 'Courier New', Courier, monospace !important;
    color: #AAAAAA !important;
    font-size: 0.95rem !important;
}

.patient-file-container blockquote {
    border-left: 3px solid #525252 !important;
    padding: 4px 16px !important;
    margin: 16px 0 !important;
    color: #737373 !important;
    font-style: italic;
}

.patient-file-container code {
    font-family: 'JetBrains Mono', monospace !important;
    font-size: 0.85rem !important;
    background-color: #222222 !important;
    padding: 2px 6px !important;
    border-radius: 4px !important;
    color: #E5E5E5 !important;
}

/* Form inputs styling */
.gr-box {
    background-color: #171717 !important;
    border: 1px solid #262626 !important;
    border-radius: 8px !important;
}

textarea, input[type="text"] {
    background-color: #0A0A0A !important;
    border: 1px solid #262626 !important;
    color: #E5E5E5 !important;
    border-radius: 6px !important;
    font-size: 0.9rem !important;
    padding: 12px !important;
}

textarea:focus, input[type="text"]:focus {
    border-color: #525252 !important;
    box-shadow: none !important;
    outline: none !important;
}

/* Primary CTA Button */
.diagnose-btn {
    background-color: #F5F5F5 !important;
    border: 1px solid #F5F5F5 !important;
    color: #0A0A0A !important;
    font-weight: 500 !important;
    font-size: 0.95rem !important;
    font-family: 'Geist', sans-serif !important;
    border-radius: 6px !important;
    padding: 12px 24px !important;
    transition: all 0.15s ease !important;
    cursor: pointer !important;
    text-align: center !important;
}

.diagnose-btn:hover {
    background-color: #E5E5E5 !important;
    border-color: #E5E5E5 !important;
}

/* Secondary Action Buttons (Outlined) */
.export-btn {
    background-color: transparent !important;
    border: 1px solid #262626 !important;
    color: #737373 !important;
    font-weight: 500 !important;
    font-family: 'Geist', sans-serif !important;
    border-radius: 6px !important;
    padding: 10px 20px !important;
    transition: all 0.15s ease !important;
    margin-top: 16px !important;
    text-align: center !important;
    font-size: 0.85rem !important;
    cursor: pointer !important;
    width: 100% !important;
}

.export-btn:hover {
    border-color: #525252 !important;
    color: #F5F5F5 !important;
}

/* Small inline pill button */
.pill-btn {
    background-color: #171717 !important;
    border: 1px solid #262626 !important;
    color: #A3A3A3 !important;
    font-size: 0.8rem !important;
    font-weight: 400 !important;
    padding: 4px 10px !important;
    border-radius: 4px !important;
    cursor: pointer !important;
    transition: all 0.1s ease !important;
}

.pill-btn:hover {
    background-color: #262626 !important;
    color: #F5F5F5 !important;
    border-color: #525252 !important;
}

/* Examples box */
.gr-example {
    background-color: #171717 !important;
    border: 1px solid #262626 !important;
    border-radius: 6px !important;
    color: #A3A3A3 !important;
    font-size: 0.85rem !important;
    transition: all 0.15s !important;
}

.gr-example:hover {
    background-color: #262626 !important;
    border-color: #525252 !important;
}

/* Hidden download buttons selector (hides them from users but keeps in DOM for JS selectors) */
#ind_download_hidden, #group_download_hidden, #rel_download_hidden {
    display: none !important;
}

/* Remove confusing elapsed/ETA texts from Gradio's loading indicator, leaving only spinner/loader elements */
.progress-level-inner, .progress-bar-wrap, .eta-bar, .meta-text, .meta-text-center, .meta-text-container {
    display: none !important;
}
"""

def clean_txt_for_pdf(text):
    """
    Translites curly/unicode punctuation that FPDF standard 8-bit fonts can't encode.
    """
    replacements = {
        '\u2018': "'",  # Smart left single quote
        '\u2019': "'",  # Smart right single quote
        '\u201c': '"',  # Smart left double quote
        '\u201d': '"',  # Smart right double quote
        '\u2013': '-',  # En dash
        '\u2014': '-',  # Em dash
        '\u2026': '...', # Ellipsis
    }
    for orig, rep in replacements.items():
        text = text.replace(orig, rep)
    # Filter non-latin-1 characters safely
    return text.encode('latin-1', 'replace').decode('latin-1')

def generate_pdf_report(report_text, mode, bug_name_or_comp_a="", comp_b=""):
    """
    Saves the therapy report text into a professionally styled case-file PDF.
    """
    if not report_text:
        return None
    default_texts = [
        "Medical file will appear here after analysis",
        "Group therapy session transcript will appear here",
        "Relationship agreement notes will appear here",
        "Error"
    ]
    if any(dt in report_text for dt in default_texts):
        return None
        
    from fpdf import FPDF
    import tempfile
    import os

    # Dynamic safe filename matching target formatting exactly
    if mode == "individual":
        clean_name = re.sub(r'[^a-zA-Z0-9_\-]', '', bug_name_or_comp_a.strip().replace(' ', '_'))
        filename = f"{clean_name if clean_name else 'Bug'}_CaseFile.pdf"
    elif mode == "group":
        filename = "GroupTherapy_Report.pdf"
    elif mode == "relationship":
        filename = "RelationshipCounseling_Report.pdf"
    else:
        filename = "Therapy_Report.pdf"
        
    # Write to unique subdirectory to completely prevent permission locks
    temp_sub = tempfile.mkdtemp(prefix="bug_pdf_")
    path = os.path.join(temp_sub, filename)

    # PDF Configuration
    pdf = FPDF()
    pdf.add_page()
    pdf.set_margins(20, 20, 20)
    pdf.set_auto_page_break(auto=True, margin=20)

    # Clinic letterhead in clinical typewriter Courier
    pdf.set_font("Courier", "B", 16)
    pdf.cell(0, 10, "BUG THERAPY CLINIC", new_x="LMARGIN", new_y="NEXT", align="C")
    pdf.set_font("Courier", "", 9)
    pdf.cell(0, 5, "LICENSED SOFTWARE PSYCHOLOGISTS | CASE FILE CONFIDENTIAL", new_x="LMARGIN", new_y="NEXT", align="C")
    pdf.ln(4)
    pdf.line(20, pdf.get_y(), 190, pdf.get_y())
    pdf.ln(8)
    
    # Metadata Block
    date_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    pdf.set_font("Courier", "", 9)
    pdf.cell(0, 5, f"DATE OF SESSION: {date_str}", new_x="LMARGIN", new_y="NEXT")
    pdf.cell(0, 5, f"THERAPY CLASSIFICATION: {mode.upper()} INTERVENTION", new_x="LMARGIN", new_y="NEXT")
    pdf.cell(0, 5, "STATUS: ARCHIVED NOTES", new_x="LMARGIN", new_y="NEXT")
    pdf.ln(6)
    pdf.line(20, pdf.get_y(), 190, pdf.get_y())
    pdf.ln(8)

    # Parsing report
    lines = report_text.split("\n")
    for line in lines:
        line = clean_txt_for_pdf(line.strip())
        if not line:
            continue
        
        # Draw clean solid partition lines for markdown horizontal dividers
        if line.startswith("---") or line.startswith("___") or (line.startswith("-") and len(line) > 5):
            pdf.ln(3)
            pdf.line(20, pdf.get_y(), 190, pdf.get_y())
            pdf.ln(5)
            continue

        # Heading 1
        if line.startswith("# "):
            pdf.ln(4)
            pdf.set_font("Courier", "B", 13)
            content = line.replace("# ", "").strip()
            pdf.cell(0, 8, content, new_x="LMARGIN", new_y="NEXT")
            pdf.set_font("Courier", "", 10)
            pdf.ln(2)
        
        # Bold labels
        elif line.startswith("**"):
            pdf.ln(1)
            parts = line.split("**")
            if len(parts) >= 3:
                pdf.set_font("Courier", "B", 10)
                pdf.write(6, parts[1] + ": ")
                pdf.set_font("Courier", "", 10)
                pdf.write(6, "".join(parts[2:]).strip() + "\n")
            else:
                pdf.set_font("Courier", "", 10)
                pdf.multi_cell(0, 6, line.replace("**", ""))
            pdf.ln(2)
            
        # Monospace bullet points
        elif line.startswith("* ") or line.startswith("- "):
            pdf.set_font("Courier", "", 10)
            content = line[2:].strip()
            pdf.multi_cell(0, 6, f"  * {content}")
            pdf.ln(1)
            
        else:
            pdf.set_font("Courier", "", 10)
            pdf.multi_cell(0, 6, line)
            pdf.ln(1.5)

    pdf.output(path)
    return path

# Simulated section-by-section progress stream generators
def run_therapy_individual_stream(bug_text, personality="None"):
    with concurrent.futures.ThreadPoolExecutor() as executor:
        future = executor.submit(run_therapy_individual, bug_text, personality)
        stages = [
            ("⏳ Case File", "⏳ Trauma History", "⏳ Therapy Session", "⏳ Treatment Plan"),
            ("βœ“ Case File", "⏳ Trauma History", "⏳ Therapy Session", "⏳ Treatment Plan"),
            ("βœ“ Case File", "βœ“ Trauma History", "⏳ Therapy Session", "⏳ Treatment Plan"),
            ("βœ“ Case File", "βœ“ Trauma History", "βœ“ Therapy Session", "⏳ Treatment Plan"),
            ("βœ“ Case File", "βœ“ Trauma History", "βœ“ Therapy Session", "βœ“ Treatment Plan")
        ]
        stage_idx = 0
        while not future.done():
            progress_md = f"""# Consulting Patient...

--------------------------------

{stages[stage_idx][0]}
{stages[stage_idx][1]}
{stages[stage_idx][2]}
{stages[stage_idx][3]}
"""
            yield progress_md
            time.sleep(1.5)
            if stage_idx < len(stages) - 1:
                stage_idx += 1
        try:
            yield future.result()
        except Exception as e:
            yield f"# Case File\n\nPatient:\n{bug_text}\n\n--------------------------------\n\n# Error\n\nTherapy interrupted: {str(e)}"

def run_therapy_group_stream(bugs_text):
    with concurrent.futures.ThreadPoolExecutor() as executor:
        future = executor.submit(run_therapy_group, bugs_text)
        stages = [
            ("⏳ Case File: Group Circle", "⏳ Circle Dynamics", "⏳ Therapy Session", "⏳ Group Treatment Plan"),
            ("βœ“ Case File: Group Circle", "⏳ Circle Dynamics", "⏳ Therapy Session", "⏳ Group Treatment Plan"),
            ("βœ“ Case File: Group Circle", "βœ“ Circle Dynamics", "⏳ Therapy Session", "⏳ Group Treatment Plan"),
            ("βœ“ Case File: Group Circle", "βœ“ Circle Dynamics", "βœ“ Therapy Session", "⏳ Group Treatment Plan"),
            ("βœ“ Case File: Group Circle", "βœ“ Circle Dynamics", "βœ“ Therapy Session", "βœ“ Group Treatment Plan")
        ]
        stage_idx = 0
        while not future.done():
            progress_md = f"""# Group Session In Progress...

--------------------------------

{stages[stage_idx][0]}
{stages[stage_idx][1]}
{stages[stage_idx][2]}
{stages[stage_idx][3]}
"""
            yield progress_md
            time.sleep(1.5)
            if stage_idx < len(stages) - 1:
                stage_idx += 1
        try:
            yield future.result()
        except Exception as e:
            yield f"# Case File: Group Circle\n\n--------------------------------\n\n# Error\n\nGroup therapy interrupted: {str(e)}"

def run_therapy_relationship_stream(component_a, component_b, conflict):
    with concurrent.futures.ThreadPoolExecutor() as executor:
        future = executor.submit(run_therapy_relationship, component_a, component_b, conflict)
        stages = [
            ("⏳ Case File: Couples Counseling", "⏳ Relationship Status", "⏳ Therapy Session", "⏳ Relationship Agreement"),
            ("βœ“ Case File: Couples Counseling", "⏳ Relationship Status", "⏳ Therapy Session", "⏳ Relationship Agreement"),
            ("βœ“ Case File: Couples Counseling", "βœ“ Relationship Status", "⏳ Therapy Session", "⏳ Relationship Agreement"),
            ("βœ“ Case File: Couples Counseling", "βœ“ Relationship Status", "βœ“ Therapy Session", "⏳ Relationship Agreement"),
            ("βœ“ Case File: Couples Counseling", "βœ“ Relationship Status", "βœ“ Therapy Session", "βœ“ Relationship Agreement")
        ]
        stage_idx = 0
        while not future.done():
            progress_md = f"""# Relationship Mediation In Progress...

--------------------------------

{stages[stage_idx][0]}
{stages[stage_idx][1]}
{stages[stage_idx][2]}
{stages[stage_idx][3]}
"""
            yield progress_md
            time.sleep(1.5)
            if stage_idx < len(stages) - 1:
                stage_idx += 1
        try:
            yield future.result()
        except Exception as e:
            yield f"# Case File: Couples Counseling\n\n--------------------------------\n\n# Error\n\nCouples therapy interrupted: {str(e)}"

# Build Gradio UI
with gr.Blocks(title="bug therapist") as demo:
    
    # Header Section
    gr.HTML(
        """
        <div style="text-align: center; padding: 24px 0 12px 0;">
            <h1 class="clinical-title">bug therapist</h1>
            <p class="clinical-subtitle">clinical psychoanalysis for software defects.</p>
        </div>
        """
    )

    with gr.Tabs(elem_classes="tabs") as tabs:
        
        # TAB 1: Individual Session
        with gr.Tab("Individual Therapy", id=1):
            with gr.Row():
                with gr.Column(scale=1):
                    ind_bug_input = gr.Textbox(
                        label="admit patient (paste stack trace, code snippet, or error log)",
                        lines=8,
                        placeholder="e.g. java.lang.NullPointerException: Attempt to invoke virtual method..."
                    )
                    
                    ind_personality = gr.Dropdown(
                        choices=[
                            "None",
                            "Abandonment issues (feeling ignored by developer)",
                            "Control freak (compulsion to govern all processing states)",
                            "Commitment issues (refusal to resolve callback/promise states)",
                            "Identity crisis (type instability, constant casting errors)",
                            "Attention seeker (verbose logs, printing internal operations)",
                            "Existential dread (cycles of execution without clear intent)"
                        ],
                        value="None",
                        label="Choose a Trauma (Optional)",
                        info="Leave blank and the therapist will diagnose automatically."
                    )
                    
                    with gr.Column():
                        ind_btn = gr.Button("diagnose bug", elem_classes=["diagnose-btn"])
                    
                with gr.Column(scale=1):
                    ind_output = gr.Markdown(
                        value="*Medical file will appear here after analysis.*",
                        elem_classes=["patient-file-container"]
                    )
                    
                    # Normal button that triggers hidden DownloadButton click
                    ind_export_btn = gr.Button("download case report pdf", elem_classes=["export-btn"])

            gr.Examples(
                examples=[
                    ["NullPointerException", "Abandonment issues (feeling ignored by developer)"],
                    ["Memory Leak in loop", "Control freak (compulsion to govern all processing states)"],
                    ["Segmentation Fault", "Existential dread (cycles of execution without clear intent)"],
                    ["RecursionError: maximum recursion depth exceeded", "Identity crisis (type instability, constant casting errors)"]
                ],
                inputs=[ind_bug_input, ind_personality],
                label="common admissions",
                cache_examples=False
            )

        # TAB 2: Group Therapy
        with gr.Tab("Group Therapy", id=2):
            with gr.Row():
                with gr.Column(scale=1):
                    # Preset triggers right above textbox
                    gr.Markdown("Quick admission presets:")
                    with gr.Row():
                        preset_classic = gr.Button("classic trio", elem_classes=["pill-btn"])
                        preset_concurrency = gr.Button("concurrency crisis", elem_classes=["pill-btn"])
                        preset_boundary = gr.Button("boundary conflict", elem_classes=["pill-btn"])
                    
                    gr.HTML("<div style='height: 10px;'></div>")
                    
                    group_circle_name = gr.Textbox(
                        label="selected circle preset",
                        interactive=False,
                        placeholder="Select a preset circle or enter custom bugs below"
                    )
                    
                    group_bugs_input = gr.Textbox(
                        label="admit patient group (separated by commas)",
                        lines=6,
                        placeholder="e.g. NullPointerException, Memory Leak, Segmentation Fault"
                    )
                    
                    with gr.Column():
                        group_btn = gr.Button("counsel group", elem_classes=["diagnose-btn"])
                    
                with gr.Column(scale=1):
                    group_output = gr.Markdown(
                        value="*Group therapy session transcript will appear here.*",
                        elem_classes=["patient-file-container"]
                    )
                    
                    # Normal button that triggers hidden DownloadButton click
                    group_export_btn = gr.Button("download group report pdf", elem_classes=["export-btn"])

            # Map quick preset buttons
            preset_classic.click(
                fn=lambda: ("Classic Trio", "NullPointerException, Memory Leak, Segmentation Fault"),
                inputs=None,
                outputs=[group_circle_name, group_bugs_input]
            )
            preset_concurrency.click(
                fn=lambda: ("Concurrency Crisis", "Deadlock, Race Condition, Thread Leak"),
                inputs=None,
                outputs=[group_circle_name, group_bugs_input]
            )
            preset_boundary.click(
                fn=lambda: ("Boundary Conflict", "Segmentation Fault, IndexOutOfBoundsException, OffByOneError"),
                inputs=None,
                outputs=[group_circle_name, group_bugs_input]
            )

            # Standard Circles dynamic dataframe
            group_history_df = gr.Dataframe(
                headers=["Circle Name", "Bugs"],
                datatype=["str", "str"],
                value=[
                    ["Classic Trio", "NullPointerException, Memory Leak, Segmentation Fault"],
                    ["Concurrency Crisis", "Deadlock, Race Condition, Thread Leak"],
                    ["Boundary Conflict", "Segmentation Fault, IndexOutOfBoundsException, OffByOneError"]
                ],
                interactive=False,
                label="standard circles"
            )

            group_history_df.select(
                fn=select_group_row,
                inputs=[group_history_df],
                outputs=[group_circle_name, group_bugs_input]
            )

        # TAB 3: Relationship Counseling
        with gr.Tab("Relationship Counseling", id=3):
            with gr.Row():
                with gr.Column(scale=1):
                    gr.Markdown("Quick relationship presets:")
                    with gr.Row():
                        preset_api = gr.Button("api friction", elem_classes=["pill-btn"])
                        preset_nesting = gr.Button("nested hell", elem_classes=["pill-btn"])
                        preset_history = gr.Button("force pushing", elem_classes=["pill-btn"])
                        
                    gr.HTML("<div style='height: 10px;'></div>")
                    
                    rel_comp_a = gr.Textbox(
                        label="component a",
                        placeholder="e.g. React Frontend"
                    )
                    rel_comp_b = gr.Textbox(
                        label="component b",
                        placeholder="e.g. Django Backend"
                    )
                    rel_conflict = gr.Textbox(
                        label="architectural conflict description",
                        lines=4,
                        placeholder="e.g. component a queries component b relentlessly; component b returns silent timeouts."
                    )
                    
                    with gr.Column():
                        rel_btn = gr.Button("counsel couple", elem_classes=["diagnose-btn"])
                    
                with gr.Column(scale=1):
                    rel_output = gr.Markdown(
                        value="*Relationship agreement notes will appear here.*",
                        elem_classes=["patient-file-container"]
                    )
                    
                    # Normal button that triggers hidden DownloadButton click
                    rel_export_btn = gr.Button("download couples report pdf", elem_classes=["export-btn"])

            # Map quick relationship presets
            preset_api.click(
                fn=lambda: ("React Frontend", "Django Backend", "Frontend floods backend with requests"),
                inputs=None,
                outputs=[rel_comp_a, rel_comp_b, rel_conflict]
            )
            preset_nesting.click(
                fn=lambda: ("Callback", "Promise", "Communication delays and trust issues"),
                inputs=None,
                outputs=[rel_comp_a, rel_comp_b, rel_conflict]
            )
            preset_history.click(
                fn=lambda: ("Git CLI", "Developer", "Force pushes without communication"),
                inputs=None,
                outputs=[rel_comp_a, rel_comp_b, rel_conflict]
            )

            # Troubled Couplings dynamic dataframe
            couples_history_df = gr.Dataframe(
                headers=["Component A", "Component B", "Conflict"],
                datatype=["str", "str", "str"],
                value=[
                    ["React Frontend", "Django Backend", "Frontend floods backend with requests"],
                    ["Git CLI", "Developer", "Force pushes without communication"],
                    ["Microservice A", "Microservice B", "Circular dependency blame game"],
                    ["Callback", "Promise", "Communication delays and trust issues"]
                ],
                interactive=False,
                label="troubled couplings"
            )

            couples_history_df.select(
                fn=select_couples_row,
                inputs=[couples_history_df],
                outputs=[rel_comp_a, rel_comp_b, rel_conflict]
            )

    # Hidden download buttons to execute reliable one-click download stream via event trigger
    ind_download_hidden = gr.DownloadButton("Download Hidden 1", elem_id="ind_download_hidden")
    group_download_hidden = gr.DownloadButton("Download Hidden 2", elem_id="group_download_hidden")
    rel_download_hidden = gr.DownloadButton("Download Hidden 3", elem_id="rel_download_hidden")

    # Event handlers
    
    # 1. Individual
    ind_btn.click(
        run_therapy_individual_stream,
        inputs=[ind_bug_input, ind_personality],
        outputs=ind_output,
        show_progress="minimal"
    )
    ind_export_btn.click(
        fn=lambda report, bug: generate_pdf_report(report, "individual", bug),
        inputs=[ind_output, ind_bug_input],
        outputs=ind_download_hidden,
        show_progress="minimal"
    ).then(
        fn=None,
        inputs=None,
        outputs=None,
        js="() => { const link = document.querySelector('#ind_download_hidden a') || document.querySelector('#ind_download_hidden'); if (link) link.click(); }"
    )

    # 2. Group
    group_btn.click(
        run_therapy_group_stream,
        inputs=[group_bugs_input],
        outputs=group_output,
        show_progress="minimal"
    ).then(
        fn=add_group_to_history,
        inputs=[group_circle_name, group_bugs_input, group_history_df],
        outputs=group_history_df
    )
    group_export_btn.click(
        fn=lambda report: generate_pdf_report(report, "group"),
        inputs=group_output,
        outputs=group_download_hidden,
        show_progress="minimal"
    ).then(
        fn=None,
        inputs=None,
        outputs=None,
        js="() => { setTimeout(() => { const link = document.querySelector('#group_download_hidden a') || document.querySelector('#group_download_hidden'); if (link) link.click(); }, 150); }"
    )

    # 3. Relationship
    rel_btn.click(
        run_therapy_relationship_stream,
        inputs=[rel_comp_a, rel_comp_b, rel_conflict],
        outputs=rel_output,
        show_progress="minimal"
    ).then(
        fn=add_couples_to_history,
        inputs=[rel_comp_a, rel_comp_b, rel_conflict, couples_history_df],
        outputs=couples_history_df
    )
    rel_export_btn.click(
        fn=lambda report, a, b: generate_pdf_report(report, "relationship", a, b),
        inputs=[rel_output, rel_comp_a, rel_comp_b],
        outputs=rel_download_hidden,
        show_progress="minimal"
    ).then(
        fn=None,
        inputs=None,
        outputs=None,
        js="() => { const link = document.querySelector('#rel_download_hidden a') || document.querySelector('#rel_download_hidden'); if (link) link.click(); }"
    )

# Launch app locally
if __name__ == "__main__":
    demo.launch(css=custom_css)