File size: 97,042 Bytes
7a1b59b
3213410
 
 
 
 
 
9f4c6cf
3213410
 
 
 
 
 
 
 
a35d7dc
9f4c6cf
fb1fbfc
121d905
6e946dd
bd064c3
24537b5
 
121d905
3213410
 
539b76f
3213410
 
 
 
 
 
 
 
e556f16
 
3213410
 
 
 
9f4c6cf
 
 
 
3213410
 
 
9991538
3213410
 
 
 
 
 
9f4c6cf
 
 
 
3213410
 
 
9991538
3213410
 
 
a35d7dc
3213410
 
a35d7dc
9ed2562
a35d7dc
 
 
 
3b3a2ae
9aae0e4
77751a1
 
a35d7dc
 
 
 
 
 
 
 
9f4c6cf
a35d7dc
 
9f4c6cf
a35d7dc
 
 
9f4c6cf
a35d7dc
 
9f4c6cf
a35d7dc
 
9f4c6cf
a35d7dc
 
9f4c6cf
a35d7dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b3a2ae
 
a35d7dc
3213410
95799ca
9ed2562
 
3213410
 
 
 
9f4c6cf
3213410
9f4c6cf
 
3213410
9f4c6cf
 
3213410
9f4c6cf
a35d7dc
 
 
9f4c6cf
 
 
3213410
9f4c6cf
 
 
3213410
9f4c6cf
 
 
 
 
 
 
3213410
9f4c6cf
 
 
 
 
3213410
 
 
 
 
 
 
9f4c6cf
 
 
 
 
 
 
 
 
 
3213410
9f4c6cf
 
 
3213410
9f4c6cf
3213410
 
9f4c6cf
 
 
3213410
 
9f4c6cf
 
3213410
9f4c6cf
 
 
 
3213410
 
 
 
409f950
3213410
 
9f4c6cf
3213410
 
a35d7dc
3213410
 
9f4c6cf
3213410
 
 
 
a35d7dc
3213410
 
 
 
 
9f4c6cf
a35d7dc
 
 
 
 
 
 
 
 
 
 
 
a1b431e
9f4c6cf
 
 
 
 
 
 
 
a35d7dc
 
9f4c6cf
a35d7dc
 
 
 
 
 
 
 
 
 
9f4c6cf
 
a35d7dc
 
 
 
 
 
9f4c6cf
 
a35d7dc
 
9f4c6cf
a35d7dc
 
 
a1b431e
a35d7dc
409f950
9f4c6cf
a35d7dc
 
 
 
9f4c6cf
a35d7dc
 
9f4c6cf
 
3213410
a35d7dc
 
 
 
9f4c6cf
 
 
 
a35d7dc
 
 
 
 
 
 
3213410
a35d7dc
 
a2d7dc8
a35d7dc
 
 
 
3213410
a35d7dc
3213410
 
 
 
a35d7dc
 
3213410
a35d7dc
 
 
 
 
 
 
3213410
a35d7dc
3213410
 
 
 
 
a35d7dc
3213410
a35d7dc
3213410
 
a35d7dc
 
6e946dd
bd064c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e946dd
a35d7dc
6e946dd
 
a35d7dc
bd064c3
 
6e946dd
 
bd064c3
4389378
 
bd064c3
 
6e946dd
 
 
3213410
bd064c3
 
 
 
 
 
3213410
121d905
bd064c3
6e946dd
121d905
 
6e946dd
 
bd064c3
6e946dd
 
 
bd064c3
6e946dd
a35d7dc
bd064c3
 
81f58eb
 
 
 
 
bd064c3
 
 
 
24537b5
 
3213410
81f58eb
 
bd064c3
 
6e946dd
bd064c3
 
3213410
6e946dd
3213410
 
a35d7dc
7a1b59b
 
 
 
 
 
 
 
3213410
a35d7dc
 
 
3213410
9f4c6cf
 
a35d7dc
9f4c6cf
 
 
 
 
 
 
a35d7dc
3213410
a35d7dc
 
 
9f4c6cf
 
a35d7dc
 
 
9f4c6cf
a35d7dc
 
 
 
 
 
3213410
 
 
a35d7dc
 
3213410
9f4c6cf
 
4d6e46c
 
9f4c6cf
a35d7dc
 
 
 
 
 
 
 
9f4c6cf
a35d7dc
 
 
 
 
 
 
 
9f4c6cf
 
 
 
 
 
 
 
a35d7dc
9f4c6cf
 
a35d7dc
9f4c6cf
 
a35d7dc
9f4c6cf
 
 
 
 
 
 
 
a35d7dc
3213410
a35d7dc
9f4c6cf
4d6e46c
 
 
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
a35d7dc
 
9f4c6cf
 
 
 
 
 
 
a35d7dc
 
 
9f4c6cf
 
 
 
 
 
a35d7dc
 
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a35d7dc
9f4c6cf
a35d7dc
 
9f4c6cf
 
3213410
 
9f4c6cf
 
 
a35d7dc
 
 
 
3213410
a35d7dc
9f4c6cf
a35d7dc
9f4c6cf
 
 
a35d7dc
 
9f4c6cf
 
a35d7dc
 
 
 
9f4c6cf
 
a35d7dc
 
9f4c6cf
3213410
a35d7dc
9f4c6cf
a35d7dc
9f4c6cf
 
 
 
 
 
 
 
 
a35d7dc
 
 
9f4c6cf
a35d7dc
 
3213410
9f4c6cf
a35d7dc
 
 
 
9f4c6cf
 
 
 
 
9991538
9f4c6cf
 
 
 
 
 
 
 
a35d7dc
9f4c6cf
 
 
 
 
 
 
3213410
a35d7dc
 
9f4c6cf
 
 
 
 
 
 
eb152c0
a35d7dc
c39ca7f
 
 
 
 
9f4c6cf
c39ca7f
 
 
 
 
9f4c6cf
c39ca7f
 
 
 
 
 
 
 
 
 
 
3213410
a35d7dc
 
3213410
e35e66d
9f4c6cf
3b3a2ae
b27da9c
 
 
9f4c6cf
 
 
 
 
b27da9c
 
 
 
9991538
b27da9c
 
a35d7dc
9f4c6cf
 
 
 
 
 
 
3213410
 
a35d7dc
 
3213410
a35d7dc
 
3213410
9991538
a35d7dc
9f4c6cf
 
 
 
 
 
 
 
c39ca7f
a35d7dc
c39ca7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f4c6cf
c39ca7f
 
 
 
 
9f4c6cf
a35d7dc
c39ca7f
3213410
a35d7dc
 
3213410
9991538
a35d7dc
9f4c6cf
 
 
 
 
 
 
a35d7dc
c39ca7f
a35d7dc
c39ca7f
 
 
 
9f4c6cf
c39ca7f
 
 
 
 
9f4c6cf
c39ca7f
3213410
a35d7dc
 
3213410
 
9991538
a35d7dc
9f4c6cf
 
 
 
 
 
 
c39ca7f
a35d7dc
c39ca7f
 
 
 
9f4c6cf
c39ca7f
 
 
 
 
9f4c6cf
a35d7dc
3213410
a35d7dc
3213410
 
a35d7dc
 
 
9f4c6cf
 
 
 
a35d7dc
9f4c6cf
 
 
 
 
 
 
 
a35d7dc
 
9f4c6cf
 
 
 
 
 
3b3a2ae
9f4c6cf
b27da9c
 
 
 
9991538
a35d7dc
b27da9c
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a35d7dc
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a35d7dc
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a35d7dc
9f4c6cf
a35d7dc
9f4c6cf
 
3b3a2ae
9f4c6cf
3213410
a35d7dc
9f4c6cf
 
 
 
 
 
 
 
 
4d6e46c
 
 
 
 
 
 
 
 
 
 
9991538
 
4d6e46c
9991538
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4389378
9991538
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9697f33
2d937c4
9991538
 
 
 
 
 
 
 
 
 
4d6e46c
 
9991538
 
4d6e46c
6e946dd
4d6e46c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9991538
 
 
4d6e46c
 
b983136
4d6e46c
 
 
 
 
 
 
 
121d905
 
 
 
 
 
 
 
 
 
 
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
3213410
9f4c6cf
 
 
a35d7dc
9f4c6cf
77751a1
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3213410
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a35d7dc
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
a35d7dc
9f4c6cf
 
 
a35d7dc
9f4c6cf
 
3213410
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3213410
9f4c6cf
 
 
 
 
 
 
 
 
 
 
a35d7dc
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a35d7dc
9991538
9f4c6cf
 
a35d7dc
9f4c6cf
 
3213410
9f4c6cf
 
9991538
 
 
 
 
88996ab
 
9991538
 
 
 
 
 
 
 
 
 
 
 
 
 
88996ab
 
9991538
 
 
 
 
 
 
 
 
 
 
 
 
3213410
9f4c6cf
9aae0e4
3213410
a35d7dc
6e946dd
a35d7dc
 
 
 
9f4c6cf
a35d7dc
 
9f4c6cf
a35d7dc
 
 
9f4c6cf
a35d7dc
 
9f4c6cf
a35d7dc
 
9f4c6cf
a35d7dc
 
9f4c6cf
a35d7dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9991538
 
 
a35d7dc
 
 
 
9f4c6cf
 
 
 
 
 
 
121d905
 
3213410
121d905
 
6e946dd
121d905
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d6e46c
88996ab
 
 
 
 
 
 
 
4d6e46c
88996ab
 
 
 
6e946dd
88996ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121d905
4389378
121d905
 
 
 
 
 
 
 
 
4d6e46c
 
9f4c6cf
 
 
 
 
 
 
 
 
3213410
9f4c6cf
3213410
a35d7dc
 
 
9f4c6cf
3213410
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd92513
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9697f33
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3213410
 
a35d7dc
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
a35d7dc
9f4c6cf
 
 
 
 
 
 
 
3213410
 
9f4c6cf
3213410
9f4c6cf
3213410
9f4c6cf
 
3213410
9f4c6cf
 
 
3213410
9f4c6cf
 
 
 
 
 
 
3213410
 
9f4c6cf
 
 
 
3213410
9f4c6cf
3213410
9f4c6cf
 
ae035f3
 
3213410
9f4c6cf
ae035f3
3213410
9f4c6cf
a35d7dc
 
 
 
3213410
 
9f4c6cf
 
 
 
3213410
9f4c6cf
3213410
9f4c6cf
 
9aae0e4
9f4c6cf
 
 
 
 
 
9991538
9f4c6cf
 
 
 
 
3213410
9f4c6cf
 
3213410
9f4c6cf
a35d7dc
 
9f4c6cf
 
 
 
 
 
 
 
 
 
 
a35d7dc
9f4c6cf
3213410
 
 
 
9f4c6cf
 
 
a35d7dc
 
 
 
9f4c6cf
 
a35d7dc
 
6e946dd
a35d7dc
6e946dd
 
 
 
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9991538
9f4c6cf
 
 
 
 
 
 
 
9991538
9f4c6cf
 
9991538
9f4c6cf
 
a35d7dc
9f4c6cf
 
 
 
a35d7dc
3213410
 
a35d7dc
9991538
a35d7dc
 
9f4c6cf
 
a35d7dc
 
3213410
 
9f4c6cf
 
 
 
 
 
 
 
 
 
 
 
a35d7dc
 
9f4c6cf
2d937c4
b983136
2d937c4
 
 
 
a35d7dc
2d937c4
 
 
 
 
9f4c6cf
a35d7dc
9f4c6cf
a35d7dc
9f4c6cf
 
 
 
3213410
 
9f4c6cf
a35d7dc
 
 
9f4c6cf
 
a35d7dc
3213410
 
a35d7dc
 
3213410
a35d7dc
 
 
 
 
 
 
3213410
a35d7dc
 
 
 
 
 
 
 
 
9f4c6cf
3213410
a35d7dc
9f4c6cf
 
a35d7dc
3213410
a35d7dc
3213410
 
a35d7dc
 
 
9f4c6cf
 
a35d7dc
3213410
9f4c6cf
3213410
6ac56c0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925

import os
import openai
import gradio as gr
import pandas as pd
from Chatbot_new import (
    generate_first_reveal, generate_internal_external_options,
    generate_second_reveal, generate_stable_unstable_options, generate_global_specific_options,
    generate_vignette, interpret_response, save_data_to_pickle,
    standardize_response, save_data_to_excel
)
import uuid
from dotenv import load_dotenv
from huggingface_hub import HfApi, HfFolder
import datetime
import logging
import asyncio
import random
import re
import threading
import time
import boto3
from botocore.config import Config

file_lock = threading.Lock()
#logging.basicConfig(level=logging.DEBUG)

tiliah_write2 = os.getenv("tiliah_write2")

# Load environment variables
load_dotenv()

##############################################################################
# File paths & Initialization
##############################################################################

excel_file = "assessment_data_cond2.xlsx"
pickle_file = "assessment_data_cond2.pkl"

# Make sure your Excel file has the PHQ/GAD columns:
if not os.path.exists(excel_file):
    pd.DataFrame(columns=[
        'Prolific ID', 'Age', 'Profession', 'Interests', 'New Interest', 'Topic Choice',
        'Vignette Number', "Vignette Type", 'Vignette', 'Tone', 'First Reveal', 'Raw Internal_External', 'Initial Internal',
        'Initial External', 'Raw Stable_Unstable', 'Initial Stable', 'Initial Unstable', 'Raw Global_Specific', 'Initial Global',
        'Initial Specific', 'Raw Reassessment', 'Reassessment Internal', 'Reassessment External',
        'Initial Relevance Rating', 'Final Relevance Rating', 'Emotional Relevance',
        'Positive Valence', 'Negative Valence', 'Likelihood of Change', "Ease of Use",
        "Clarity of Instructions", "Engagement Level", "Satisfaction with Assessment",
        "Cognitive Load", "Additional Comments", 'PHQ-9 Score', 'GAD-7 Score', "Attention Check 1", "Attention Check 2"
    ]).to_excel(excel_file, index=False, engine="openpyxl")


# Same for the pickle file:
if not os.path.exists(pickle_file):
    pd.DataFrame(columns=[
        'Prolific ID', 'Age', 'Profession', 'Interests', 'New Interest', 'Topic Choice',
        'Vignette Number', "Vignette Type", 'Vignette', 'Tone', 'First Reveal', 'Raw Internal_External', 'Initial Internal',
        'Initial External', 'Raw Stable_Unstable', 'Initial Stable', 'Initial Unstable', 'Raw Global_Specific', 'Initial Global',
        'Initial Specific', 'Raw Reassessment', 'Reassessment Internal', 'Reassessment External',
        'Initial Relevance Rating', 'Final Relevance Rating', 'Emotional Relevance',
        'Positive Valence', 'Negative Valence', 'Likelihood of Change', "Ease of Use",
        "Clarity of Instructions", "Engagement Level", "Satisfaction with Assessment",
        "Cognitive Load", "Additional Comments", 'PHQ-9 Score', 'GAD-7 Score', "Attention Check 1", "Attention Check 2"
    ]).to_pickle(pickle_file)

##############################################################################
# Shared user_state & Constants
##############################################################################

def get_default_app_state():
    state = {
        "prolific_id": None,
        "phq_score": 0,
        "gad_score": 0,
        "eligible": False,
        "welcome_message": False,
        "vignette_types": ["custom"] * 6 + ["generic"] * 6,
        "Attention Check 1": None,
        "Attention Check 2": None,
        "standardized_data": {
            "Prolific ID": None,
            "Raw Age": None,
            "Raw Profession": None,
            "Raw Interests": None,
            "Age": None,
            "Profession": None,
            "Interests": None,
            'New Interest': None,
            "Topic Choice": None,
            "Vignette Number": None,
            "Vignette Type": None, 
            "Vignette": None,
            "Tone": None,
            "First Reveal": None,
            'Raw Internal_External': None,
            "Initial Internal": None,
            'Initial External': None,
            'Raw Stable_Unstable': None,
            'Initial Stable': None,
            'Initial Unstable': None,
            'Raw Global_Specific': None,
            'Initial Global': None,
            'Initial Specific': None,
            'Raw Reassessment': None,
            'Reassessment Internal': None,
            'Reassessment External': None,
            'Initial Relevance Rating': None,
            'Final Relevance Rating': None,
            'Emotional Relevance': None,
            'Positive Valence': None,
            'Negative Valence': None,
            'Likelihood of Change': None,
            'PHQ-9 Score': None,
            'GAD-7 Score': None,
            "Second Reveal": None,
            "Explanation Response": None,
            "Assessment Internal External Response": None,
            "Evolved Internal External Response": None,
        },
        "stage": "prestart",
        "user_responses": [],
        "vignette_counter": 1,
        "topic_choice": None,
        "options_text": None,
        "desired_tone": None,
        "usability_question_counter": 0,
        "usability_feedback": {
            "Ease of Use": None,
            "Clarity of Instructions": None,
            "Engagement Level": None,
            "Satisfaction with Assessment": None,
            "Cognitive Load": None,
            "Additional Comments": None

        }
    }
    random.shuffle(state["vignette_types"])  # Shuffle order per participant

    return state

EXCLUSION_THRESHOLD = 20

##############################################################################
# Vignettes
##############################################################################

def generate_custom_vignette(chat_history, topic_choice, desired_tone, user_state, feedback=None):
    """
    Generates a personalized vignette for psychological assessment based on user preferences, ensuring
    that each vignette exclusively reflects the chosen topic (profession or interest) without mixing them.
    """
    # Retrieve stored user info
    user_age = user_state["standardized_data"].get("Age", "Unknown")
    user_profession = user_state["standardized_data"].get("Profession", "Unknown")
    user_interests = user_state["standardized_data"].get("Interests", "Unknown")
    new_interest = user_state["standardized_data"].get("New Interest", None)

    # Identify the relevant topic context based on topic_choice
    if topic_choice == "1":
        # Focus on profession only
        chosen_topic_text = f"Profession: {user_profession}"
        topic_context = f"a scenario directly related to teaching or performing tasks typical of {user_profession}"
    elif topic_choice == "2":
        # Focus on personal interests only
        chosen_topic_text = f"Interests: {user_interests}"
        topic_context = f"a scenario reflecting one of the user's personal interests ({user_interests})"
    elif topic_choice == "3" and new_interest:
        # Use the newly added interest
        chosen_topic_text = f"New Interest: {new_interest}"
        topic_context = f"a scenario inspired by the newly mentioned interest ({new_interest})"
    else:
        # Fallback for any other case
        chosen_topic_text = "General context"
        topic_context = "a general scenario based on the user's profile"
    
    # Decide the tone
    if desired_tone == "Positive":
        tone_context = "a pleasant and rewarding situation, highlighting success, collaboration, or enjoyable experiences."
    elif desired_tone == "Negative":
        tone_context = "an unpleasant or confrontational situation, involving conflict, challenges, or setbacks."
    else:
        tone_context = "a neutral situation."

    # If feedback is provided, embed it in the prompt
    feedback_instructions = ""
    if feedback and feedback.strip():
        feedback_instructions = f"""
        The user has provided additional information or critiques about the previous scenario:
        "{feedback}"
        Please incorporate this feedback to make the scenario more aligned with the user's context.
        """
    
    # Build a prompt that references ONLY the chosen topic
    prompt = f"""
    You are tasked with generating a short, personalized vignette for a psychological assessment.
    The user is {user_age} years old.
    {chosen_topic_text}
    Scenario Details:
    - The vignette must strictly focus on {topic_context}.
    - The tone of the vignette should reflect {tone_context}.
    - The vignette should include:
        - A clear context type (e.g., work, social, physical, educational, creative).
        - A specific interaction (e.g., feedback from authority, peer collaboration, group dynamics).
        - A defined event or action (e.g., presenting an idea, resolving a conflict, completing a project).
    Guidelines:
    - The vignette must describe external events only, without referencing thoughts, emotions, or internal reflections.
    - Use second-person language ("You...").
    - Keep the vignette concise (under 50 tokens) and neutral/professional.
    - Do not include personal identifying information.
    - Do not mention both profession and personal interests together; focus exclusively on the chosen topic.
    - Do not mix multiple interests or contexts; stay consistent with the single chosen topic.
    {feedback_instructions}
    
    Now generate the vignette:
    """

    try:
        response = openai.chat.completions.create(
            model="gpt-4o",
            messages=[
                {"role": "system", "content": "You are an assistant generating short, topic-focused scenarios without mixing contexts."},
                {"role": "user", "content": prompt},
            ],
            temperature=0.3,
            max_tokens=100
        )

        content = response.choices[0].message.content.strip()
        return content, desired_tone

    except KeyError as ke:
        print(f"KeyError accessing user_state: {ke}")
        return None, None
    except Exception as e:
        print(f"Error generating vignette: {e}")
        return None, None


def generate_generic_vignette(topic_choice, desired_tone):
    """
    Generates a generic vignette for psychological assessment, ignoring user profile details.
    """
    try:
        # Define tone context
        if desired_tone == "Positive":
            tone_context = "a pleasant and rewarding situation, highlighting success, collaboration, or enjoyable experiences."
        elif desired_tone == "Negative":
            tone_context = "an unpleasant or confrontational situation, involving conflict, challenges, or setbacks."
        else:
            tone_context = "a neutral situation."

        # Identify the topic context based on topic_choice
        if topic_choice == "1":
            topic_context = "a general professional scenario"
        elif topic_choice == "2":
            topic_context = "a general personal interest scenario"
        else:
            topic_context = "a general scenario suitable for any context"

        # Build the prompt
        prompt = f"""
        You are tasked with generating a short, generic vignette for a psychological assessment.
        Scenario Details:
        - The topic of the vignette is {topic_context}.
        - The tone of the vignette should reflect {tone_context}.
        - The vignette should include:
            - A clear context type (e.g., work, social, physical activity, educational, or creative).
            - A specific interaction (e.g., feedback from authority, peer collaboration, or group dynamics).
            - A defined event or action (e.g., presenting an idea, resolving a conflict, or completing a project).
        
        Guidelines:
        - The vignette must describe external events only, without referencing thoughts, emotions, or internal reflections.
        - Use second-person language ("You...").
        - Keep the vignette concise, under 50 tokens.
        - Use neutral and professional language suitable for a psychological assessment.
        - Do not include personal identifying information or references to the user's actual profile.
        
        Example:
            Positive Example:
                "You collaborate with a colleague on a shared report. 
                They praise your clear communication, and together you finalize the work ahead of schedule."
            
            Negative Example:
                "During a community gathering, you run into a disagreement over how to organize an activity. 
                The conversation becomes tense, and participants struggle to find common ground."
        
        Now generate the vignette:
        """

        # Call the OpenAI API
        response = openai.chat.completions.create(
            model="gpt-4o",
            messages=[
                {"role": "system", "content": "You are an assistant generating generic psychological assessment scenarios."},
                {"role": "user", "content": prompt},
            ],
            temperature=0.3,
            max_tokens=100
        )
        vignette = response.choices[0].message.content.strip()
        return vignette, desired_tone

    except Exception as e:
        print(f"Error generating generic vignette: {e}")
        return None, desired_tone


########################################################################################
# Storage Functions
########################################################################################

def upload_file_to_repo(
    local_file_path, 
    repo_id, 
    hf_token, 
    path_in_repo=None, 
    repo_type="space"):
    """
    Uploads `local_file_path` to a Hugging Face repo (dataset/space/model).
    Deletes existing versions of the file first.
    :param local_file_path: local file (e.g. "partial_data_cond2.xlsx")
    :param repo_id: e.g. "mojakob/user_data" or "mojakob/my-space"
    :param hf_token: huggingface token with write access
    :param path_in_repo: file path in the repo (defaults to local_file_path)
    :param repo_type: "dataset", "space", or "model"
    """

    api = HfApi()
    if path_in_repo is None:
        path_in_repo = local_file_path

    # 1. Delete previous file(s) of same name
    all_files = api.list_repo_files(repo_id, repo_type=repo_type)
    for file in all_files:
        if file.startswith(path_in_repo):  # match by filename prefix
            api.delete_file(
                path_in_repo=file, 
                repo_id=repo_id, 
                repo_type=repo_type, 
                token=hf_token
            )
            print(f"Deleted old file: {file}")

    # 2. Upload the new version
    api.upload_file(
        path_or_fileobj=local_file_path,
        path_in_repo=path_in_repo,
        repo_id=repo_id,
        repo_type=repo_type,
        token=hf_token,
        commit_message="Upload latest version of data file"
    )

    print(f"Uploaded {local_file_path} -> {repo_id}/{path_in_repo} [repo_type={repo_type}]")


# def save_to_excel(new_row, user_state):
#     """
#     Appends a single row (new_row) to the user's unique file 
#     stored in user_state["excel_file"].

#     Then uploads that updated file to Hugging Face, preserving concurrency 
#     by never touching a shared file.
#     """
#     hf_token = os.getenv("tiliah_write2")
#     dataset_repo_id = "mojakob/user_data" 
#     local_file = user_state.get("excel_file")

#     usability_data = user_state.get("usability_feedback", {})
#     new_row.update(usability_data)
    
#     if not local_file:
#         print("Error: No user_state['excel_file'] found.")
#         return

#     try:
#         with file_lock:
#             # 1. If the unique user file doesn't exist yet, create a new one with appropriate columns
#             if not os.path.exists(local_file):
#                 df = pd.DataFrame(columns=new_row.keys())
#             else:
#                 df = pd.read_excel(local_file, engine="openpyxl")
            
#             # 2. Append the new row
#             df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)
#             print("SAVING row to unique user file:", new_row)
            
#             # 3. Save locally
#             df.to_excel(local_file, index=False, engine="openpyxl")

#         # 4. Upload to Hugging Face (outside the lock)
#         if hf_token and dataset_repo_id:
#             api = HfApi()
#             path_in_repo = f"Cond2/{local_file}"
#             future_upload = api.upload_file(
#                 path_or_fileobj=local_file,
#                 path_in_repo=path_in_repo,  # same name in the repo
#                 repo_id=dataset_repo_id,
#                 repo_type="dataset",
#                 token=hf_token,
#                 run_as_future=True
#             )
#             future_upload
#             future_upload.result()            
#             print(f"Uploaded {local_file} to HF dataset.")
#         else:
#             print("No HF token or dataset repo provided, skipping HF upload.")
#     except Exception as e:
#         print(f"Error in save_to_excel: {e}")
#         raise

def save_to_excel(new_row, user_state):
    """
    Appends a single row (new_row) to the user's unique file 
    stored in user_state["excel_file"].

    Then uploads that updated file to an S3-compatible bucket 
    (e.g., Hetzner) under "Cond2/<filename>", preserving concurrency 
    by never touching a shared file.
    """
    # Merge usability data if present
    usability_data = user_state.get("usability_feedback", {})
    new_row.update(usability_data)

    local_file = user_state.get("excel_file")
    if not local_file:
        print("Error: No user_state['excel_file'] found.")
        return

    # Read S3 credentials from environment
    s3_access_key = os.getenv("HETZNER_ACCESS_KEY_ID")
    s3_secret_key = os.getenv("HETZNER_SECRET_ACCESS_KEY")
    s3_endpoint   = os.getenv("HETZNER_S3_ENDPOINT")
    bucket_name   = os.getenv("HETZNER_BUCKET_NAME")

    try:
        with file_lock:
            # 1) If the user file doesn't exist, create it with new_row's columns
            if not os.path.exists(local_file):
                df = pd.DataFrame(columns=new_row.keys())
            else:
                df = pd.read_excel(local_file, engine="openpyxl")
            
            # 2) Append the new row
            df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)
            print("SAVING row to unique user file:", new_row)
            
            # 3) Save locally
            df.to_excel(local_file, index=False, engine="openpyxl")

        # 4) Upload to S3 outside the lock, if credentials/bucket are set
        if s3_access_key and s3_secret_key and s3_endpoint and bucket_name:
            from botocore.config import Config
            my_config = Config(
                signature_version="s3v4",
                s3={"addressing_style": "path"}
            )
            s3_client = boto3.client(
                "s3",
                aws_access_key_id=s3_access_key,
                aws_secret_access_key=s3_secret_key,
                endpoint_url=s3_endpoint,
                config=my_config
            )
            # Use the basename to avoid uploading unwanted path details
            s3_key = f"Cond2/{os.path.basename(local_file)}"
            s3_client.upload_file(local_file, bucket_name, s3_key)
            print(f"Uploaded {local_file} to S3 bucket '{bucket_name}' at key: {s3_key}")
        else:
            print("No S3 credentials or bucket provided, skipping S3 upload.")

    except Exception as e:
        print(f"Error in save_to_excel: {e}")
        raise


def validate_numeric_input(user_input, min_val=1, max_val=10):
    try:
        value = int(user_input.strip())
        if value < min_val or value > max_val:
            return None, f"Please provide a number between {min_val} and {max_val}."
        return value, None
    except ValueError:
        return None, f"Please provide a number between {min_val} and {max_val}."

#############################################################################
# Chat Flow
#############################################################################

def new_chat_input(chat_history, user_state, user_input, *args, **kwargs):
        
    if not user_input.strip():
        return (
            chat_history,                 # Updated chat history
            user_state,                   # Updated user state
            gr.update(visible=True, value=""),  # Textbox
            gr.update(visible=False),     # Slider
            gr.update(visible=False)      # Confirm button
        )
    chat_history.append((user_input, ""))  
    
    vignette_tones = [
        'Positive', 'Negative', 'Negative', 'Positive', 'Positive', 'Negative', 'Negative', 'Positive',
        'Positive', 'Negative', 'Negative', 'Positive', 'Positive', 'Negative', 'Negative', 'Positive']  # Total of 16 vignettes
    
    
    print(f"user_state at start of new_chat_input: {user_state}")
    print(f"input received: {user_input}")
    print(f"history received: {chat_history}")
    
    if user_state["stage"] == "prestart":
        user_state["standardized_data"]['Prolific ID'] = user_state["prolific_id"]
        # Retrieve the "Raw" fields first
        raw_age = user_state["standardized_data"].get("Raw Age", "Unknown")
        raw_profession = user_state["standardized_data"].get("Raw Profession", "Unknown")
        raw_interests = user_state["standardized_data"].get("Raw Interests", "Unknown")

        required_fields = ["Age", "Profession", "Interests"]
        for field in required_fields:
            if field not in user_state["standardized_data"]:
                raise KeyError(f"Missing field '{field}' in user_state['standardized_data'].")

        # Pick vignette type
        vignette_type = user_state["vignette_types"][user_state["vignette_counter"] - 1]
        user_state["standardized_data"]["Vignette Type"] = vignette_type  # Store vignette type        

    
        # Adjust the topic choice prompt based on vignette type
        if vignette_type == "generic":
            response = """
            Let's create a scenario for you.
            Which topic would you prefer?
            1. A general professional scenario.
            2. A general personal interest scenario.
            """
            user_state['options_text'] = '1. A general professional scenario.\n2. A general personal interest scenario.'
        else:
            response = """
            Let's create a scenario for you.
            Which topic would you prefer?
            1. A situation related to your profession.
            2. A situation related to your personal interests.
            3. Something else about me. (Add another activity or interest that is important to you by saying "I also like...")
            """
            user_state['options_text'] = (
                '1. A situation related to your profession.\n'
                '2. A situation related to your personal interests.\n'
                '3. Something else about me (Add another activity or interest that is important to you by saying "I also like...")'
            )
        
        user_state["stage"] = "topic_choice"
        print(f"user_state during initial topic_choice: {user_state}")

        if user_state["vignette_counter"] == 1 and not user_state.get("welcome_message", False):
            welcome_message = "Alright then! "
            response = welcome_message + response
            user_state["welcome_message"] = True        
        
        chat_history[-1] = (user_input, response)
        return (
            chat_history,                 # Updated chat history
            user_state,                   # Updated user state
            gr.update(visible=True, value=""),  # Textbox
            gr.update(visible=False),     # Slider
            gr.update(visible=False)      # Confirm button
        )
        
    elif user_state["stage"] == "topic_choice":
        print("topic_choice block successfully entered")
        print(f"User entered input: {user_input}")
        
        # Pick vignette type
        vignette_type = user_state["vignette_types"][user_state["vignette_counter"] - 1]
        user_state["standardized_data"]["Vignette Type"] = vignette_type  # Store vignette type 
        
        # Define the options_text based on vignette_type
        if vignette_type == "generic":
            user_state['options_text'] = '1. A general professional scenario.\n2. A general personal interest scenario.'
        else:
            user_state['options_text'] = (
                '1. A situation related to your profession.\n'
                '2. A situation related to your personal interests.\n'
                '3. Something else about me (Add another activity or interest that is important to you by saying "I also like...")'
            )
        
        # Store the user's response
        user_state["user_responses"].append({"stage": "topic_choice", "response": user_input})
        print(f"user input was: {user_input}, user responses after storing it are: {user_state['user_responses']}")
        
        user_input_lower = user_input.lower().strip()
        
        # Initialize mapped_option2
        mapped_option2 = None
        
        # Check for "i also like" or explicit "3" in the input
        if "i also like" in user_input_lower:
            mapped_option2 = "3"
            new_interest = user_input_lower.split("i also like", 1)[1].strip()
            
            user_state["standardized_data"]["New Interest"] = new_interest
            
            existing_interests = user_state["standardized_data"].get("Interests", "")
            if existing_interests:
                user_state["standardized_data"]["Interests"] = existing_interests + ", " + new_interest
            else:
                user_state["standardized_data"]["Interests"] = new_interest
            
            user_state["topic_choice"] = "3"
            user_state["standardized_data"]["Topic Choice"] = "3"
        elif "3" in user_input_lower and vignette_type == "custom":
            mapped_option2 = "3"
            # Attempt to parse the new interest from any text after "3"
            split_on_3 = user_input_lower.split("3", 1)
            new_interest_raw = split_on_3[1].strip() if len(split_on_3) > 1 else ""
            
            if new_interest_raw:
                new_interest = new_interest_raw
            else:
                new_interest = "unspecified"  # fallback
            
            user_state["standardized_data"]["New Interest"] = new_interest
            
            existing_interests = user_state["standardized_data"].get("Interests", "")
            if existing_interests:
                user_state["standardized_data"]["Interests"] = existing_interests + ", " + new_interest
            else:
                user_state["standardized_data"]["Interests"] = new_interest
            
            user_state["topic_choice"] = "3"
            user_state["standardized_data"]["Topic Choice"] = "3"
        else:
            # Use interpret_response to map the input to options
            mapped_option1 = standardize_response("Please extract the user's chosen topic.", user_input)
            mapped_option2 = interpret_response(mapped_option1, user_state['options_text'], user_state)
            user_state["topic_choice"] = mapped_option2
            user_state["standardized_data"]["Topic Choice"] = mapped_option2
        
        print(f"User Input: {user_input}")
        print(f"Mapped Option: {mapped_option2}")
        
        # Determine valid options based on vignette_type
        if vignette_type == "generic":
            valid_options = ['1', '2']
        else:
            valid_options = ['1', '2', '3']
        
        if mapped_option2 in valid_options:
            # Assign vignette number and desired_tone
            user_state["standardized_data"]['Vignette Number'] = user_state["vignette_counter"]
            user_state["desired_tone"] = vignette_tones[user_state["vignette_counter"] - 1] if user_state["vignette_counter"] - 1 < len(vignette_tones) else "Positive"
            
            # Generate vignette based on vignette_type
            if vignette_type == "generic":
                vignette, tone = generate_generic_vignette(
                    topic_choice=mapped_option2, 
                    desired_tone=user_state["desired_tone"]
                )
            else:
                vignette, tone = generate_custom_vignette(
                    chat_history=chat_history,
                    topic_choice=mapped_option2,
                    desired_tone=user_state["desired_tone"],
                    user_state=user_state
                )
            
            if vignette is None:
                user_state["stage"] = "error"
                response = "Error generating vignette. Please restart."
                chat_history[-1] = (user_input, response)        
                return (
                    chat_history,                 
                    user_state,                   
                    gr.update(visible=True, value=""),  
                    gr.update(visible=False),     
                    gr.update(visible=False)      
                )
            
            # Update user_state with vignette and tone
            user_state["vignette"] = vignette
            user_state["tone"] = tone
            user_state["user_responses"].append({
                'stage': 'vignette', 
                'content': user_state["vignette"], 
                'tone': user_state["tone"]
            })
            
            user_state["standardized_data"]['Vignette'] = user_state["vignette"]
            user_state["standardized_data"]['Tone'] = user_state["tone"]
            user_state["stage"] = "vignette_usability_assessment"
            print(f"Stage updated to: {user_state['stage']}")
        
            # Prepare the response based on vignette_type
            if vignette_type == "generic":
                response = (
                    f"Alright, please imagine you are witnessing the following scene:\n\n{user_state['vignette']}\n\n"
                    "Before we proceed, on a scale from 1 to 10, how relevant, immersive, or relatable is the depicted scenario to you personally? (1 = not at all, 10 = completely)"
                )
            else:
                response = (
                    f"Alright, please imagine you are witnessing the following scene:\n\n{user_state['vignette']}\n\n"
                    "Before we proceed: Have you personally experienced something similar to this scenario before? "
                    "Please rate the similarity on a scale from 1 to 10 (1 = Not at all similar, 10 = Extremely similar)."
                )
        
            chat_history[-1] = (user_input, response)        
            return (
                chat_history,                 
                user_state,                   
                gr.update(visible=True, value=""),  
                gr.update(visible=False),     
                gr.update(visible=False)      
            )          
        else:
            response = "Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?"
            chat_history[-1] = (user_input, response)        
            return (
                chat_history,                 
                user_state,                   
                gr.update(visible=True, value=""),  
                gr.update(visible=False),     
                gr.update(visible=False)      
            )       

    elif user_state["stage"] == "vignette_usability_assessment":
        try:
            relevance_rating = int(user_input.strip())
        except ValueError:
            response = "Please provide a number between 1 and 10."
            chat_history[-1] = (user_input, response)
            return (
                chat_history,
                user_state,
                gr.update(visible=True, value=""),
                gr.update(visible=False),
                gr.update(visible=False)
            )
        if relevance_rating not in range(1, 11):
            response = "Please provide a number between 1 and 10."
            chat_history[-1] = (user_input, response)
            return (
                chat_history,
                user_state,
                gr.update(visible=True, value=""),
                gr.update(visible=False),
                gr.update(visible=False)
            )        
            
        # Store the initial relevance rating if not already stored
        if f'Initial Relevance Rating' not in user_state["standardized_data"]:
            user_state["standardized_data"][f'Initial Relevance Rating'] = int(relevance_rating)
    
        if int(relevance_rating) < 6:
            # Retrieve vignette_type
            vignette_type = user_state["standardized_data"]["Vignette Type"]
            if vignette_type == "custom":
                # Trigger regeneration only for custom vignettes
                user_state["stage"] = "vignette_regeneration"
                response = (
                    "I'm sorry to hear that the scenario wasn't quite fitting. "
                    "I might have misunderstood some of your responses.\n\n"
                    "Could you please briefly clarify why the scenario felt off, so we can come up with a better one?"
                )
            else:
                # For generic vignettes, skip regeneration and proceed
                user_state["stage"] = "emotional_relevance"
                response = (
                    "How much emotional impact did this scenario have on you? (1 = None, 10 = A lot)"
                )
    
            chat_history[-1] = (user_input, response)        
            return (
                chat_history,                 
                user_state,                   
                gr.update(visible=True, value=""),  
                gr.update(visible=False),     
                gr.update(visible=False)      
            )
        
        # Accept the vignette
        user_state["standardized_data"][f'Vignette'] = user_state["vignette"]
        user_state["standardized_data"][f'Tone'] = user_state["tone"]
        # Store the final relevance rating
        user_state["standardized_data"][f'Final Relevance Rating'] = int(relevance_rating)
        user_state["stage"] = "emotional_relevance"
        # Emotional relevance rating
        response = "How much emotional impact did this scenario have on you? (1 = None, 10 = A lot)"
        chat_history[-1] = (user_input, response)        
        return (
            chat_history,                 
            user_state,                   
            gr.update(visible=True, value=""),  
            gr.update(visible=False),     
            gr.update(visible=False)      
        )


    elif user_state["stage"] == "emotional_relevance":
        try:
            emotional_relevance = int(user_input.strip())
        except ValueError:
            response = "Please provide a number between 1 and 10."
            chat_history[-1] = (user_input, response)
            return (
                chat_history,
                user_state,
                gr.update(visible=True, value=""),
                gr.update(visible=False),
                gr.update(visible=False)
            )
        if emotional_relevance not in range(1, 11):
            response = "Please provide a number between 1 and 10."
            chat_history[-1] = (user_input, response)
            return (
                chat_history,
                user_state,
                gr.update(visible=True, value=""),
                gr.update(visible=False),
                gr.update(visible=False)
            )
        
        
        # Store emotional relevance rating
        user_state["standardized_data"][f'Emotional Relevance'] = int(emotional_relevance)
        user_state["stage"] = "positive_valence"
        # Positive Valence
        response = f"""How much joy, excitement, or satisfaction did this scenario evoke in you? (1 = None, 10 = A lot)"""
        chat_history[-1] = (user_input, response)        
        return (
            chat_history,                 # Updated chat history
            user_state,                   # Updated user state
            gr.update(visible=True, value=""),  # Textbox
            gr.update(visible=False),     # Slider
            gr.update(visible=False)      # Confirm button
        )
    

    elif user_state["stage"] == "positive_valence":
        positive_valence, error = validate_numeric_input(user_input, 1, 10)
        if error:
            response = error
            chat_history[-1] = (user_input, response)
            return (
                chat_history,
                user_state,
                gr.update(visible=True, value=""),
                gr.update(visible=False),
                gr.update(visible=False)
            )
        
        # Store positive valence rating
        user_state["standardized_data"][f'Positive Valence'] = int(positive_valence)
        user_state["stage"] = "negative_valence"

        # Negative Valence
        response = f"""How much discomfort or tension did you feel while imagining this scenario? (1 = None, 10 = A lot)"""
        chat_history[-1] = (user_input, response)        
        return (
            chat_history,                 # Updated chat history
            user_state,                   # Updated user state
            gr.update(visible=True, value=""),  # Textbox
            gr.update(visible=False),     # Slider
            gr.update(visible=False)      # Confirm button
        )

    elif user_state["stage"] == "negative_valence":
        negative_valence, error = validate_numeric_input(user_input, 1, 10)
        if error:
            response = error
            chat_history[-1] = (user_input, response)
            return (
                chat_history,
                user_state,
                gr.update(visible=True, value=""),
                gr.update(visible=False),
                gr.update(visible=False)
            )
        
        # Store negative valence rating
        user_state["standardized_data"][f'Negative Valence'] = int(negative_valence)

        # Move to next stage
        user_state["stage"] = "internal_external"
        user_state['options_text'] = generate_internal_external_options(chat_history, user_state["standardized_data"][f'Vignette'], user_state)
        response = (
        f"Please read the scenario again and use the slider below to answer the next few questions:\n"
        f"\n{user_state['vignette']}\n"
        "\nImagine this situation is happening to you personally. \nFrom 1 to 10, which of the following statements do you think is more likely (1 = Definitely Option A, 10 = Definitely Option B):\n"
        f"\n{user_state['options_text']}")
        chat_history[-1] = (user_input, response)        
        return (
            chat_history,                # Updated chat history
            user_state,                  # Updated user state
            gr.update(visible=False),    # Textbox
            gr.update(visible=True),     # Slider
            gr.update(visible=True)      # Confirm button
        )
            
    elif user_state["stage"] == "vignette_regeneration":
        additional_info = user_input
        user_state["user_responses"].append({
            "stage": "vignette_regeneration",
            "feedback": additional_info
        })
        
        # Retrieve vignette_type
        vignette_type = user_state["standardized_data"]["Vignette Type"]
        
        if vignette_type != "custom":
            # If vignette is generic, skip regeneration
            user_state["stage"] = "emotional_relevance"
            response = (
                "How much emotional impact did this scenario have on you? (1 = None, 10 = A lot)"
            )
            chat_history[-1] = (user_input, response)        
            return (
                chat_history,                 
                user_state,                   
                gr.update(visible=True, value=""),  
                gr.update(visible=False),     
                gr.update(visible=False)      
            )
        
        # For custom vignettes, proceed with regeneration
        # Retrieve the current topic choice
        topic_choice = user_state["standardized_data"].get("Topic Choice", user_state["topic_choice"])
        new_interest = user_state["standardized_data"].get("New Interest", None)
        
        # Determine topic_choice_for_vignette
        if topic_choice == "3" and new_interest:
            topic_choice_for_vignette = new_interest
        else:
            topic_choice_for_vignette = topic_choice
        
        # Regenerate the vignette, passing user feedback
        vignette, tone = generate_custom_vignette(
            chat_history=chat_history,
            topic_choice=topic_choice_for_vignette,
            desired_tone=user_state["desired_tone"],
            user_state=user_state,
            feedback=additional_info
        )
        
        if vignette is None:
            user_state["stage"] = "error"
            response = "There was an error generating the vignette. Please restart the assessment."
            chat_history[-1] = (user_input, response)        
            return (
                chat_history,                 
                user_state,                   
                gr.update(visible=True, value=""),  
                gr.update(visible=False),     
                gr.update(visible=False)      
            )
        
        # Update user_state with the regenerated vignette and tone
        user_state["vignette"] = vignette
        user_state["tone"] = tone
        user_state["user_responses"].append({
            'stage': "vignette_regenerated",
            'content': user_state["vignette"],
            'tone': user_state["tone"]
        })
        
        # Update the standardized data
        user_state["standardized_data"]['Vignette'] = user_state["vignette"]
        user_state["standardized_data"]['Tone'] = user_state["tone"]
        
        # Return to usability assessment
        user_state["stage"] = "vignette_usability_assessment"
        
        response = (
            "Okay, let's try again. Please imagine you are witnessing the following scene:\n\n"
            f"{user_state['vignette']}\n\n"
            "Before we proceed, on a scale from 1 to 10, how relevant, immersive, or relatable is the depicted scenario to you personally? (1 = not at all, 10 = completely)"
        )
        
        chat_history[-1] = (user_input, response)        
        return (
            chat_history,                 
            user_state,                   
            gr.update(visible=True, value=""),  
            gr.update(visible=False),     
            gr.update(visible=False)      
        )
    

    elif user_state["stage"] == "usability_feedback":
        print("Transitioning to usability_feedback stage.")
        #save_to_pickle(user_state["standardized_data"])
        #save_to_excel(user_state["standardized_data"])
        feedback_questions = [
            """Thank you for completing all the scenarios. We just have a few more questions before you leave. 
            
            How easy was it to complete the assessment? (1 = Not at all, 10 = Very much)""",
            "How clear were the instructions? (1 = Not at all, 10 = Very much)",
            "How engaging was the assessment experience? (1 = Not at all, 10 = Very much)",
            "How satisfied are you with this assessment? (1 = Not at all, 10 = Very much)",
            "How mentally demanding was the assessment? (1 = Not at all, 10 = Very much)",
            None
        ]
        
        if user_state["usability_question_counter"] < 5:
            # ----------------------------------------------------------
            # Handling numeric questions (1..5)
            try:
                numeric_response = int(user_input)
            except ValueError:
                response = "Please provide a number between 1 and 10."
                chat_history[-1] = (user_input, response)
                return (
                    chat_history,
                    user_state,
                    gr.update(visible=True, value=""),
                    gr.update(visible=False),
                    gr.update(visible=False)
                )
        
            if numeric_response not in range(1, 11):
                response = "Please provide a number between 1 and 10."
                chat_history[-1] = (user_input, response)
                return (
                    chat_history,
                    user_state,
                    gr.update(visible=True, value=""),
                    gr.update(visible=False),
                    gr.update(visible=False)
                )
        
            # Store numeric response
            question_key = [
                "Ease of Use",
                "Clarity of Instructions",
                "Engagement Level",
                "Satisfaction with Assessment",
                "Cognitive Load"
            ][user_state["usability_question_counter"]]
            user_state["usability_feedback"][question_key] = numeric_response
        
            user_state["usability_question_counter"] += 1
        
            # If we still have more numeric questions
            if user_state["usability_question_counter"] < 5:
                response = feedback_questions[user_state["usability_question_counter"]]
                chat_history[-1] = (user_input, response)
                return (
                    chat_history,
                    user_state,
                    gr.update(visible=True, value=""),
                    gr.update(visible=False),
                    gr.update(visible=False)
                )
        
            # else we are now at the Additional Comments question:
            # response = "Do you have any additional comments about your experience? (Type 'no' if none.)"
            response = "Lastly, do you have any additional comments or feedback regarding your experience? (Type 'no' if none.)"
            chat_history[-1] = (user_input, response)
            user_state["usability_question_counter"] = 5
            return (
                chat_history,
                user_state,
                gr.update(visible=True, value=""),  # Let them type text
                gr.update(visible=False),
                gr.update(visible=False)
            )
                
    
        # Check if we've finished all questions
        elif user_state["usability_question_counter"] == 5:
            user_state["usability_feedback"]["Additional Comments"] = user_input.strip()
            user_state["stage"] = "completed"
            save_to_excel({
                'Prolific ID': user_state["prolific_id"],
                'Age': user_state["standardized_data"].get("Age", None),
                'Profession': user_state["standardized_data"].get("Profession", None),
                'Interests': user_state["standardized_data"].get("Interests", None),
                'New Interest': user_state["standardized_data"].get("New Interest", None),
                'Topic Choice': user_state["standardized_data"].get("Topic Choice", None),
                'Vignette Number': user_state["standardized_data"].get("Vignette Number", None),
                'Vignette Type': user_state["standardized_data"].get("Vignette Type", None),
                'Vignette': user_state["standardized_data"].get("Vignette", None),
                'Tone': user_state["standardized_data"].get("Tone", None),
                'First Reveal': user_state["standardized_data"].get("First Reveal", None),
                'Raw Internal_External': user_state["standardized_data"].get("Raw Internal_External", None),
                'Initial Internal': user_state["standardized_data"].get("Initial Internal", None),
                'Initial External': user_state["standardized_data"].get("Initial External", None),
                'Raw Stable_Unstable': user_state["standardized_data"].get("Raw Stable_Unstable", None),
                'Initial Stable': user_state["standardized_data"].get("Initial Stable", None),
                'Initial Unstable': user_state["standardized_data"].get("Initial Unstable", None),
                'Raw Global_Specific': user_state["standardized_data"].get("Raw Global_Specific", None),
                'Initial Global': user_state["standardized_data"].get("Initial Global", None),
                'Initial Specific': user_state["standardized_data"].get("Initial Specific", None),
                'Raw Reassessment': user_state["standardized_data"].get("Raw Reassessment", None),
                'Reassessment Internal': user_state["standardized_data"].get("Reassessment Internal", None),
                'Reassessment External': user_state["standardized_data"].get("Reassessment External", None),
                'Initial Relevance Rating': user_state["standardized_data"].get("Initial Relevance Rating", None),
                'Final Relevance Rating': user_state["standardized_data"].get("Final Relevance Rating", None),
                'Emotional Relevance': user_state["standardized_data"].get("Emotional Relevance", None),
                'Positive Valence': user_state["standardized_data"].get("Positive Valence", None),
                'Negative Valence': user_state["standardized_data"].get("Negative Valence", None),
                'Likelihood of Change': user_state["standardized_data"].get("Likelihood of Change", None),
                "Ease of Use": user_state["standardized_data"].get("Ease of Use", None),
                "Clarity of Instructions": user_state["standardized_data"].get("Clarity of Instructions", None),
                "Engagement Level": user_state["standardized_data"].get("Engagement Level", None),
                "Satisfaction with Assessment": user_state["standardized_data"].get("Satisfaction with Assessment", None),
                "Cognitive Load": user_state["standardized_data"].get("Cognitive Load", None),
                "Additional Comments": user_state["standardized_data"].get("Additional Comments", None),
                'PHQ-9 Score': user_state["phq_score"],
                'GAD-7 Score': user_state["gad_score"],
                "Attention Check 1": user_state.get("Attention Check 1", None),
                "Attention Check 2": user_state.get("Attention Check 2", None)
            }, user_state)
            
            response = "Thank you for your feedback! Your responses have been saved. Please use the following link to submit your results: https://app.prolific.com/submissions/complete?cc=C1ECU6HA"
            chat_history[-1] = (user_input, response)        
            return (
                chat_history,                 # Updated chat history
                user_state,                   # Updated user state
                gr.update(visible=True, value=""),  # Textbox
                gr.update(visible=False),     # Slider
                gr.update(visible=False)      # Confirm button
            )

    elif user_state["stage"] == "completed":
            response = "Thank you for your feedback! Your responses have been saved. Please use the following link to submit your results: https://app.prolific.com/submissions/complete?cc=C1ECU6HA"
            chat_history[-1] = (user_input, response)        
            return (
                chat_history,                 # Updated chat history
                user_state,                   # Updated user state
                gr.update(visible=True, value=""),  # Textbox
                gr.update(visible=False),     # Slider
                gr.update(visible=False)      # Confirm button
            )                        
    
    else:
        print(f"Unexpected user_state or input: stage={user_state['stage']}, message={user_input}")
        response = "An unexpected error occurred. Please try again or contact support."
        chat_history[-1] = (user_input, response)        
        return (
            chat_history,                 # Updated chat history
            user_state,                   # Updated user state
            gr.update(visible=True, value=""),  # Textbox
            gr.update(visible=False),     # Slider
            gr.update(visible=False)      # Confirm button
        )

##################################################################################
# Sliders
##################################################################################

def slider_input(chat_history, user_state, attribution_slider, *args, **kwargs):
    if 1 <= attribution_slider <= 10:
        chat_history.append((str(attribution_slider), ""))    
    
    if attribution_slider < 1 or attribution_slider > 10:
        response = "Please pick a number between 1 and 10."
        chat_history[-1] = (str(attribution_slider), response)
        return (
            chat_history,                # Updated chat history
            user_state,                  # Updated user state
            gr.update(visible=False),    # Hide the textbox
            gr.update(visible=True, value=1),     # Show the slider
            gr.update(visible=True)      # Show the Confirm button
        )
    
    # For internal/external
    if user_state["stage"] == "internal_external":
        user_state["standardized_data"]['Raw Internal_External'] = attribution_slider
        # 1–5 => '1', 6–10 => '2'
        user_state["explanation_response"] = '1' if attribution_slider <= 5 else '2'

        # Store numeric
        if user_state["explanation_response"] == '1':
            user_state["standardized_data"]['Initial Internal'] = 1
            user_state["standardized_data"]['Initial External'] = 0
        else:
            user_state["standardized_data"]['Initial Internal'] = 0
            user_state["standardized_data"]['Initial External'] = 1

        # Next stage => stable_unstable
        user_state["stage"] = "stable_unstable"
        # Generate stable/unstable text
        user_state['options_text'] = generate_stable_unstable_options(
            user_state["standardized_data"]["Vignette"], user_state["explanation_response"], user_state
        )
        # global_specific_output = generate_global_specific_options(
        #     user_state["standardized_data"]["Vignette"], user_state["explanation_response"], user_state
        # )
        
        response = (
            "Now, from 1 to 10, which do you think is more likely? (1 = Definitely Option A, 10 = Definitely Option B)\n\n"
            f"{user_state['options_text']}"
        )
        chat_history[-1] = (str(attribution_slider), response)
        # Return the chat + user_state, and keep the slider visible
        return (
            chat_history,                # Updated chat history
            user_state,                  # Updated user state
            gr.update(visible=False),    # Hide the textbox
            gr.update(visible=True, value=1),     # Show the slider
            gr.update(visible=True)      # Show the Confirm button
        )

    elif user_state["stage"] == "stable_unstable":
        user_state["standardized_data"]['Raw Stable_Unstable'] = attribution_slider
        user_state["explanation_stable_unstable_response"] = '1' if attribution_slider <= 5 else '2'
        if user_state["explanation_stable_unstable_response"] == '1':
            user_state["standardized_data"]['Initial Stable'] = 1
            user_state["standardized_data"]['Initial Unstable'] = 0
        else:
            user_state["standardized_data"]['Initial Stable'] = 0
            user_state["standardized_data"]['Initial Unstable'] = 1
        
        # Move on to global_specific
        user_state["stage"] = "global_specific"
        
        print("explanation_response value passed to global_specific stage:")
        print(user_state["explanation_response"])
        
        user_state['options_text'] = generate_global_specific_options(
            user_state["standardized_data"]["Vignette"], user_state["explanation_response"], user_state
        )
        
        response = (
            "Next, from 1 to 10, which do you think is more likely? (1 = Definitely Option A, 10 = Definitely Option B)\n\n"
            f"{user_state['options_text']}"
        )
        chat_history[-1] = (str(attribution_slider), response)
        return (
            chat_history,                # Updated chat history
            user_state,                  # Updated user state
            gr.update(visible=False),    # Hide the textbox
            gr.update(visible=True, value=1),     # Show the slider
            gr.update(visible=True)      # Show the Confirm button
        )

    elif user_state["stage"] == "global_specific":
        user_state["standardized_data"]['Raw Global_Specific'] = attribution_slider
        user_state["explanation_global_specific_response"] = '1' if attribution_slider <= 5 else '2'
        if user_state["explanation_global_specific_response"] == '1':
            user_state["standardized_data"]['Initial Global'] = 1
            user_state["standardized_data"]['Initial Specific'] = 0
        else:
            user_state["standardized_data"]['Initial Global'] = 0
            user_state["standardized_data"]['Initial Specific'] = 1
        
        # Move to next stage => internal_external_reassessment
        user_state["stage"] = "internal_external_reassessment"
        user_state["first_reveal"] = generate_first_reveal(
            user_state["vignette"], user_state
        )
        user_state['options_text'] = generate_internal_external_options(
            chat_history,
            user_state["standardized_data"]["Vignette"] + " " + user_state["first_reveal"],
            user_state
        )
        response = (
            f"Alright, now please imagine:\n\n{user_state['first_reveal']}\n\n"
            "On a scale from 1 to 10, which is more likely? (1 = Definitely Option A, 10 = Definitely Option B)\n"
            f"{user_state['options_text']}"
        )
        chat_history[-1] = (str(attribution_slider), response)
        return (
            chat_history,                # Updated chat history
            user_state,                  # Updated user state
            gr.update(visible=False),    # Hide the textbox
            gr.update(visible=True, value=1),     # Show the slider
            gr.update(visible=True)      # Show the Confirm button
        )
    elif user_state["stage"] == "internal_external_reassessment":
        # store Reassessment
        user_state["standardized_data"]['Raw Reassessment'] = attribution_slider
        user_state["assessment_internal_external_response"] = '1' if attribution_slider <= 5 else '2'
        if user_state["assessment_internal_external_response"] == '1':
            user_state["standardized_data"]['Reassessment Internal'] = 1
            user_state["standardized_data"]['Reassessment External'] = 0
        else:
            user_state["standardized_data"]['Reassessment Internal'] = 0
            user_state["standardized_data"]['Reassessment External'] = 1
    
        # Next vignette
        user_state["vignette_counter"] += 1
    
        # --- Attention Check triggers here ---
        # If we’re at vignette #3, do attention_check_1 (unless it's already done)
        if user_state["vignette_counter"] == 3 and user_state["Attention Check 1"] is None:
            user_state["stage"] = "Attention Check 1"
            response = (
                "ATTENTION CHECK: \n\n"
                "Please set the slider to 10 (option on the very right) to show you're paying attention."
            )
            chat_history[-1] = (str(attribution_slider), response)
            return (
                chat_history,
                user_state,
                gr.update(visible=False),
                gr.update(visible=True, value=1),  # reset slider to 1
                gr.update(visible=True)           # show confirm button
            )
    
        # If we’re at vignette #9, do attention_check_2 (unless it's already done)
        if user_state["vignette_counter"] == 9 and user_state["Attention Check 2"] is None:
            user_state["stage"] = "Attention Check 2"
            response = (
                "ATTENTION CHECK: \n\n"
                "Once again, please set the slider to 10 (option on the very right) to confirm you're paying attention."
            )
            chat_history[-1] = (str(attribution_slider), response)
            return (
                chat_history,
                user_state,
                gr.update(visible=False),
                gr.update(visible=True, value=1),
                gr.update(visible=True)
            )
        
        # If all vignettes are complete, transition to usability feedback
        if user_state["vignette_counter"] > 12:
            print("All vignettes completed. Moving to usability feedback.")
           # save_to_pickle(user_state["standardized_data"])
            save_to_excel({
                'Prolific ID': user_state["prolific_id"],
                'Age': user_state["standardized_data"].get("Age", None),
                'Profession': user_state["standardized_data"].get("Profession", None),
                'Interests': user_state["standardized_data"].get("Interests", None),
                'New Interest': user_state["standardized_data"].get("New Interest", None),
                'Topic Choice': user_state["standardized_data"].get("Topic Choice", None),
                'Vignette Number': user_state["standardized_data"].get("Vignette Number", None),
                'Vignette Type': user_state["standardized_data"].get("Vignette Type", None),
                'Vignette': user_state["standardized_data"].get("Vignette", None),
                'Tone': user_state["standardized_data"].get("Tone", None),
                'First Reveal': user_state["standardized_data"].get("First Reveal", None),
                'Raw Internal_External': user_state["standardized_data"].get("Raw Internal_External", None),
                'Initial Internal': user_state["standardized_data"].get("Initial Internal", None),
                'Initial External': user_state["standardized_data"].get("Initial External", None),
                'Raw Stable_Unstable': user_state["standardized_data"].get("Raw Stable_Unstable", None),
                'Initial Stable': user_state["standardized_data"].get("Initial Stable", None),
                'Initial Unstable': user_state["standardized_data"].get("Initial Unstable", None),
                'Raw Global_Specific': user_state["standardized_data"].get("Raw Global_Specific", None),
                'Initial Global': user_state["standardized_data"].get("Initial Global", None),
                'Initial Specific': user_state["standardized_data"].get("Initial Specific", None),
                'Raw Reassessment': user_state["standardized_data"].get("Raw Reassessment", None),
                'Reassessment Internal': user_state["standardized_data"].get("Reassessment Internal", None),
                'Reassessment External': user_state["standardized_data"].get("Reassessment External", None),
                'Initial Relevance Rating': user_state["standardized_data"].get("Initial Relevance Rating", None),
                'Final Relevance Rating': user_state["standardized_data"].get("Final Relevance Rating", None),
                'Emotional Relevance': user_state["standardized_data"].get("Emotional Relevance", None),
                'Positive Valence': user_state["standardized_data"].get("Positive Valence", None),
                'Negative Valence': user_state["standardized_data"].get("Negative Valence", None),
                'Likelihood of Change': user_state["standardized_data"].get("Likelihood of Change", None),
                "Ease of Use": user_state["standardized_data"].get("Ease of Use", None),
                "Clarity of Instructions": user_state["standardized_data"].get("Clarity of Instructions", None),
                "Engagement Level": user_state["standardized_data"].get("Engagement Level", None),
                "Satisfaction with Assessment": user_state["standardized_data"].get("Satisfaction with Assessment", None),
                "Cognitive Load": user_state["standardized_data"].get("Cognitive Load", None),
                "Additional Comments": user_state["standardized_data"].get("Additional Comments", None),
                'PHQ-9 Score': user_state["phq_score"],
                'GAD-7 Score': user_state["gad_score"],
                "Attention Check 1": user_state.get("Attention Check 1", None),
                "Attention Check 2": user_state.get("Attention Check 2", None)                
            }, user_state)
            user_state["stage"] = "usability_feedback"
            user_state["usability_question_counter"] = 0
            response = "Thank you for completing all the scenarios. We just have a few more questions before you leave.\n \n How easy was it to complete the assessment? (1 = Not at all, 10 = Very much)"
            chat_history[-1] = (str(attribution_slider), response)        
            return (
                chat_history,                 # Updated chat history
                user_state,                   # Updated user state
                gr.update(visible=True, value=""),  # Textbox
                gr.update(visible=False),     # Slider
                gr.update(visible=False)      # Confirm button
            )    
        
        else:
            user_state["stage"] = "topic_choice"
            # save_to_pickle(user_state["standardized_data"])
            save_to_excel({
                'Prolific ID': user_state["prolific_id"],
                'Age': user_state["standardized_data"].get("Age", None),
                'Profession': user_state["standardized_data"].get("Profession", None),
                'Interests': user_state["standardized_data"].get("Interests", None),
                'New Interest': user_state["standardized_data"].get("New Interest", None),
                'Topic Choice': user_state["standardized_data"].get("Topic Choice", None),
                'Vignette Number': user_state["standardized_data"].get("Vignette Number", None),
                'Vignette Type': user_state["standardized_data"].get("Vignette Type", None),
                'Vignette': user_state["standardized_data"].get("Vignette", None),
                'Tone': user_state["standardized_data"].get("Tone", None),
                'First Reveal': user_state["standardized_data"].get("First Reveal", None),
                'Raw Internal_External': user_state["standardized_data"].get("Raw Internal_External", None),
                'Initial Internal': user_state["standardized_data"].get("Initial Internal", None),
                'Initial External': user_state["standardized_data"].get("Initial External", None),
                'Raw Stable_Unstable': user_state["standardized_data"].get("Raw Stable_Unstable", None),
                'Initial Stable': user_state["standardized_data"].get("Initial Stable", None),
                'Initial Unstable': user_state["standardized_data"].get("Initial Unstable", None),
                'Raw Global_Specific': user_state["standardized_data"].get("Raw Global_Specific", None),
                'Initial Global': user_state["standardized_data"].get("Initial Global", None),
                'Initial Specific': user_state["standardized_data"].get("Initial Specific", None),
                'Raw Reassessment': user_state["standardized_data"].get("Raw Reassessment", None),
                'Reassessment Internal': user_state["standardized_data"].get("Reassessment Internal", None),
                'Reassessment External': user_state["standardized_data"].get("Reassessment External", None),
                'Initial Relevance Rating': user_state["standardized_data"].get("Initial Relevance Rating", None),
                'Final Relevance Rating': user_state["standardized_data"].get("Final Relevance Rating", None),
                'Emotional Relevance': user_state["standardized_data"].get("Emotional Relevance", None),
                'Positive Valence': user_state["standardized_data"].get("Positive Valence", None),
                'Negative Valence': user_state["standardized_data"].get("Negative Valence", None),
                'Likelihood of Change': user_state["standardized_data"].get("Likelihood of Change", None),
                "Ease of Use": user_state["standardized_data"].get("Ease of Use", None),
                "Clarity of Instructions": user_state["standardized_data"].get("Clarity of Instructions", None),
                "Engagement Level": user_state["standardized_data"].get("Engagement Level", None),
                "Satisfaction with Assessment": user_state["standardized_data"].get("Satisfaction with Assessment", None),
                "Cognitive Load": user_state["standardized_data"].get("Cognitive Load", None),
                "Additional Comments": user_state["standardized_data"].get("Additional Comments", None),
                'PHQ-9 Score': user_state["phq_score"],
                'GAD-7 Score': user_state["gad_score"],
                "Attention Check 1": user_state.get("Attention Check 1", None),
                "Attention Check 2": user_state.get("Attention Check 2", None)                
            }, user_state)
    
            # Pick vignette type
            vignette_type = user_state["vignette_types"][user_state["vignette_counter"] - 1]
            user_state["standardized_data"]["Vignette Type"] = vignette_type  # Store vignette type 
    
            if vignette_type == "generic":
                response = (
                f"Thank you! We are now finished with scene {user_state['vignette_counter'] - 1}. In total you will be seeing 12 scenes.\n\nWhat would you like for your next round?\n"
                """1. A general professional scenario.
                2. A general personal interest scenario.
                """)
                user_state['options_text'] = '1. A general professional scenario.\n2. A general personal interest scenario.'
                chat_history[-1] = (str(attribution_slider), response)
                return (
                    chat_history,
                    user_state,
                    gr.update(visible=True, value=""),
                    gr.update(visible=False),
                    gr.update(visible=False)
                )                
            else:
                response = (
                f"Thank you! We are now finished with scene {user_state['vignette_counter'] - 1}. In total you will be seeing 12 scenes.\n\nWhat would you like for your next round?\n"
                """1. A situation related to your profession.
                2. A situation related to your personal interests.
                3. Something else about me. (Add another activity or interest that is important to you by saying "I also like...")
                """)
                user_state['options_text'] = (
                    '1. A situation related to your profession.\n'
                    '2. A situation related to your personal interests.\n'
                    '3. Something else about me (Add another activity or interest that is important to you by saying "I also like...")'
                )
                chat_history[-1] = (str(attribution_slider), response)
                return (
                    chat_history,
                    user_state,
                    gr.update(visible=True, value=""),
                    gr.update(visible=False),
                    gr.update(visible=False)
                )

    elif user_state["stage"] in ["Attention Check 1", "Attention Check 2"]:
        # 1) Determine which check
        check_id = user_state["stage"][-1]
        # 2) Pass/fail
        if attribution_slider == 10:
            user_state[f"Attention Check {check_id}"] = True
        else:
            user_state[f"Attention Check {check_id}"] = False    


        # Save data
        user_state["stage"] = "topic_choice"
        # save_to_pickle(user_state["standardized_data"])
        save_to_excel({
            'Prolific ID': user_state["prolific_id"],
            'Age': user_state["standardized_data"].get("Age", None),
            'Profession': user_state["standardized_data"].get("Profession", None),
            'Interests': user_state["standardized_data"].get("Interests", None),
            'New Interest': user_state["standardized_data"].get("New Interest", None),
            'Topic Choice': user_state["standardized_data"].get("Topic Choice", None),
            'Vignette Number': user_state["standardized_data"].get("Vignette Number", None),
            'Vignette Type': user_state["standardized_data"].get("Vignette Type", None),
            'Vignette': user_state["standardized_data"].get("Vignette", None),
            'Tone': user_state["standardized_data"].get("Tone", None),
            'First Reveal': user_state["standardized_data"].get("First Reveal", None),
            'Raw Internal_External': user_state["standardized_data"].get("Raw Internal_External", None),
            'Initial Internal': user_state["standardized_data"].get("Initial Internal", None),
            'Initial External': user_state["standardized_data"].get("Initial External", None),
            'Raw Stable_Unstable': user_state["standardized_data"].get("Raw Stable_Unstable", None),
            'Initial Stable': user_state["standardized_data"].get("Initial Stable", None),
            'Initial Unstable': user_state["standardized_data"].get("Initial Unstable", None),
            'Raw Global_Specific': user_state["standardized_data"].get("Raw Global_Specific", None),
            'Initial Global': user_state["standardized_data"].get("Initial Global", None),
            'Initial Specific': user_state["standardized_data"].get("Initial Specific", None),
            'Raw Reassessment': user_state["standardized_data"].get("Raw Reassessment", None),
            'Reassessment Internal': user_state["standardized_data"].get("Reassessment Internal", None),
            'Reassessment External': user_state["standardized_data"].get("Reassessment External", None),
            'Initial Relevance Rating': user_state["standardized_data"].get("Initial Relevance Rating", None),
            'Final Relevance Rating': user_state["standardized_data"].get("Final Relevance Rating", None),
            'Emotional Relevance': user_state["standardized_data"].get("Emotional Relevance", None),
            'Positive Valence': user_state["standardized_data"].get("Positive Valence", None),
            'Negative Valence': user_state["standardized_data"].get("Negative Valence", None),
            'Likelihood of Change': user_state["standardized_data"].get("Likelihood of Change", None),
            "Ease of Use": user_state["standardized_data"].get("Ease of Use", None),
            "Clarity of Instructions": user_state["standardized_data"].get("Clarity of Instructions", None),
            "Engagement Level": user_state["standardized_data"].get("Engagement Level", None),
            "Satisfaction with Assessment": user_state["standardized_data"].get("Satisfaction with Assessment", None),
            "Cognitive Load": user_state["standardized_data"].get("Cognitive Load", None),
            "Additional Comments": user_state["standardized_data"].get("Additional Comments", None),
            'PHQ-9 Score': user_state["phq_score"],
            'GAD-7 Score': user_state["gad_score"],
            "Attention Check 1": user_state.get("Attention Check 1", None),
            "Attention Check 2": user_state.get("Attention Check 2", None)                
        }, user_state)

        # Pick vignette type
        vignette_type = user_state["vignette_types"][user_state["vignette_counter"] - 1]
        user_state["standardized_data"]["Vignette Type"] = vignette_type  # Store vignette type 

        if vignette_type == "generic":
            response = (
            f"Thank you! We are now finished with scene {user_state['vignette_counter'] - 1}. In total you will be seeing 12 scenes.\n\nWhat would you like for your next round?\n"
            """1. A general professional scenario.
            2. A general personal interest scenario.
            """)
            user_state['options_text'] = '1. A general professional scenario.\n2. A general personal interest scenario.'
            chat_history[-1] = (str(attribution_slider), response)
            return (
                chat_history,
                user_state,
                gr.update(visible=True, value=""),
                gr.update(visible=False),
                gr.update(visible=False)
            )                
        else:
            response = (
            f"Thank you! We are now finished with scene {user_state['vignette_counter'] - 1}. In total you will be seeing 12 scenes.\n\nWhat would you like for your next round?\n"
            """1. A situation related to your profession.
            2. A situation related to your personal interests.
            3. Something else about me. (Add another activity or interest that is important to you by saying "I also like...")
            """)
            user_state['options_text'] = (
                '1. A situation related to your profession.\n'
                '2. A situation related to your personal interests.\n'
                '3. Something else about me (Add another activity or interest that is important to you by saying "I also like...")'
            )
            chat_history[-1] = (str(attribution_slider), response)
            return (
                chat_history,
                user_state,
                gr.update(visible=True, value=""),
                gr.update(visible=False),
                gr.update(visible=False)
            )                  
    
    else:  
        print(f"Unexpected user_state or input: stage={user_state['stage']}, message={attribution_slider}")
        response = "An unexpected error occurred. Please try again or contact support."
        chat_history[-1] = (str(attribution_slider), response)        
        return (
            chat_history,                 
            user_state,                   
            gr.update(visible=True, value=""),  # Textbox
            gr.update(visible=False),     # Slider
            gr.update(visible=False)      # Confirm button
        )
            

### Gradio app #############################################################

css = """
.custom-slider input[type=range] {
    accent-color: #1a73e8; /* Change this to your desired color */
}
"""

with gr.Blocks(theme= gr.themes.Glass(), css=css) as app:
    ########################################################################
    # Page 1: Briefing & Informed Consent
    ########################################################################

    user_state = gr.State(get_default_app_state())
    
    with gr.Row(visible=True) as page_1: 
        with gr.Column():
            gr.Markdown("""
            # **Information for Participants and Declaration of Consent**  
            ## **Evaluating the Validity of LLM-Based Psychological Assessments**
            
            ---
            
            ## **Dear Participant,**  
            ### We invite you to participate in the study described above. Your participation is entirely voluntary. You may refuse to participate or withdraw at any time without needing to provide a reason, and doing so will have no negative consequences for you.  
            
            ###  This study is designed to contribute to academic research by exploring a novel type of psychological assessment using advanced AI technology.  
            
            ###  Please read the following information carefully before deciding whether to participate. You may proceed only after acknowledging that you understand the study and your rights as a participant.  
            
            ---
            
            ## **Purpose of the Study**  
            ### This study aims to evaluate whether an AI-based psychological assessment can provide insights into cognitive patterns comparable to traditional methods.
            
            ---
            
            ## **Study Procedure**  
            ### - The study consists of three online sessions. Each session lasts approximately 20–30 minutes. The assessment will be conducted over the course of one week with three days in between each session. You must complete all three sessions to receive full compensation.  
            ### - You will reflect on various scenarios and provide feedback on your experience.  
            
            ---
            
            ## **Potential Benefits**  
            ### While there are no direct personal benefits, your participation will contribute to research that could help improve psychological diagnostic tools using AI.  
            
            ---
            
            ## **Potential Risks**  
            ### - The study presents minimal risks.  
            ### - Some scenarios may ask you to reflect on personal responsibility, which could cause minor emotional discomfort.  
            ### - If you feel uncomfortable, you can withdraw at any time.  
            
            ## **Eligibility Criteria:**  
            ### - Participants must be 18 or older, fluent in English, and score below the clinical threshold on pre-screening mental health questionnaires.  
            ### - Participants with diagnosed mental health disorders or high scores on these questionnaires are excluded.  
            
            ---
            
            ## **Data Handling and Privacy**  
            ### - Your data will be anonymised and used only for statistical purposes.  
            ### - No personal identifying information will be collected.  
            ### - The data will be securely stored and accessed only by authorised study personnel.
            
            ---
            
            ## **Reimbursement**  
            ### - You will not incur any costs for participating.  
            ### - Compensation will be provided through Prolific based on the time spent participating.
            ### - You will receive a partial completion code after each session, but full payment will only be processed upon completing all three sessions.
            
            ---
            
            ## **Withdrawal and Contact Information**  
            ### - You may withdraw at any time without providing a reason.  
            ### - If you experience any discomfort or have questions about the study, please contact the coordinators:  
            ####  - **Nace Mikus**: nace.mikus@univie.ac.at  
            ####  - **Jakob Möller**: a12028569@unet.univie.ac.at  
            
            ---
            
            ## **Acknowledgment**  
            ### By clicking "I Acknowledge and Consent" you confirm that:  
            ### - You have read and understood the information provided.  
            ### - You are aware of your right to withdraw at any time without consequences.  
            ### - You agree to participate in the study and for your anonymised data to be used for academic research.
            ---
            ### Please enter your Prolific ID before moving on:
            """)

            pid_input = gr.Textbox(label="Prolific ID (required)")
            pid_output = gr.Markdown()
            
            # Consent by pressing the button
            briefing_start_button = gr.Button("I Acknowledge and Consent")
    
    ########################################################################
    # Page 2: Pretest: PHQ-9
    ########################################################################

    with gr.Row(visible=False) as page_2:
        with gr.Column():
            # PHQ-9           
            gr.Markdown("""#### Over the last 2 weeks, how often have you been bothered by 
            #### any of the following problems (0 = "Never", 3 = "Very often")?""")
            
            q1 = gr.Radio(choices=["0", "1", "2", "3"], label="Little interest or pleasure in doing things?", value = "0")
            q2 = gr.Radio(choices=["0", "1", "2", "3"], label="Feeling down, depressed, or hopeless?", value = "0")
            q3 = gr.Radio(choices=["0", "1", "2", "3"], label="Trouble falling or staying asleep, or sleeping too much?", value = "0")
            q4 = gr.Radio(choices=["0", "1", "2", "3"], label="Feeling tired or having little energy?", value = "0")
            q5 = gr.Radio(choices=["0", "1", "2", "3"], label="Poor appetite or overeating?", value = "0")
            q6 = gr.Radio(choices=["0", "1", "2", "3"], label="Feeling bad about yourself?", value = "0")
            q7 = gr.Radio(choices=["0", "1", "2", "3"], label="Trouble concentrating?", value = "0")
            q8 = gr.Radio(choices=["0", "1", "2", "3"], label="Moving or speaking so slowly people noticed?", value = "0")
            phq_result = gr.Markdown()
            next_button = gr.Button("Next")
    
    ########################################################################
    # Page 3: Pretest: GAD-7
    ########################################################################

    with gr.Row(visible=False) as page_3:
        with gr.Column():
            gr.Markdown(""" 
            #### Over the last 2 weeks, how often have you been bothered by
            #### any of the following problems (0 = "Never", 3 = "Very often")?
            """)
            g1 = gr.Radio(choices=["0", "1", "2", "3"], label="Feeling nervous, anxious, or on edge?", value = "0")
            g2 = gr.Radio(choices=["0", "1", "2", "3"], label="Not being able to stop or control worrying?", value = "0")
            g3 = gr.Radio(choices=["0", "1", "2", "3"], label="Worrying too much about different things?", value = "0")
            g4 = gr.Radio(choices=["0", "1", "2", "3"], label="Trouble relaxing?", value = "0")
            g5 = gr.Radio(choices=["0", "1", "2", "3"], label="Being so restless that it’s hard to sit still?", value = "0")
            g6 = gr.Radio(choices=["0", "1", "2", "3"], label="Becoming easily annoyed or irritable?", value = "0")
            g7 = gr.Radio(choices=["0", "1", "2", "3"], label="Feeling afraid as if something awful might happen?", value = "0")
            gad_result = gr.HTML()
            finish_button = gr.Button("Finish")
    
    #######################################################################
    # Page 4: User Profile
    #######################################################################

    with gr.Row(visible=False) as page_4:
        with gr.Column():
            gr.Markdown("# Tell Us About Yourself")
            gr.Markdown("""### Great! During the course of this assessment you will be confronted with descriptions of fictional everyday situations. Please try to immerse yourself in these scenarios as if they were happening to you personally.

        ### You will encounter some scenarios that may be closely related to your personal interests or profession, and others that are more general or hypothetical. Please engage with each scenario to the best of your ability, even if it does not directly match your personal experiences. This mix of personalized and generic scenarios helps us understand how people respond in a variety of contexts.
        
        ### In order to provide you with situations that might be more relevant to you specifically, 
        ### we need some general information about you. Don't worry, you will remain anonymous!        
        
        ### Please tell us your age, profession and one of your personal interests.""")
            age_input = gr.Textbox(label="Age", placeholder="Enter your age (e.g., 25)", lines=1)
            profession_input = gr.Textbox(label="Profession", placeholder="Enter your profession (e.g., Engineer)", lines=1)
            interest_input = gr.Textbox(label="One personal interest", placeholder="Enter a hobby or interest (e.g., Painting)", lines=1)
        
            user_profile_button = gr.Button("Submit Profile")
            user_profile_output = gr.Markdown()
    
    #######################################################################
    # Page 5: Chatbot Assessment
    #######################################################################

    with gr.Row(visible=False) as page_5:
        with gr.Column():
            # Existing chatbot code
            gr.Markdown("""### Engage with the chatbot by typing your messages below and submitting with **Enter**. Don't worry, this chatbot does not have live access to the internet. Your data will only be processed locally.""")
            chatbot = gr.Chatbot(value = [(None, "Hello! I'm Evaline, I will guide you through a total of 12 scenarios during this assessment. This will approximately take 20-30 minutes. Are you ready to get started?")], label= "Evaline")
            user_message = gr.Textbox(placeholder="Type your message here...", label= "Your Message", lines=1)
    
            # Slider for Attributions (Initially Hidden)
            attribution_slider = gr.Slider(
                minimum=1,
                maximum=10,
                step=0.1,
                label="1 = Definitely Option A,                                 10 = Definitely Option B",
                visible=False,
                interactive=True,
                elem_classes=["custom-slider"]  # Apply custom CSS class
            )
            
            # Confirm Button for Slider (Initially Hidden)
            confirm_button = gr.Button("Confirm", visible=False)
            
            # Submit handler for text input
            user_message.submit(
                fn=new_chat_input,
                inputs=[chatbot, user_state, user_message],
                outputs=[chatbot, user_state, user_message, attribution_slider, confirm_button],
                queue=False
            )
         
            # Confirm handler for slider
            confirm_button.click(
                fn=slider_input,
                inputs=[chatbot, user_state, attribution_slider],
                outputs=[chatbot, user_state, user_message, attribution_slider, confirm_button],
                queue=False
            )
    
    ######################################################################
    # Transition Logic
    ######################################################################
    
    # 1) After Briefing, go to PHQ-9
    def store_pid_and_show_phq9(pid, user_state):
        # 1) Validate the PID
        pid = pid.strip()
        if not pid:
            return (
                "Error: Please enter your Prolific ID.",
                gr.update(visible=True),   # keep page_1 visible
                gr.update(visible=False),  # keep page_2 hidden
                user_state
            )
        # 2) Store the PID and create unique file name
        user_state["prolific_id"] = pid
        
        timestamp = time.strftime("%Y%m%d_%H%M%S")
        user_state["excel_file"] = f"Cond2_{pid}_{timestamp}.xlsx"  
        
        # 3) Hide page_1, show page_2
        return (
            f"Prolific ID {pid} recorded, now proceed to PHQ-9.",
            gr.update(visible=False),  # hide page_1
            gr.update(visible=True),   # show page_2
            user_state
        )
    
    briefing_start_button.click(
        fn=store_pid_and_show_phq9,
        inputs=[pid_input, user_state],
        outputs=[
            pid_output,
            page_1,    # hide page_1 (Briefing)
            page_2,    # show page_2 (PHQ-9)
            user_state]
    )
    
    # 2) After finishing PHQ-9, go to GAD-7
    def process_phq9_and_show_gad7(q1, q2, q3, q4, q5, q6, q7, q8, user_state):
        q1 = int(q1) if q1 is not None else 0
        q2 = int(q2) if q2 is not None else 0
        q3 = int(q3) if q3 is not None else 0
        q4 = int(q4) if q4 is not None else 0
        q5 = int(q5) if q5 is not None else 0
        q6 = int(q6) if q6 is not None else 0
        q7 = int(q7) if q7 is not None else 0
        q8 = int(q8) if q8 is not None else 0
       # q9 = int(q9) if q9 is not None else 0        
        
        # Store ID & compute PHQ-9
        user_state["phq_score"] = q1 + q2 + q3 + q4 + q5 + q6 + q7 + q8
    
        # On success, hide Page 2 & show Page 3
        return (
            f"PHQ-9 total = {user_state['phq_score']}. Proceed to GAD-7.",
            gr.update(visible=False),  # Hide page_2
            gr.update(visible=True),   # Show page_3
            user_state
        )
    
    next_button.click(
        fn=process_phq9_and_show_gad7,
        inputs=[q1, q2, q3, q4, q5, q6, q7, q8, user_state],
        outputs=[
            phq_result, 
            page_2,    # hide page_2 (PHQ-9)
            page_3,    # show page_3 (GAD-7)    
            user_state 
        ]
    )
    
    # 3) After finishing GAD-7, go to User Profile
    def process_gad7_and_show_user_profile(g1, g2, g3, g4, g5, g6, g7, user_state):
        # Ensure all GAD-7 inputs are integers
        g1 = int(g1) if g1 is not None else 0
        g2 = int(g2) if g2 is not None else 0
        g3 = int(g3) if g3 is not None else 0
        g4 = int(g4) if g4 is not None else 0
        g5 = int(g5) if g5 is not None else 0
        g6 = int(g6) if g6 is not None else 0
        g7 = int(g7) if g7 is not None else 0
    
        # Calculate combined score
        user_state["gad_score"] = g1 + g2 + g3 + g4 + g5 + g6 + g7
        combined_score = user_state["phq_score"] + user_state["gad_score"]
    
        if combined_score > 25:
            rejection_link = "https://app.prolific.com/submissions/complete?cc=C11ALNAE"
            rejection_message = (
                f"Unfortunately, your combined score indicates that you do not meet the inclusion criteria for this study. "
                f"Please complete your submission on Prolific using the following link: {rejection_link}"
            )
            return (
                rejection_message,
                gr.update(visible=True),   # Ensure the container for the message (page_3) is visible
                gr.update(visible=False),  # Hide page_4 so that only the rejection message is seen
                user_state,
            )
    
        user_state["eligible"] = True
    
        return (
            f"GAD-7 completed, total = {user_state['gad_score']}. Proceeding to user profile.",
            gr.update(visible=False),  # Hide page_3 (GAD-7)
            gr.update(visible=True),   # Show page_4 (User Profile)
            user_state,)
    
    finish_button.click(
        fn=process_gad7_and_show_user_profile,  # Updated function name
        inputs=[g1, g2, g3, g4, g5, g6, g7, user_state],
        outputs=[
            gad_result, 
            page_3,        # hide page_3 (GAD-7)
            page_4,       # show page_4 (User Profile)
            user_state]
    )
    
    # 4) After User Profile, go to Chatbot   
    def process_user_profile(age, profession, interest, user_state):
        
        # 1) Validate user input (check required fields)
        if not age.strip():
            return "Error: Please enter your age.", gr.update(visible=True), gr.update(visible=False), user_state
        if not profession.strip():
            return "Error: Please enter your profession.", gr.update(visible=True), gr.update(visible=False), user_state
        if not interest.strip():
            return "Error: Please enter a personal interest.", gr.update(visible=True), gr.update(visible=False), user_state
    
        # 2) Store in user_state
        user_state["standardized_data"]["Raw Age"] = age.strip()
        user_state["standardized_data"]["Raw Profession"] = profession.strip()
        user_state["standardized_data"]["Raw Interests"] = interest.strip()
        user_state["standardized_data"]["Age"] = age.strip()
        user_state["standardized_data"]["Profession"] = profession.strip()
        user_state["standardized_data"]["Interests"] = interest.strip()
        
        print(f"user_state at the end of show_chatbot_after_profile: {user_state}")
    
        return (
            "Profile submitted successfully. Proceeding to the chatbot.",
            gr.update(visible=False),  # Hide page_4 (User Profile)
            gr.update(visible=True),   # Show page_5 (Chatbot)
            user_state
        )
                
    user_profile_button.click(
        fn=process_user_profile,
        inputs=[age_input, profession_input, interest_input, user_state],
        outputs=[
            user_profile_output,
            page_4,     # hide page_4 (User Profile)
            page_5,      # show page_5 (Chatbot)
            user_state]
    )

            
app.launch()