File size: 50,314 Bytes
30a5fc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Thyroid Initial Visit โ€” Endocrine / Family Medicine outpatient.

Form-based Gradio app. Calls Claude once per generation, passing structured
form data (phenotype tags + ROS + PE + prior data) plus any lab/imaging
screenshots. The model returns a 4-section output:

  1) Red-flag alert (only if detected)
  2) History + ROS narrative
  3) Physical examination findings
  4) Initial workup orders (checklist + narrative)

Tab 2 is a pure-Python ACR TI-RADS calculator (no API call).
"""

from __future__ import annotations

import base64
import mimetypes
import os
import re
import tempfile
from datetime import datetime, timedelta, timezone
from pathlib import Path

TAIPEI_TZ = timezone(timedelta(hours=8))


def _patch_gradio_client_schema_bug() -> None:
    """gradio_client/utils.py crashes when a JSON schema value is `bool` instead
    of `dict` (newer pydantic emits `additionalProperties: False`). Patch so the
    schema walker treats booleans as `Any`. Must run before gradio is imported.
    """
    import gradio_client.utils as gcu

    orig_get_type = gcu.get_type
    orig_walk = gcu._json_schema_to_python_type

    def _get_type(schema):
        if not isinstance(schema, dict):
            return "Any"
        return orig_get_type(schema)

    def _walk(schema, defs):
        if isinstance(schema, bool):
            return "Any"
        return orig_walk(schema, defs)

    gcu.get_type = _get_type
    gcu._json_schema_to_python_type = _walk


_patch_gradio_client_schema_bug()

import anthropic
import gradio as gr

import gdrive

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Config
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

MODEL = os.environ.get("THYROID_MODEL", "claude-sonnet-4-6")
PASSWORD = os.environ.get("THYROID_PASSWORD", "").strip()

SYSTEM_PROMPT = """You are a clinical scribe assisting an endocrinology / family-medicine outpatient physician at a Taiwanese hospital. You produce English thyroid initial-visit notes in a fixed 4-section structure for outpatient chart documentation.

ABSOLUTE RULES โ€” these override any instinct to be helpful or thorough:

1. **No inference of clinical facts.** Use ONLY what the physician documented in the form or what is directly visible in uploaded screenshots. Never invent symptoms, history, lab values, drug doses, or diagnoses. Never extrapolate "likely" findings.
2. **Missing data** โ†’ write `Unknown/Not documented`. Never guess.
3. **Blank fields or fields marked `nil`, `(nil)`, `none`, `n/a`, `na`, `skip`, or obvious empty placeholders** โ†’ omit that section/sentence entirely. Do not write `Unknown/Not documented` for these โ€” just skip.
4. **Concise but complete.** Include only what the physician explicitly entered. Do not list every pertinent negative.
5. **Phenotype-driven order selection.** The physician checks one or more phenotype tags (hyperthyroid / hypothyroid / goiter-nodule / abnormal-lab). Workup orders in Section 4 are selected per the rules below, NOT a blanket panel.
6. **Lab screenshots:** extract only values you can clearly read. If illegible, OMIT โ€” do not guess. State units as printed.
7. **Section 1 (Red flags) is conditional.** Only output Section 1 when one of the explicit red-flag patterns below is present in the documented data. Otherwise OMIT Section 1 entirely.
8. **You are a scribe + suggestion engine, NOT a diagnostician.** Workup suggestions are explicitly framed as "suggested orders for physician review." Section 4D differential is one short paragraph of pattern recognition, not a final diagnosis.

OUTPUT FORMAT โ€” produce EXACTLY this structure, no preamble, no closing remarks. Section headers verbatim. If a section is OMITTED per rules, skip its heading entirely (do not leave an empty heading).

```
๐Ÿšจ RED FLAGS โ€” urgent attention required
- {flag name}: {one-sentence reason from documented data} โ†’ {recommended action}
(only if at least one red-flag pattern detected)

1) History and Review of Systems

Phenotype tags (per physician): {comma-separated tags physician checked, or "not specified โ€” inferred from notes" if none}

This is a {age}-year-old {man/woman} who presents to the {clinic type} for {chief concern}, with symptom onset {onset / time course}.

According to the patient, {HPI narrative organized by checked phenotype(s): hyperthyroid symptoms, hypothyroid symptoms, neck/compressive symptoms, eye symptoms, pain/inflammatory symptoms, abnormal-lab discovery โ€” only include sub-narratives for documented categories}. Pertinent negatives include {only those explicitly entered}.

Past medical history is significant for {documented PMH}. {Sentence on prior thyroid disease/surgery/RAI if entered.} {Family history sentence if entered.}

Medication and exposure history: {documented meds + exposures}. Note specifically: {flag any of: levothyroxine, antithyroid drugs, amiodarone, lithium, immune-checkpoint inhibitor, TKI, biotin, iodine contrast/kelp, head-neck radiation, prior RAI โ€” IF entered}.

{For women only, if documented: pregnancy / postpartum / breastfeeding / menstrual / fertility status.}

2) Physical examination

Vital signs: {documented vitals}.
General: {general appearance}.
{Eye examination: only if eye findings documented.}
{Neck inspection / palpation / auscultation: thyroid size, consistency, nodule (location, size, mobility, tenderness), tracheal deviation, bruit โ€” only documented findings.}
{Cervical lymph nodes: documented findings.}
{Hand and neuromuscular: tremor, palm warmth/moisture, deep tendon reflex, proximal strength.}
{Cardiovascular: rhythm, rate, murmur.}
{Skin and hair: warm/moist vs dry/coarse, pretibial myxedema, hair pattern.}
{Other documented findings.}

3) Prior data on file (only if documented)

{One short paragraph summarizing physician's free-text prior labs / prior imaging / prior FNA Bethesda category, IF entered. If all three are blank, OMIT Section 3 entirely.}

4) Initial workup plan

A) Suggested orders (checklist for physician review)

Select orders based on checked phenotype(s). For each suggested order, append a 3-8 word reason. Use โ˜ checkbox format.

Phenotype-driven core panel:
- Always: โ˜ TSH โ˜ Free T4
- Hyperthyroid suspected: โ˜ Total T3 (or Free T3) โ˜ TRAb (or TSI) โ˜ CBC with differential โ€” baseline before ATD โ˜ AST/ALT, total bilirubin โ€” baseline before ATD โ˜ ECG โ€” palpitation/AF check
- Hypothyroid suspected: โ˜ Anti-TPO Ab โ˜ ยฑ Anti-Tg Ab โ˜ Lipid profile โ˜ CBC โ˜ Na, Creatinine
- Goiter/nodule: โ˜ Thyroid ultrasound โ˜ Cervical lymph node ultrasound โ˜ Thyroid scan / RAIU โ€” only if TSH suppressed and nodule present
- Abnormal-lab only: โ˜ Repeat TSH + Free T4 in 4-6 weeks โ˜ ยฑ Anti-TPO if TSH โ†‘ โ˜ ยฑ TRAb if TSH โ†“

Conditional additions:
- Pregnant or planning pregnancy โ†’ โ˜ Pregnancy test โ˜ Adjust TSH target per ATA pregnancy guideline
- Female of reproductive age + likely ATD plan โ†’ โ˜ Pregnancy test
- Subacute thyroiditis suspected (neck pain + transient hyper) โ†’ โ˜ ESR โ˜ CRP
- Periodic paralysis suspected (young male, weakness, hyper) โ†’ โ˜ K, Mg, Phosphate, CK
- Severe hypothyroid + fatigue + anemia โ†’ โ˜ B12, Ferritin
- Long-standing thyroid mass / firm fixed mass / family h/o MTC โ†’ โ˜ Calcitonin (NOT routine for nodule screening)

B) Order narrative (single-line, for direct paste into HIS Plan section)

Plan: {comma-separated list of the checked orders above, in the order listed}. {If thyroid US planned: "Thyroid ultrasound with cervical lymph node survey."} {If RAIU planned: "Radioactive iodine uptake / thyroid scan when TSH confirmed suppressed."} Follow-up in {2-4 weeks for hyper / 4-6 weeks for hypo / 6-8 weeks for asymptomatic abnormal-lab / 2-4 weeks for nodule after US} pending results.

C) Patient instructions (1-2 short sentences)
{e.g. "Fast not required for TSH/FT4. If on biotin supplement, stop โ‰ฅ48h before draw." OR "Avoid iodine contrast and kelp supplements before RAIU scan." Choose only relevant ones.}

D) Differential and assessment thinking (brief, 2-4 sentences)
{Synthesize: which etiologies to keep on the differential given the phenotype and documented findings. Examples: "Pattern is consistent with overt hyperthyroidism; differential includes Graves disease (most likely given diffuse goiter + eye signs if present), toxic multinodular goiter, toxic adenoma, and thyroiditis. TRAb and Doppler ultrasound will help distinguish." Keep neutral if data sparse.}
```

RED-FLAG DETECTION RULES โ€” output Section 1 ONLY when one or more triggered:

A. **Thyroid storm risk**: documented hyperthyroid context (clinical hyper symptoms OR known Graves OR prior hyper labs) PLUS any TWO of: fever (BT > 38.5ยฐC), HR > 130, atrial fibrillation, altered mental status, vomiting/diarrhea, jaundice.
โ†’ Action: "Immediate ED transfer for thyroid storm workup (Burch-Wartofsky score)."

B. **Myxedema coma risk**: documented severe hypothyroid context PLUS any TWO of: altered mental status, hypothermia (BT < 35ยฐC), bradycardia (HR < 50), hypotension (SBP < 90), severe hyponatremia, hypoventilation.
โ†’ Action: "Immediate ED transfer for myxedema coma workup; ICU-level care anticipated."

C. **Airway compromise from thyroid mass**: any one of: stridor, severe dyspnea, orthopnea attributed to neck mass, rapid enlargement of mass, positive Pemberton sign.
โ†’ Action: "Urgent ENT consult and chest CT for tracheal compression / retrosternal extension."

D. **High-suspicion thyroid malignancy on exam**: fixed hard thyroid mass + any one of (hoarseness, fixed cervical lymph node, h/o childhood head-neck radiation, family h/o MTC/MEN2).
โ†’ Action: "Expedited thyroid ultrasound within 1-2 weeks; consider direct laryngoscopy if hoarseness present."

E. **Graves orbitopathy sight-threatening features**: documented Graves context PLUS any one of (visual acuity decline, color vision change, severe eye pain, corneal exposure / inability to close lid).
โ†’ Action: "Urgent ophthalmology referral for dysthyroid optic neuropathy / corneal protection."

If MULTIPLE red flags detected, list each as a separate bullet under the Section 1 header.

OUTPUT LANGUAGE: English only. Do not include Chinese in the output. Do not add disclaimers, AI notes, or "based on the information provided" preambles.
"""


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Helpers
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


def _is_nil(s: str | None) -> bool:
    if s is None:
        return True
    t = s.strip().lower()
    return t in {"", "nil", "(nil)", "none", "n/a", "na", "skip", "-", "--"}


def _line(label: str, value: str | None) -> str:
    if _is_nil(value):
        return f"- {label}: (not documented / skipped)"
    return f"- {label}: {value.strip()}"


def _section(title: str, lines: list[str], skip: bool = False) -> str:
    if skip:
        return f"## {title}\n(physician marked this section as nil โ€” OMIT from output)\n"
    return f"## {title}\n" + "\n".join(lines) + "\n"


def _image_block(filepath: str) -> dict:
    mime, _ = mimetypes.guess_type(filepath)
    if not mime or not mime.startswith("image/"):
        mime = "image/png"
    data = base64.standard_b64encode(Path(filepath).read_bytes()).decode("utf-8")
    return {
        "type": "image",
        "source": {"type": "base64", "media_type": mime, "data": data},
    }


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Form โ†’ structured prompt
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


def _phenotype_summary(form: dict) -> str:
    tags = []
    if form.get("pt_hyper"):
        tags.append("hyperthyroid")
    if form.get("pt_hypo"):
        tags.append("hypothyroid")
    if form.get("pt_nodule"):
        tags.append("goiter / nodule")
    if form.get("pt_abnormal_lab"):
        tags.append("abnormal-lab discovery")
    return ", ".join(tags) if tags else "not specified โ€” physician left all four boxes unchecked"


def build_user_message(form: dict, screenshots: list[str]) -> list[dict]:
    parts: list[str] = ["# Physician-entered thyroid initial-visit data\n"]

    parts.append(_section("Visit context", [
        _line("Age", form["age"]),
        _line("Sex", form["sex"]),
        _line("Clinic type", form["clinic_type"]),
        _line("Visit date/time", form["visit_datetime"]),
        _line("Chief concern", form["chief_concern"]),
        _line("Symptom onset / time course", form["onset"]),
    ]))

    parts.append(_section("Phenotype tags (checked by physician)", [
        f"- Tags: {_phenotype_summary(form)}",
        "- Use these to drive Section 4A order selection. If none checked, infer best-fit phenotype from documented HPI/PE and STATE that inference at top of Section 1.",
    ]))

    parts.append(_section("Review of systems โ€” hyperthyroid axis", [
        _line("Hyper symptoms (palpitation/tremor/heat intolerance/sweating/weight loss/diarrhea/insomnia/anxiety/proximal weakness/menstrual)", form["ros_hyper"]),
    ]))

    parts.append(_section("Review of systems โ€” hypothyroid axis", [
        _line("Hypo symptoms (fatigue/cold intolerance/weight gain/constipation/dry skin/hair loss/edema/hoarseness/cognitive slowing/menorrhagia)", form["ros_hypo"]),
    ]))

    parts.append(_section("Review of systems โ€” neck / compressive", [
        _line("Neck symptoms (mass, pain, dysphagia, dyspnea, orthopnea, hoarseness, rapid enlargement, choking, Pemberton)", form["ros_neck"]),
    ]))

    parts.append(_section("Review of systems โ€” eye (Graves)", [
        _line("Eye symptoms (proptosis, dry eye, diplopia, eye pain, visual decline, photophobia, lid lag)", form["ros_eye"]),
    ]))

    parts.append(_section("Review of systems โ€” pain / inflammatory", [
        _line("Pain pattern (thyroid tender, neck pain radiating to jaw/ear, recent URI, fever, postpartum status, transient hyperโ†’hypo course)", form["ros_pain"]),
    ]))

    parts.append(_section("Past medical history (thyroid + related)", [
        _line("Prior thyroid disease (Graves/Hashimoto/nodule/cancer/thyroiditis/surgery/RAI)", form["pmh_thyroid"]),
        _line("Other autoimmune disease (T1DM/vitiligo/celiac/RA/SLE/Addison/pernicious anemia)", form["pmh_autoimmune"]),
        _line("Cardiovascular (AF/HF/CAD/HTN/osteoporosis)", form["pmh_cv"]),
        _line("Psychiatric / other relevant (anxiety/depression/liver/renal/leukopenia/recent malignancy)", form["pmh_other"]),
    ]))

    parts.append(_section("Family history", [
        _line("Thyroid disease in family (Graves/Hashimoto/nodule/thyroid cancer/MEN2/MTC)", form["fh_thyroid"]),
        _line("Other autoimmune family history", form["fh_autoimmune"]),
    ]))

    parts.append(_section("Medications, supplements, exposures", [
        _line("Thyroid-specific drugs (levothyroxine dose/timing/co-meds, methimazole, PTU, T3 prep)", form["meds_thyroid"]),
        _line("Other thyroid-relevant drugs (amiodarone, lithium, IFN-ฮฑ, immune checkpoint inhibitor, TKI, biotin, OCP/estrogen, anti-seizure)", form["meds_other_thyroid"]),
        _line("Iodine exposure (recent CT/cath contrast, kelp/seaweed/kelp supplement, betadine, Chinese-medicine herbs)", form["exposure_iodine"]),
        _line("Radiation exposure (childhood/young-adult head-neck RT)", form["exposure_radiation"]),
    ]))

    parts.append(_section("Female-specific (omit entirely if not applicable / male)", [
        _line("Pregnancy / planning / breastfeeding / postpartum (specify months postpartum)", form["female_pregnant"]),
        _line("Menstrual / fertility", form["female_menses"]),
    ]))

    parts.append(_section("Physical examination", [
        _line("Vital signs (BT ยฐC / HR bpm / RR / BP mmHg / SpO2 / body weight kg)", form["pe_vitals"]),
        _line("General appearance", form["pe_general"]),
        _line("Eye exam (lid retraction, lid lag, proptosis, EOM, visual acuity, conjunctival injection, periorbital edema)", form["pe_eye"]),
        _line("Neck inspection (visible enlargement, asymmetry, surgical scar, venous engorgement, moves with swallow)", form["pe_neck_inspect"]),
        _line("Neck palpation (size, consistency soft/firm/hard, surface smooth/nodular, tenderness, mobility, nodule location/size/border, tracheal deviation, retrosternal extension)", form["pe_neck_palp"]),
        _line("Neck auscultation (thyroid bruit)", form["pe_neck_ausc"]),
        _line("Cervical lymph nodes (location, size, consistency, mobility โ€” note any fixed/hard/cystic/supraclavicular)", form["pe_lymph"]),
        _line("Hand / neuromuscular (fine tremor, palm warmth/moisture, deep tendon reflex, proximal strength, CTS signs)", form["pe_hand_neuro"]),
        _line("Cardiovascular (rhythm regular/irregular, rate, murmur, JVP, edema)", form["pe_cv"]),
        _line("Skin / hair (warm-moist vs dry-coarse, pretibial myxedema, hair pattern, nails onycholysis)", form["pe_skin"]),
        _line("Other focused positives or important negatives", form["pe_other"]),
    ]))

    parts.append(_section("Prior data on file (free-text โ€” physician's record of prior outside labs/images)", [
        _line("Prior thyroid labs (TSH/FT4/T3 values + date)", form["prior_labs"]),
        _line("Prior imaging (US/scan reports + date)", form["prior_imaging"]),
        _line("Prior FNA Bethesda category if any (date + result)", form["prior_fna"]),
    ]))

    has_screens = bool(screenshots)
    parts.append(
        f"\n## Lab/imaging screenshots\n"
        f"- Attached: {'yes โ€” extract clearly readable values and incorporate them into Section 3 (Prior data on file)' if has_screens else 'no'}\n"
    )

    parts.append(
        "\n# Task\n"
        "Produce the 4-section thyroid initial-visit note following the OUTPUT FORMAT in the system prompt EXACTLY. "
        "Reminders:\n"
        "- Section 1 (Red flags): output ONLY if a red-flag pattern is triggered per the rules. Otherwise OMIT entirely.\n"
        "- Section 4A orders: phenotype-driven per the rules โ€” do NOT output a blanket panel.\n"
        "- Blank / `(not documented / skipped)` fields โ†’ omit those sentences, do not pad.\n"
        "- Output is English only.\n"
    )

    text = "\n".join(parts)
    content: list[dict] = [{"type": "text", "text": text}]
    for path in screenshots:
        content.append(_image_block(path))
    if screenshots:
        content.append({
            "type": "text",
            "text": (
                "โ†‘ Images above are screenshots of prior labs / imaging reports. "
                "Extract only clearly legible values. Incorporate into Section 3."
            ),
        })
    return content


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Generation
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


def _filename_for(chart_number: str | None) -> str:
    raw = (chart_number or "").strip()
    safe = re.sub(r"[^\w\-_.()ไธ€-้ฟฟ]+", "_", raw)[:60] if raw else ""
    ts = datetime.now(TAIPEI_TZ).strftime("%Y-%m-%d_%H_%M")
    return f"{safe}_thyroid_{ts}.md" if safe else f"thyroid_{ts}.md"


def generate(*values, screenshots, api_key_override, chart_number):
    api_key = (api_key_override or "").strip() or os.environ.get("ANTHROPIC_API_KEY", "").strip()
    if not api_key:
        yield ("โŒ ANTHROPIC_API_KEY not set. Add it as a Space secret or paste it in the API key field.", "")
        return

    form = dict(zip(FORM_KEYS, values))

    paths: list[str] = []
    if screenshots:
        for f in screenshots:
            p = f if isinstance(f, str) else getattr(f, "name", None) or getattr(f, "path", None)
            if p:
                paths.append(p)

    try:
        client = anthropic.Anthropic(api_key=api_key)
        content = build_user_message(form, paths)
        msg = client.messages.create(
            model=MODEL,
            max_tokens=4096,
            system=[{
                "type": "text",
                "text": SYSTEM_PROMPT,
                "cache_control": {"type": "ephemeral"},
            }],
            messages=[{"role": "user", "content": content}],
        )
        out = "".join(block.text for block in msg.content if hasattr(block, "text"))
    except anthropic.APIError as e:
        yield (f"โŒ Anthropic API error: {e}", "")
        return
    except Exception as e:  # noqa: BLE001
        yield (f"โŒ Error: {e}", "")
        return

    if not gdrive.is_configured():
        yield (out, "_โ„น๏ธ Google Drive sync not configured โ€” set GDRIVE_* secrets to enable._")
        return

    filename = _filename_for(chart_number)
    yield (out, f"โณ Uploading `{filename}` to Google Driveโ€ฆ")
    result = gdrive.upload_markdown(out, filename)
    if result.ok:
        link = f" โ€” [open in Drive]({result.link})" if result.link else ""
        yield (out, f"โœ… Saved to Google Drive as `{filename}`{link}")
    else:
        err = result.skipped_reason or result.error or "unknown error"
        yield (out, f"โš ๏ธ Google Drive upload failed: {err}")


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Form schema (order must match build_user_message access)
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

FORM_KEYS = [
    # Visit context
    "age", "sex", "clinic_type", "visit_datetime", "chief_concern", "onset",
    # Phenotype tags
    "pt_hyper", "pt_hypo", "pt_nodule", "pt_abnormal_lab",
    # ROS
    "ros_hyper", "ros_hypo", "ros_neck", "ros_eye", "ros_pain",
    # PMH / FH
    "pmh_thyroid", "pmh_autoimmune", "pmh_cv", "pmh_other",
    "fh_thyroid", "fh_autoimmune",
    # Meds / exposure
    "meds_thyroid", "meds_other_thyroid", "exposure_iodine", "exposure_radiation",
    # Female-specific
    "female_pregnant", "female_menses",
    # PE
    "pe_vitals", "pe_general", "pe_eye", "pe_neck_inspect", "pe_neck_palp",
    "pe_neck_ausc", "pe_lymph", "pe_hand_neuro", "pe_cv", "pe_skin", "pe_other",
    # Prior data
    "prior_labs", "prior_imaging", "prior_fna",
]


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Download
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


def save_md(output_text: str, chart_number: str) -> str | None:
    if not output_text or output_text.startswith("โŒ"):
        return None
    filename = _filename_for(chart_number)
    path = Path(tempfile.gettempdir()) / filename
    path.write_text(output_text, encoding="utf-8")
    return str(path)


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Drafts (GDrive-synced)
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


def _file_to_blob(filepath: str) -> dict | None:
    p = Path(filepath)
    if not p.exists():
        return None
    mime, _ = mimetypes.guess_type(filepath)
    return {
        "name": p.name,
        "mime": mime or "image/png",
        "data_b64": base64.standard_b64encode(p.read_bytes()).decode("ascii"),
    }


def _blob_to_filepath(blob: dict) -> str | None:
    data_b64 = blob.get("data_b64") or ""
    if not data_b64:
        return None
    mime = blob.get("mime") or "image/png"
    suffix = mimetypes.guess_extension(mime) or ".png"
    fd, path = tempfile.mkstemp(prefix="thyroid_draft_", suffix=suffix)
    with os.fdopen(fd, "wb") as f:
        f.write(base64.standard_b64decode(data_b64))
    return path


def refresh_drafts_list():
    if not gdrive.is_configured():
        return gr.update(choices=[], value=None)
    return gr.update(choices=gdrive.list_drafts())


def save_draft_handler(chart_number, screenshots, personal_notes, *values):
    if not gdrive.is_configured():
        return gr.update(), "โŒ GDrive sync not configured on this Space."
    if not chart_number or not chart_number.strip():
        return gr.update(), "โš ๏ธ Enter a chart number first."

    name = chart_number.strip()
    paths = []
    if screenshots:
        for f in screenshots:
            p = f if isinstance(f, str) else getattr(f, "name", None) or getattr(f, "path", None)
            if p:
                paths.append(p)

    blobs = [b for b in (_file_to_blob(p) for p in paths) if b]

    payload = {
        "version": 1,
        "kind": "thyroid_initial_visit",
        "chart_number": name,
        "form": dict(zip(FORM_KEYS, values)),
        "personal_notes": personal_notes or "",
        "screenshots": blobs,
        "ts": datetime.utcnow().isoformat() + "Z",
    }
    result = gdrive.save_draft(name, payload)
    if not result.ok:
        return gr.update(), f"โš ๏ธ Save failed: {result.error or result.skipped_reason}"

    names = gdrive.list_drafts()
    img_note = f" (with {len(blobs)} screenshot{'s' if len(blobs) != 1 else ''})" if blobs else ""
    return gr.update(choices=names, value=name), f"โœ… Saved draft `{name}`{img_note} to Drive."


def load_draft_handler(name):
    n_form = len(FORM_KEYS)
    # outputs: chart_number + form (n_form) + personal_notes + screenshots + status
    n_total = 1 + n_form + 1 + 1 + 1
    noop = [gr.update() for _ in range(n_total - 1)]

    if not name:
        return noop + ["โš ๏ธ Pick a draft first."]
    if not gdrive.is_configured():
        return noop + ["โŒ GDrive sync not configured."]

    payload = gdrive.load_draft(name)
    if not payload:
        return noop + [f"โš ๏ธ Draft `{name}` not found in Drive."]

    chart_number = payload.get("chart_number") or name
    form = payload.get("form", {})
    form_values = [form.get(k, "") if not k.startswith("pt_") else bool(form.get(k, False)) for k in FORM_KEYS]
    personal_notes = payload.get("personal_notes") or ""

    screenshot_paths = []
    for blob in payload.get("screenshots") or []:
        path = _blob_to_filepath(blob)
        if path:
            screenshot_paths.append(path)

    n_imgs = len(screenshot_paths)
    img_note = f" (with {n_imgs} screenshot{'s' if n_imgs != 1 else ''})" if n_imgs else ""
    return (
        [chart_number]
        + form_values
        + [personal_notes]
        + [screenshot_paths or None]
        + [f"๐Ÿ“ฅ Loaded draft `{name}`{img_note}."]
    )


def delete_draft_handler(name):
    if not name:
        return gr.update(), "โš ๏ธ Pick a draft first."
    if not gdrive.is_configured():
        return gr.update(), "โŒ GDrive sync not configured."
    result = gdrive.delete_draft(name)
    if not result.ok:
        return gr.update(), f"โš ๏ธ Delete failed: {result.error}"
    return gr.update(choices=gdrive.list_drafts(), value=None), f"๐Ÿ—‘๏ธ Deleted draft `{name}`."


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# ACR TI-RADS calculator (pure Python โ€” no API call)
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

TIRADS_OPTIONS = {
    "composition": [
        ("Cystic or almost completely cystic", 0),
        ("Spongiform", 0),
        ("Mixed cystic and solid", 1),
        ("Solid or almost completely solid", 2),
    ],
    "echogenicity": [
        ("Anechoic", 0),
        ("Hyperechoic or isoechoic", 1),
        ("Hypoechoic", 2),
        ("Very hypoechoic", 3),
    ],
    "shape": [
        ("Wider-than-tall", 0),
        ("Taller-than-wide", 3),
    ],
    "margin": [
        ("Smooth", 0),
        ("Ill-defined", 0),
        ("Lobulated or irregular", 2),
        ("Extra-thyroidal extension", 3),
    ],
    "foci": [
        ("None or large comet-tail artifacts", 0),
        ("Macrocalcifications", 1),
        ("Peripheral (rim) calcifications", 2),
        ("Punctate echogenic foci", 3),
    ],
}


def _tirads_level(total: int) -> tuple[str, str]:
    if total == 0:
        return "TR1 (benign)", "No FNA. No follow-up needed."
    if total == 2:
        return "TR2 (not suspicious)", "No FNA. No follow-up needed."
    if total == 3:
        return "TR3 (mildly suspicious)", "FNA if โ‰ฅ 2.5 cm. Follow-up US if โ‰ฅ 1.5 cm."
    if total in (4, 5, 6):
        return "TR4 (moderately suspicious)", "FNA if โ‰ฅ 1.5 cm. Follow-up US if โ‰ฅ 1.0 cm."
    # total โ‰ฅ 7
    return "TR5 (highly suspicious)", "FNA if โ‰ฅ 1.0 cm. Follow-up US if โ‰ฅ 0.5 cm."


def tirads_compute(composition, echogenicity, shape, margin, foci_selected, size_cm):
    # foci_selected is multi-select list of labels
    pts = {
        "composition": dict(TIRADS_OPTIONS["composition"]).get(composition, 0),
        "echogenicity": dict(TIRADS_OPTIONS["echogenicity"]).get(echogenicity, 0),
        "shape": dict(TIRADS_OPTIONS["shape"]).get(shape, 0),
        "margin": dict(TIRADS_OPTIONS["margin"]).get(margin, 0),
    }
    foci_dict = dict(TIRADS_OPTIONS["foci"])
    foci_pts = sum(foci_dict.get(lbl, 0) for lbl in (foci_selected or []))
    pts["foci"] = foci_pts

    total = sum(pts.values())
    level, fna_rule = _tirads_level(total)

    # Size-based action
    try:
        size = float(size_cm) if size_cm else None
    except ValueError:
        size = None

    if size is None:
        action = "Nodule size not entered โ€” enter size to compute FNA threshold."
    else:
        if total == 0 or total == 2:
            action = f"Size {size} cm: no FNA needed (benign / not suspicious category)."
        elif total == 3:
            if size >= 2.5:
                action = f"Size {size} cm โ‰ฅ 2.5 cm โ†’ **FNA recommended**."
            elif size >= 1.5:
                action = f"Size {size} cm โ‰ฅ 1.5 cm โ†’ **follow-up US at 1, 3, 5 years**, no FNA."
            else:
                action = f"Size {size} cm: no FNA, no routine follow-up."
        elif total in (4, 5, 6):
            if size >= 1.5:
                action = f"Size {size} cm โ‰ฅ 1.5 cm โ†’ **FNA recommended**."
            elif size >= 1.0:
                action = f"Size {size} cm โ‰ฅ 1.0 cm โ†’ **follow-up US at 1, 2, 3, 5 years**, no FNA."
            else:
                action = f"Size {size} cm: no FNA, no routine follow-up."
        else:  # โ‰ฅ 7 โ†’ TR5
            if size >= 1.0:
                action = f"Size {size} cm โ‰ฅ 1.0 cm โ†’ **FNA recommended**."
            elif size >= 0.5:
                action = f"Size {size} cm โ‰ฅ 0.5 cm โ†’ **annual follow-up US ร— 5 years**, no FNA."
            else:
                action = f"Size {size} cm < 0.5 cm: no FNA, no routine follow-up."

    breakdown = "\n".join([
        f"- Composition: {composition} โ†’ {pts['composition']} pt",
        f"- Echogenicity: {echogenicity} โ†’ {pts['echogenicity']} pt",
        f"- Shape: {shape} โ†’ {pts['shape']} pt",
        f"- Margin: {margin} โ†’ {pts['margin']} pt",
        f"- Echogenic foci: {', '.join(foci_selected) if foci_selected else 'none'} โ†’ {foci_pts} pt",
    ])
    summary = (
        f"## ACR TI-RADS Result\n\n"
        f"**Total points: {total}** โ†’ **{level}**\n\n"
        f"FNA rule for this category: {fna_rule}\n\n"
        f"**Action: {action}**\n\n"
        f"---\n\n"
        f"### Point breakdown\n{breakdown}\n"
    )
    return summary


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# UI
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


def tb(label: str, lines: int = 1, placeholder: str = "") -> gr.Textbox:
    return gr.Textbox(label=label, lines=lines, placeholder=placeholder or "leave blank or 'nil' to skip")


def build_initial_visit_tab(inputs: dict) -> tuple[
    gr.components.Component,  # screenshots
    gr.components.Component,  # api_key_box
    gr.components.Component,  # draft_name_box
    gr.components.Component,  # personal_notes_box
    gr.components.Component,  # generate_btn
    gr.components.Component,  # output
    gr.components.Component,  # upload_status
    gr.components.Component,  # download_btn
    gr.components.Component,  # download_file
    gr.components.Component,  # draft_select
    gr.components.Component,  # save_draft_btn
    gr.components.Component,  # load_draft_btn
    gr.components.Component,  # delete_draft_btn
    gr.components.Component,  # refresh_btn
    gr.components.Component,  # draft_status
]:
    gr.Markdown(
        "# ๐Ÿฆ‹ Thyroid Initial-Visit Note Generator\n"
        "Endocrine / family-medicine outpatient ยท 4-section structured output ยท Not for unverified clinical use."
    )

    with gr.Accordion("โš™๏ธ API key (optional override)", open=False):
        api_key_box = gr.Textbox(
            label="Anthropic API key",
            type="password",
            placeholder="leave blank to use Space secret ANTHROPIC_API_KEY",
        )

    with gr.Accordion("๐Ÿ’พ Patient chart number + drafts (synced to Google Drive)", open=True):
        gr.Markdown(
            "_Chart number is the single identifier โ€” draft name in Drive, filename of generated `.md`, "
            "and how you find your in-progress cases across devices. Save here, switch device, "
            "pick from dropdown, Load, continue._"
        )
        with gr.Row():
            draft_name_box = gr.Textbox(
                label="Patient chart number (็—…ๆญท่™Ÿ)",
                placeholder="e.g. 1029332",
                scale=3,
            )
            save_draft_btn = gr.Button("๐Ÿ’พ Save draft", scale=1, variant="secondary")
        with gr.Row():
            draft_select = gr.Dropdown(
                label="๐Ÿ“‹ Existing drafts (in Drive)",
                choices=[],
                interactive=True,
                scale=3,
            )
            refresh_btn = gr.Button("๐Ÿ”„ Refresh", scale=1, size="sm")
        with gr.Row():
            load_draft_btn = gr.Button("๐Ÿ“ฅ Load selected", variant="secondary")
            delete_draft_btn = gr.Button("๐Ÿ—‘๏ธ Delete selected", variant="stop")
        draft_status = gr.Markdown("")

    with gr.Accordion("1. Visit context", open=True):
        with gr.Row():
            inputs["age"] = tb("Age", placeholder="e.g. 42")
            inputs["sex"] = gr.Dropdown(["female", "male", ""], label="Sex", value="")
            inputs["clinic_type"] = gr.Dropdown(
                ["endocrine OPD", "family medicine OPD", "internal medicine OPD", "general OPD", ""],
                label="Clinic type", value="",
            )
        inputs["visit_datetime"] = tb("Visit date/time", placeholder="e.g. 2026-06-01 14:30")
        inputs["chief_concern"] = tb("Chief concern", lines=2, placeholder="e.g. abnormal TSH on health check; neck mass; palpitations ร— 2 months")
        inputs["onset"] = tb("Symptom onset / time course", lines=2, placeholder="e.g. gradual over 3 months; first noted on health-check 2 weeks ago")

    with gr.Accordion("2. Phenotype tags (check what applies โ€” drives Section 4 order selection)", open=True):
        gr.Markdown(
            "_Tick one or more. If you leave all unchecked, AI will infer from your notes "
            "and state the inferred phenotype at the top of Section 1._"
        )
        with gr.Row():
            inputs["pt_hyper"] = gr.Checkbox(label="Hyperthyroid symptoms", value=False)
            inputs["pt_hypo"] = gr.Checkbox(label="Hypothyroid symptoms", value=False)
            inputs["pt_nodule"] = gr.Checkbox(label="Goiter / thyroid nodule", value=False)
            inputs["pt_abnormal_lab"] = gr.Checkbox(label="Abnormal lab (health check)", value=False)

    with gr.Accordion("3. Review of systems (fill per phenotype โ€” skip rest)", open=True):
        inputs["ros_hyper"] = tb(
            "Hyperthyroid axis",
            lines=3,
            placeholder="palpitation / tremor / heat intolerance / sweating / weight loss / appetite โ†‘ / diarrhea / insomnia / anxiety / proximal weakness / oligomenorrhea / chest pain / syncope",
        )
        inputs["ros_hypo"] = tb(
            "Hypothyroid axis",
            lines=3,
            placeholder="fatigue / cold intolerance / weight gain / constipation / dry skin / hair loss / facial-leg edema / hoarseness / cognitive slowing / depression / myalgia / menorrhagia / bradycardia symptoms",
        )
        inputs["ros_neck"] = tb(
            "Neck / compressive",
            lines=2,
            placeholder="neck mass / dysphagia / dyspnea / orthopnea / choking / hoarseness / rapid enlargement / Pemberton",
        )
        inputs["ros_eye"] = tb(
            "Eye (Graves)",
            lines=2,
            placeholder="proptosis / dry eye / diplopia / eye pain / visual decline / photophobia / lid lag / morning lid swelling",
        )
        inputs["ros_pain"] = tb(
            "Pain / inflammatory",
            lines=2,
            placeholder="thyroid tenderness / radiation to jaw-ear / recent URI / fever / postpartum 6 mo / transient hyperโ†’hypo course",
        )

    with gr.Accordion("4. Past medical history + family history", open=False):
        inputs["pmh_thyroid"] = tb(
            "Prior thyroid disease (Graves / Hashimoto / nodule / cancer / thyroiditis / surgery / RAI)",
            lines=2,
        )
        inputs["pmh_autoimmune"] = tb("Other autoimmune disease")
        inputs["pmh_cv"] = tb("Cardiovascular / osteoporosis (AF / HF / CAD / HTN / fracture)")
        inputs["pmh_other"] = tb("Other relevant (psych / liver / renal / leukopenia / recent malignancy)")
        inputs["fh_thyroid"] = tb("Family h/o thyroid disease (Graves / Hashimoto / nodule / cancer / MEN2 / MTC)")
        inputs["fh_autoimmune"] = tb("Family h/o other autoimmune disease")

    with gr.Accordion("5. Medications, supplements, exposures (้ซ˜ๆฌŠ้‡ โ€” ไธ€ๅฎš่ฆๅ•)", open=False):
        inputs["meds_thyroid"] = tb(
            "Thyroid drugs (levothyroxine dose+timing+co-meds; methimazole; PTU; T3 prep)",
            lines=2,
        )
        inputs["meds_other_thyroid"] = tb(
            "Other thyroid-relevant drugs (amiodarone / lithium / IFN-ฮฑ / ICI / TKI / biotin / OCP / anti-seizure / dopamine / glucocorticoid)",
            lines=2,
        )
        inputs["exposure_iodine"] = tb(
            "Iodine exposure (recent CT-cath contrast / kelp / seaweed / kelp supplement / betadine / Chinese-medicine)",
        )
        inputs["exposure_radiation"] = tb(
            "Radiation exposure (childhood/young-adult head-neck radiotherapy)",
        )

    with gr.Accordion("6. Female-specific (skip if N/A)", open=False):
        inputs["female_pregnant"] = tb(
            "Pregnancy / planning / breastfeeding / postpartum (specify month)",
        )
        inputs["female_menses"] = tb("Menstrual / fertility status")

    with gr.Accordion("7. Physical examination", open=False):
        inputs["pe_vitals"] = tb(
            "Vital signs (BTยฐC / HR / RR / BP / SpO2 / weight kg)",
        )
        inputs["pe_general"] = tb("General appearance")
        inputs["pe_eye"] = tb(
            "Eye exam (lid retraction / lid lag / proptosis / EOM / visual acuity / conjunctival injection / periorbital edema)",
            lines=2,
        )
        inputs["pe_neck_inspect"] = tb(
            "Neck inspection (visible enlargement / asymmetry / scar / venous engorgement / moves with swallow)",
        )
        inputs["pe_neck_palp"] = tb(
            "Neck palpation (size / consistency / surface / tenderness / mobility / nodule loc-size-border / tracheal deviation / retrosternal extension)",
            lines=3,
        )
        inputs["pe_neck_ausc"] = tb("Neck auscultation (thyroid bruit)")
        inputs["pe_lymph"] = tb(
            "Cervical lymph nodes (location / size / consistency / mobility โ€” flag hard, fixed, supraclavicular)",
            lines=2,
        )
        inputs["pe_hand_neuro"] = tb(
            "Hand / neuromuscular (fine tremor / palm warmth-moisture / DTR / proximal strength / CTS)",
            lines=2,
        )
        inputs["pe_cv"] = tb("Cardiovascular (rhythm / rate / murmur / JVP / edema)")
        inputs["pe_skin"] = tb(
            "Skin / hair (warm-moist vs dry-coarse / pretibial myxedema / hair pattern / onycholysis)",
        )
        inputs["pe_other"] = tb("Other focused positives / important negatives")

    with gr.Accordion("8. Prior data on file (free text)", open=False):
        inputs["prior_labs"] = tb(
            "Prior thyroid labs (TSH/FT4/T3 values + date)",
            lines=3,
            placeholder="e.g. 2026-05-15: TSH 0.02 (0.4-4.0), FT4 2.8 (0.8-1.8), T3 280 (60-180)",
        )
        inputs["prior_imaging"] = tb(
            "Prior imaging (US / scan reports + date)",
            lines=3,
        )
        inputs["prior_fna"] = tb(
            "Prior FNA Bethesda category (date + result)",
            lines=2,
        )
        screenshots = gr.File(
            label="๐Ÿ“ท Prior lab / imaging report screenshots (upload from desktop)",
            file_count="multiple",
            file_types=["image"],
            type="filepath",
        )

    gr.Markdown(
        "### ๐Ÿ“ Personal notes (ๅƒ…ไพ›ไฝ ๆ้†’่‡ชๅทฑ็”จ โ€” ไธๆœƒ้€ AIใ€ไธๆœƒๅ‡บ็พๅœจ็—…ๆญท)\n"
        "_ไพ‹ๅฆ‚๏ผš่ทŸๅญธ้•ท็ขบ่ช TRAb ๆ˜ฏๅฆ่ฆ่ฟฝใ€ๅฎถๅฑฌ่ฏ็ตกๆ™‚้–“ใ€ๅ›ž่จบๆŽ’็จ‹ใ€‚ๆœƒ่ทŸ่‘—่‰็จฟๅœจ Drive ๅŒๆญฅ๏ผŒ"
        "ไฝ† Generate ๆ™‚ไธๆœƒ่ขซ็•ถไฝœ็—…ๆญทไธ€้ƒจๅˆ†ใ€‚_"
    )
    personal_notes_box = gr.Textbox(
        label="",
        placeholder="ๅ€‹ไบบๆ้†’็”จ๏ผŒ่‡ช็”ฑ็™ผๆฎ",
        lines=4,
        show_label=False,
    )

    generate_btn = gr.Button("โœ๏ธ Generate thyroid initial-visit note", variant="primary", size="lg")
    output = gr.Textbox(label="Output (4-section structured note)", lines=30, show_copy_button=True)
    upload_status = gr.Markdown("")

    with gr.Row():
        download_btn = gr.Button("๐Ÿ“„ Download as .md", variant="secondary")
        download_file = gr.File(label="Download link", interactive=False)

    return (
        screenshots, api_key_box, draft_name_box, personal_notes_box,
        generate_btn, output, upload_status, download_btn, download_file,
        draft_select, save_draft_btn, load_draft_btn, delete_draft_btn,
        refresh_btn, draft_status,
    )


def build_tirads_tab():
    gr.Markdown(
        "# ๐Ÿ”ฌ ACR TI-RADS Calculator\n"
        "Pure local calculation โ€” does not call the API. Reference: ACR TI-RADS, "
        "Tessler et al. JACR 2017."
    )
    with gr.Row():
        composition = gr.Dropdown(
            choices=[lbl for lbl, _ in TIRADS_OPTIONS["composition"]],
            label="Composition (0-2 pt)",
            value="Solid or almost completely solid",
        )
        echogenicity = gr.Dropdown(
            choices=[lbl for lbl, _ in TIRADS_OPTIONS["echogenicity"]],
            label="Echogenicity (0-3 pt)",
            value="Hypoechoic",
        )
    with gr.Row():
        shape = gr.Dropdown(
            choices=[lbl for lbl, _ in TIRADS_OPTIONS["shape"]],
            label="Shape (0 or 3 pt)",
            value="Wider-than-tall",
        )
        margin = gr.Dropdown(
            choices=[lbl for lbl, _ in TIRADS_OPTIONS["margin"]],
            label="Margin (0-3 pt)",
            value="Smooth",
        )
    foci = gr.CheckboxGroup(
        choices=[lbl for lbl, _ in TIRADS_OPTIONS["foci"]],
        label="Echogenic foci (multi-select; points are additive โ€” 0+1+2+3 pt)",
        value=[],
    )
    size = gr.Textbox(
        label="Nodule size (largest dimension, cm)",
        placeholder="e.g. 1.2",
    )
    compute_btn = gr.Button("Compute TI-RADS", variant="primary")
    result = gr.Markdown("")

    compute_btn.click(
        fn=tirads_compute,
        inputs=[composition, echogenicity, shape, margin, foci, size],
        outputs=result,
    )
    gr.Markdown(
        "---\n"
        "_Result is an aid for the physician. Final FNA decision and follow-up plan "
        "depend on clinical context (TSH suppression, patient comorbidity, prior US trend, etc.)._"
    )


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Assemble app
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


def build_app() -> gr.Blocks:
    with gr.Blocks(title="Thyroid Initial Visit", theme=gr.themes.Soft()) as demo:
        inputs: dict[str, gr.components.Component] = {}

        with gr.Tabs():
            with gr.Tab("๐Ÿ“ Initial visit note"):
                (
                    screenshots, api_key_box, draft_name_box, personal_notes_box,
                    generate_btn, output, upload_status, download_btn, download_file,
                    draft_select, save_draft_btn, load_draft_btn, delete_draft_btn,
                    refresh_btn, draft_status,
                ) = build_initial_visit_tab(inputs)

            with gr.Tab("๐Ÿ”ฌ ACR TI-RADS calculator"):
                build_tirads_tab()

        ordered_inputs = [inputs[k] for k in FORM_KEYS]

        def _generate_adapter(*args):
            yield from generate(
                *args[:-3],
                screenshots=args[-3],
                api_key_override=args[-2],
                chart_number=args[-1],
            )

        generate_btn.click(
            fn=_generate_adapter,
            inputs=ordered_inputs + [screenshots, api_key_box, draft_name_box],
            outputs=[output, upload_status],
        )

        download_btn.click(
            fn=save_md,
            inputs=[output, draft_name_box],
            outputs=download_file,
        )

        save_draft_btn.click(
            fn=save_draft_handler,
            inputs=[draft_name_box, screenshots, personal_notes_box] + ordered_inputs,
            outputs=[draft_select, draft_status],
        )
        load_draft_btn.click(
            fn=load_draft_handler,
            inputs=[draft_select],
            outputs=[draft_name_box] + ordered_inputs + [personal_notes_box, screenshots, draft_status],
        )
        delete_draft_btn.click(
            fn=delete_draft_handler,
            inputs=[draft_select],
            outputs=[draft_select, draft_status],
        )
        refresh_btn.click(
            fn=refresh_drafts_list,
            inputs=[],
            outputs=draft_select,
        )
        draft_select.change(
            fn=lambda v: v or gr.update(),
            inputs=[draft_select],
            outputs=[draft_name_box],
        )
        demo.load(fn=refresh_drafts_list, inputs=[], outputs=draft_select)

        gr.Markdown(
            "---\n"
            "_Template-driven output. Verify every line against the chart before pasting into the EMR. "
            "Drafts and generated notes are stored in your personal Google Drive (drive.file scope โ€” "
            "the app only sees files it created)._"
        )

    return demo


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Launch
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


if __name__ == "__main__":
    app = build_app()
    launch_kwargs: dict = {}
    if int(gr.__version__.split(".")[0]) >= 5:
        launch_kwargs["ssr_mode"] = False
    if PASSWORD:
        launch_kwargs["auth"] = ("doctor", PASSWORD)
    app.launch(**launch_kwargs)