B
File size: 118,583 Bytes
a022f28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24c2d48
a022f28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24c2d48
 
 
 
 
a022f28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24c2d48
 
 
a022f28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a839ec
a022f28
f3196ba
a022f28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
662807d
a022f28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf2f052
a022f28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a166f7
 
 
 
 
a022f28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a166f7
 
 
 
 
 
 
 
 
a022f28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a166f7
 
 
 
 
 
 
 
a022f28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a166f7
 
 
 
 
 
 
 
 
 
 
 
a022f28
7a166f7
 
a022f28
7a166f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a022f28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24c2d48
 
 
 
a022f28
24c2d48
a022f28
 
 
 
 
 
 
 
 
 
 
24c2d48
 
a022f28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
739d992
 
 
a022f28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
"""Gradio for the HOT No-AI Control condition.



Same UI shape as socratic / explanatory (chatbot panel left, argument

textbox right, end-session button) so the visual confound across the three

conditions is minimised. The difference is delivery: this condition has

no chat. After the participant submits their initial argument, the host

code calls the same `core.perfect_answer.generate_session_artifacts`

generator the bot conditions use, then renders the resulting essay as a

single piece of reading material in the chatbot panel.



Phases (implicit, driven by button clicks):

  Phase 1 (entry): chatbot shows the case; arg_input writes initial argument.

  Phase 2 (after Submit Initial confirm): host code runs the per-session

                   generator (around 15-30s blocking call, status message

                   shown). On success, two assistant messages appear: a

                   short intro line and the ~600-word perfect-answer essay.

                   arg_input becomes a notepad.

  Phase 3 (after End Session): notepad locked, done panel shown.



The discussion plan is generated as a side-output of the same generator

call and is logged at the top level of the session JSON for analyst use.

The participant never sees it; there is no bot agenda in this condition.



Schema 1.0 envelope is identical to socratic / explanatory: `condition`,

`run_mode`, `case_id`, `perfect_answer`, `discussion_plan`, `feedback`,

`essays`, `turns`. `turns` is always empty for this condition.

"""

import time
import gradio as gr

from core import SessionLogger, now_aest, get_next_client
from core.config_loader import BASE_DIR, CONFIG


# ============================================================
# Lockdown config (revise-check gate)
# ============================================================
_LOCKDOWN_CFG = (CONFIG.get("lockdown") if isinstance(CONFIG, dict) else None) or {}
LOCKDOWN_REVISE_CHECK = bool(_LOCKDOWN_CFG.get("revise_check", False))
print(f"[lockdown] revise_check={LOCKDOWN_REVISE_CHECK}", flush=True)


# Revise-check gate: word-level similarity ratio between initial argument
# and current argument. > REVISE_SIMILARITY_THRESHOLD means the participant
# has not revised enough (changed less than 10% of words) — block End
# Session with a modal asking them to revise more.
REVISE_SIMILARITY_THRESHOLD = 0.9
import difflib as _difflib


def _arg_word_similarity(initial_text, current_text):
    """Word-level SequenceMatcher ratio. 1.0 = identical, 0.0 = no overlap.

    Lowercased, whitespace-tokenised; punctuation kept on tokens."""
    a = (initial_text or "").lower().split()
    b = (current_text or "").lower().split()
    if not a or not b:
        return 0.0
    return _difflib.SequenceMatcher(None, a, b).ratio()


def _revise_gate_trigger_html():
    """Hidden element whose id triggers the revise-gate modal in JS."""
    nonce = str(int(time.time() * 1000))
    return f'<div id="revise-gate-trigger-{nonce}" style="display:none"></div>'


# ============================================================
# Tutorial image carousel — appears as a full-screen overlay on
# participant entry. Images live in `tutorial_images/` next to this app.py,
# named 01.png / 02.png / ... so they sort in display order. The folder
# scan is done once at startup; each image is base64-encoded and injected
# into the head as a JS array, so no runtime file serving is needed.
# ============================================================
import base64 as _b64
from pathlib import Path as _Path

_TUTORIAL_DIR = BASE_DIR / "tutorial_images"


def _load_tutorial_images_b64():
    """Scan tutorial_images/, sort by filename, return list of data URLs.

    Returns [] if folder is missing or empty (carousel won't render)."""
    if not _TUTORIAL_DIR.exists():
        return []
    out = []
    # ONLY .png accepted — earlier deploys left stale .webp on remote that
    # upload_folder won't auto-clean, so narrow the loader to ignore them.
    exts = {".png": "image/png"}
    for f in sorted(_TUTORIAL_DIR.iterdir()):
        if not f.is_file():
            continue
        mime = exts.get(f.suffix.lower())
        if not mime:
            continue
        try:
            raw = f.read_bytes()
            enc = _b64.b64encode(raw).decode("ascii")
            out.append(f"data:{mime};base64,{enc}")
        except Exception as e:
            print(f"[tutorial] skipping {f.name}: {e}", flush=True)
    return out


_TUTORIAL_IMAGES_B64 = _load_tutorial_images_b64()
print(f"[tutorial] loaded {len(_TUTORIAL_IMAGES_B64)} image(s)", flush=True)


def _build_tutorial_head():
    """Build the <style> + <script> block that injects:

      (1) a Welcome overlay shown first (Msg1 + 'Start walkthrough'),

      (2) a mixed walkthrough carousel that interleaves image slides and

          a Msg2 text slide; footer has Back + Next buttons, with 'Start'

          replacing Next on the last slide.



    Slides in order (no_ai condition):

        1-3: tutorial images 01..03

        4:   Msg2 text panel (reference-version explanation)

        5-6: tutorial images 04..05



    All advance buttons share the orange Gradio primary-button color.



    Returns empty string if there aren't enough images to fill the layout.

    """
    if len(_TUTORIAL_IMAGES_B64) < 5:
        return ""
    arr = "[" + ",".join(f'"{u}"' for u in _TUTORIAL_IMAGES_B64) + "]"
    return """

<style>

/* ----- Welcome overlay (shown first; Msg1) ----- */

#welcome-overlay {

    position: fixed;

    inset: 0;

    background: rgba(0, 0, 0, 0.78);

    z-index: 200001;

    display: flex;

    align-items: center;

    justify-content: center;

    padding: 24px;

}

#welcome-overlay .welcome-modal {

    background: #ffffff;

    border-radius: 16px;

    padding: 64px 72px;

    max-width: 760px;

    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.35);

    display: flex;

    flex-direction: column;

    gap: 36px;

    align-items: center;

    text-align: center;

    font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, "Apple Color Emoji", "Segoe UI Emoji", sans-serif;

}

#welcome-overlay .welcome-text {

    font-size: 1.45em;

    color: #1f2937;

    line-height: 1.6;

}

#welcome-overlay .welcome-btn {

    background: var(--button-primary-background-fill, #f59e0b);

    color: var(--button-primary-text-color, #fff);

    border: none;

    border-radius: 8px;

    padding: 14px 34px;

    font-size: 1.15em;

    font-weight: 600;

    cursor: pointer;

    font-family: inherit;

    transition: filter 0.15s ease;

}

#welcome-overlay .welcome-btn:hover {

    background: var(--button-primary-background-fill-hover, #d97706);

    filter: brightness(0.95);

}



/* ----- Walkthrough overlay (mixed image + text carousel) ----- */

#walkthrough-overlay {

    position: fixed;

    inset: 0;

    background: rgba(0, 0, 0, 0.92);

    z-index: 200000;

    display: flex;

    align-items: center;

    justify-content: center;

    padding: 0;

}

#walkthrough-overlay .walkthrough-img {

    max-width: 100vw;

    max-height: 100vh;

    object-fit: contain;

    display: none;

}

#walkthrough-overlay .walkthrough-text-modal {

    background: #ffffff;

    border-radius: 16px;

    padding: 64px 72px;

    max-width: 760px;

    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.35);

    text-align: center;

    font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;

    font-size: 1.45em;

    color: #1f2937;

    line-height: 1.6;

    display: none;

}

#walkthrough-overlay .walkthrough-text-modal b,

#walkthrough-overlay .walkthrough-text-modal strong {

    color: #111827;

}

#walkthrough-overlay .walkthrough-footer {

    position: fixed;

    bottom: 28px;

    left: 50%;

    transform: translateX(-50%);

    display: flex;

    align-items: center;

    gap: 18px;

    font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;

}

#walkthrough-overlay .walkthrough-counter {

    color: rgba(255, 255, 255, 0.92);

    background: rgba(0, 0, 0, 0.55);

    padding: 7px 14px;

    border-radius: 16px;

    font-size: 0.95em;

    font-variant-numeric: tabular-nums;

}

#walkthrough-overlay .walkthrough-back {

    background: transparent;

    color: rgba(255, 255, 255, 0.92);

    border: 1px solid rgba(255, 255, 255, 0.6);

    border-radius: 8px;

    padding: 10px 24px;

    font-size: 1em;

    font-weight: 600;

    cursor: pointer;

    font-family: inherit;

    transition: opacity 0.15s ease, background 0.15s ease;

}

#walkthrough-overlay .walkthrough-back:hover {

    background: rgba(255, 255, 255, 0.12);

}

#walkthrough-overlay .walkthrough-back:disabled {

    opacity: 0.3;

    cursor: not-allowed;

}

#walkthrough-overlay .walkthrough-next,

#walkthrough-overlay .walkthrough-done {

    background: var(--button-primary-background-fill, #f59e0b);

    color: var(--button-primary-text-color, #fff);

    border: none;

    border-radius: 8px;

    padding: 10px 28px;

    font-size: 1em;

    font-weight: 600;

    cursor: pointer;

    font-family: inherit;

    transition: filter 0.15s ease;

}

#walkthrough-overlay .walkthrough-next:hover,

#walkthrough-overlay .walkthrough-done:hover {

    background: var(--button-primary-background-fill-hover, #d97706);

    filter: brightness(0.95);

}

#walkthrough-overlay .walkthrough-done { display: none; }

#walkthrough-overlay.last-slide .walkthrough-done { display: inline-block; }

#walkthrough-overlay.last-slide .walkthrough-next { display: none; }

</style>

<script>

window.__TUTORIAL_IMAGES = """ + arr + """;

(function() {

    if (!Array.isArray(window.__TUTORIAL_IMAGES) || window.__TUTORIAL_IMAGES.length < 5) return;

    var started = false;



    // Recovery guard: if localStorage carries an unfinished session, the

    // RECOVERY_HEAD layer takes over (modal + restore flow). Skip welcome

    // and walkthrough entirely so the recovery modal can render cleanly.

    try {

        var raw = localStorage.getItem('answer_ca_session_v1');

        if (raw) {

            var st = JSON.parse(raw);

            if (st && st.session_id) {

                console.log('[walkthrough] skipped — recovery in progress for', st.session_id);

                return;

            }

        }

    } catch (e) { /* fall through to normal flow */ }



    // Msg2 HTML — kept here as a constant for easy edit. no_ai variant

    // describes the reference-version flow (no chatbot discussion).

    var MSG2_HTML =

        'The AI assistant will first generate a more developed version ' +

        'of your initial argument. This version is meant to help you ' +

        'reflect on and improve your reasoning.<br><br>' +

        'Read the AI-generated version carefully. You may continue ' +

        'chatting with the AI assistant about that version if you wish. ' +

        'Take from it what is useful, and <b>revise your own argument</b> ' +

        'on the right. When you are ready, submit your final revised version.';



    function buildWelcome() {

        var overlay = document.createElement('div');

        overlay.id = 'welcome-overlay';

        overlay.innerHTML =

            '<div class="welcome-modal">' +

              '<div class="welcome-text">' +

                'Welcome to the study.<br><br>' +

                'First, we will briefly show you how to use the interface.' +

              '</div>' +

              '<button type="button" class="welcome-btn">Start walkthrough</button>' +

            '</div>';

        document.body.appendChild(overlay);

        overlay.querySelector('.welcome-btn').addEventListener('click', function() {

            overlay.remove();

            buildWalkthrough();

        });

    }



    function buildWalkthrough() {

        var imgs = window.__TUTORIAL_IMAGES;

        // no_ai slide deck: image, image, image, text(Msg2), image, image

        var slides = [

            {type: 'image', src: imgs[0]},

            {type: 'image', src: imgs[1]},

            {type: 'image', src: imgs[2]},

            {type: 'text',  html: MSG2_HTML},

            {type: 'image', src: imgs[3]},

            {type: 'image', src: imgs[4]}

        ];

        var N = slides.length;

        var idx = 0;

        var overlay = document.createElement('div');

        overlay.id = 'walkthrough-overlay';

        overlay.innerHTML =

            '<img class="walkthrough-img" alt="Walkthrough slide">' +

            '<div class="walkthrough-text-modal"></div>' +

            '<div class="walkthrough-footer">' +

              '<button type="button" class="walkthrough-back">Back</button>' +

              '<span class="walkthrough-counter"></span>' +

              '<button type="button" class="walkthrough-next">Next</button>' +

              '<button type="button" class="walkthrough-done">Start</button>' +

            '</div>';

        document.body.appendChild(overlay);

        var img = overlay.querySelector('.walkthrough-img');

        var textModal = overlay.querySelector('.walkthrough-text-modal');

        var counter = overlay.querySelector('.walkthrough-counter');

        var backBtn = overlay.querySelector('.walkthrough-back');

        var nextBtn = overlay.querySelector('.walkthrough-next');

        var doneBtn = overlay.querySelector('.walkthrough-done');



        function update() {

            var s = slides[idx];

            if (s.type === 'image') {

                img.src = s.src;

                img.style.display = 'block';

                textModal.style.display = 'none';

            } else {

                textModal.innerHTML = s.html;

                textModal.style.display = 'block';

                img.style.display = 'none';

            }

            counter.textContent = (idx + 1) + ' / ' + N;

            backBtn.disabled = (idx === 0);

            overlay.classList.toggle('last-slide', idx === N - 1);

        }

        backBtn.addEventListener('click', function() {

            if (idx > 0) { idx--; update(); }

        });

        nextBtn.addEventListener('click', function() {

            if (idx < N - 1) { idx++; update(); }

        });

        doneBtn.addEventListener('click', function() {

            window.__walkthroughStartedAt = Date.now() / 1000;

            console.log('[walkthrough] recorded ts=' + window.__walkthroughStartedAt);

            overlay.remove();

        });

        update();

    }



    function start() {

        if (started) return;

        started = true;

        buildWelcome();

    }



    if (document.readyState === 'loading') {

        document.addEventListener('DOMContentLoaded', start);

    } else {

        start();

    }

})();

</script>

"""


TUTORIAL_HEAD = _build_tutorial_head()


# ============================================================
# Session-recovery layer (browser-side). localStorage keys are namespaced
# per condition (`answer_ca_session_v1` / `answer_ca_tab_id`) so other
# A_Ethic Spaces opened in the same browser do not collide. The touch-observer
# watches for clicks anywhere on the chatbot (covers aha/ugh reactions) and
# arg_input edits and send-button clicks to keep `last_touched` fresh.
# ============================================================
RECOVERY_HEAD = """

<style>

.soc-hidden-helper,

#recover-session-id-input,

#recover-btn,

#recovery-payload {

    display: none !important;

}

#recovery-overlay {

    position: fixed;

    inset: 0;

    background: rgba(0, 0, 0, 0.78);

    z-index: 200002;

    display: flex;

    align-items: center;

    justify-content: center;

    padding: 24px;

}

#recovery-overlay .recovery-modal {

    background: #ffffff;

    border-radius: 16px;

    padding: 56px 64px;

    max-width: 640px;

    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.35);

    display: flex;

    flex-direction: column;

    gap: 28px;

    align-items: center;

    text-align: center;

    font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;

}

#recovery-overlay .recovery-title {

    font-size: 1.35em;

    font-weight: 600;

    color: #111827;

    line-height: 1.35;

}

#recovery-overlay .recovery-body {

    font-size: 1.05em;

    color: #374151;

    line-height: 1.55;

}

#recovery-overlay .recovery-actions {

    display: flex;

    gap: 14px;

    flex-wrap: wrap;

    justify-content: center;

}

#recovery-overlay .recovery-fresh,

#recovery-overlay .recovery-continue {

    border: none;

    border-radius: 8px;

    padding: 12px 28px;

    font-size: 1.05em;

    font-weight: 600;

    cursor: pointer;

    font-family: inherit;

    transition: filter 0.15s ease, background 0.15s ease;

}

#recovery-overlay .recovery-fresh {

    background: transparent;

    color: #4b5563;

    border: 1px solid #d1d5db;

}

#recovery-overlay .recovery-fresh:hover { background: #f3f4f6; }

#recovery-overlay .recovery-continue {

    background: var(--button-primary-background-fill, #f59e0b);

    color: var(--button-primary-text-color, #fff);

}

#recovery-overlay .recovery-continue:hover {

    background: var(--button-primary-background-fill-hover, #d97706);

    filter: brightness(0.95);

}

#recovery-overlay .recovery-loading {

    color: #6b7280;

    font-size: 0.95em;

    display: none;

}

#recovery-overlay.loading .recovery-actions { display: none; }

#recovery-overlay.loading .recovery-loading { display: block; }

#recovery-overlay .recovery-error {

    color: #b91c1c;

    font-size: 0.95em;

    display: none;

}

#recovery-overlay.error .recovery-error { display: block; }

#recovery-overlay.error .recovery-loading { display: none; }

#recovery-overlay.error .recovery-actions { display: flex; }

</style>

<script>

window.__RECOVERY = (function() {

    const STORAGE_KEY = 'answer_ca_session_v1';

    const TAB_KEY = 'answer_ca_tab_id';



    function getOrCreateTabId() {

        let tid = sessionStorage.getItem(TAB_KEY);

        if (!tid) {

            tid = 'tab_' + Date.now().toString(36) + '_' +

                  Math.random().toString(36).slice(2, 10);

            sessionStorage.setItem(TAB_KEY, tid);

        }

        return tid;

    }



    function readState() {

        try {

            const raw = localStorage.getItem(STORAGE_KEY);

            return raw ? JSON.parse(raw) : null;

        } catch (e) { return null; }

    }



    function writeState(state) {

        try { localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); }

        catch (e) { console.warn('[recovery] localStorage write failed', e); }

    }



    function clearState() {

        try { localStorage.removeItem(STORAGE_KEY); } catch (e) {}

    }



    function saveSession(sid, code) {

        writeState({

            tab_id: getOrCreateTabId(),

            session_id: sid,

            completion_code: code || '',

            last_touched: Date.now(),

        });

        console.log('[recovery] localStorage write — session_id =', sid);

    }



    function touchSession() {

        const s = readState();

        if (!s || !s.session_id) return;

        s.last_touched = Date.now();

        writeState(s);

    }



    function buildModal({title, body, freshLabel, continueLabel,

                        onFresh, onContinue}) {

        let existing = document.getElementById('recovery-overlay');

        if (existing) existing.remove();

        const overlay = document.createElement('div');

        overlay.id = 'recovery-overlay';

        overlay.innerHTML =

            '<div class="recovery-modal">' +

              '<div class="recovery-title">' + title + '</div>' +

              '<div class="recovery-body">' + body + '</div>' +

              '<div class="recovery-actions">' +

                '<button type="button" class="recovery-fresh">' + freshLabel + '</button>' +

                '<button type="button" class="recovery-continue">' + continueLabel + '</button>' +

              '</div>' +

              '<div class="recovery-loading">Restoring your session, please wait…</div>' +

              '<div class="recovery-error">Could not restore the session. Please start a new one.<br><span class="recovery-error-detail" style="display:block;margin-top:8px;font-size:0.85em;color:#6b7280;"></span></div>' +

            '</div>';

        document.body.appendChild(overlay);

        overlay.querySelector('.recovery-fresh').addEventListener('click', () => {

            overlay.remove();

            onFresh();

        });

        overlay.querySelector('.recovery-continue').addEventListener('click', () => {

            overlay.classList.add('loading');

            overlay.classList.remove('error');

            onContinue();

        });

        return overlay;

    }



    function triggerServerRecover(sid, attempt) {

        attempt = attempt || 0;

        const inputWrap = document.querySelector('#recover-session-id-input');

        const btnWrap = document.querySelector('#recover-btn');

        if (!inputWrap || !btnWrap) {

            if (attempt < 30) {

                if (attempt === 0) {

                    console.log('[recovery] hidden recover elements not yet in DOM, retrying');

                }

                setTimeout(() => triggerServerRecover(sid, attempt + 1), 200);

                return;

            }

            console.error('[recovery] hidden recover elements not found after 6s');

            const overlay = document.getElementById('recovery-overlay');

            if (overlay) {

                overlay.classList.remove('loading');

                overlay.classList.add('error');

                const detail = overlay.querySelector('.recovery-error-detail');

                if (detail) detail.textContent = '(reason: recover button missing from DOM)';

            }

            return;

        }

        const ta = inputWrap.querySelector('textarea') || inputWrap.querySelector('input');

        if (!ta) {

            console.error('[recovery] no input element inside #recover-session-id-input');

            return;

        }

        const setter = Object.getOwnPropertyDescriptor(

            window.HTMLTextAreaElement.prototype, 'value'

        )?.set || Object.getOwnPropertyDescriptor(

            window.HTMLInputElement.prototype, 'value'

        )?.set;

        if (setter) setter.call(ta, sid); else ta.value = sid;

        ta.dispatchEvent(new Event('input', { bubbles: true }));

        ta.dispatchEvent(new Event('change', { bubbles: true }));



        setTimeout(() => {

            const btn = btnWrap.querySelector('button') || btnWrap;

            btn.click();

            console.log('[recovery] recover-btn clicked, sid =', sid);

        }, 100);

    }



    function startTouchObserver() {

        // no_ai has no chat input — touch on any chatbot click (reactions)

        // and on arg_input keystrokes (which are the dominant activity in

        // this condition).

        document.addEventListener('click', function(e) {

            const cb = e.target.closest('#chatbot-main, #chatbot-main *');

            if (cb) touchSession();

        }, true);

        document.addEventListener('input', function(e) {

            const ta = e.target.closest('#right-essay textarea, #right-essay input');

            if (ta) touchSession();

        }, true);

    }



    function startRecoveryCheck() {

        if (!document.body) { setTimeout(startRecoveryCheck, 100); return; }

        startTouchObserver();



        const state = readState();

        if (!state || !state.session_id) {

            console.log('[recovery] no saved session, normal flow');

            return;

        }

        const myTabId = getOrCreateTabId();

        const continueHandler = () => {

            state.tab_id = myTabId;

            state.last_touched = Date.now();

            writeState(state);

            triggerServerRecover(state.session_id);

        };

        const freshHandler = () => {

            clearState();

            console.log('[recovery] user chose Start fresh — localStorage cleared');

            location.reload();

        };

        if (state.tab_id && state.tab_id !== myTabId) {

            buildModal({

                title: '<b>Session open in another tab</b>',

                body: 'A previous session appears to be open in another browser tab. ' +

                      'You can take it over here (the other tab will go out of sync), ' +

                      'or start a new session.',

                freshLabel: 'Start a new session',

                continueLabel: 'Take over here',

                onFresh: freshHandler,

                onContinue: continueHandler,

            });

        } else {

            buildModal({

                title: '<b>Continue your previous session?</b>',

                body: 'Your previous session was not completed. ' +

                      'Would you like to continue where you left off, or start a new session?',

                freshLabel: 'Start a new session',

                continueLabel: 'Continue',

                onFresh: freshHandler,

                onContinue: continueHandler,

            });

        }

    }



    if (document.readyState === 'loading') {

        document.addEventListener('DOMContentLoaded', startRecoveryCheck);

    } else {

        startRecoveryCheck();

    }



    return {

        saveSession: saveSession,

        clearState: clearState,

        dismissModalIfLoading: function() {

            const overlay = document.getElementById('recovery-overlay');

            if (overlay && overlay.classList.contains('loading')) {

                overlay.remove();

            }

        },

        markModalError: function(reason) {

            const overlay = document.getElementById('recovery-overlay');

            if (overlay) {

                overlay.classList.remove('loading');

                overlay.classList.add('error');

                const detail = overlay.querySelector('.recovery-error-detail');

                if (detail) {

                    detail.textContent = reason

                        ? '(reason: ' + reason + ')'

                        : '';

                }

            }

        },

    };

})();

</script>

"""


# ============================================================
# Revise-check gate: modal styling + JS watcher + a flags block so the
# watcher can early-return when revise_check is OFF in config.
# ============================================================
_LOCKDOWN_FLAGS_JS = f"""<script>

window.__LOCKDOWN = {{

    reviseCheck: {str(LOCKDOWN_REVISE_CHECK).lower()}

}};

</script>"""

REVISE_GATE_HEAD = """

<style>

/* Revise-check gate modal — shown when the participant tries End Session

   with an argument too similar to their initial submission. */

#revise-gate-overlay {

    position: fixed;

    inset: 0;

    background: rgba(0, 0, 0, 0.78);

    z-index: 200001;

    display: flex;

    align-items: center;

    justify-content: center;

    padding: 24px;

}

#revise-gate-overlay .revise-gate-modal {

    background: #ffffff;

    border-radius: 14px;

    padding: 36px 44px;

    max-width: 620px;

    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.35);

    display: flex;

    flex-direction: column;

    gap: 18px;

    align-items: center;

    text-align: center;

    font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, "Apple Color Emoji", "Segoe UI Emoji", sans-serif;

}

#revise-gate-overlay .revise-gate-title,

#revise-gate-overlay .revise-gate-body,

#revise-gate-overlay .revise-gate-btn {

    font-family: inherit;

}

#revise-gate-overlay .revise-gate-title {

    font-size: 1.35em;

    color: #1f2937;

    line-height: 1.35;

}

#revise-gate-overlay .revise-gate-body {

    font-size: 1em;

    color: #4b5563;

    line-height: 1.5;

}

#revise-gate-overlay .revise-gate-btn {

    background: var(--button-primary-background-fill, #f59e0b);

    color: var(--button-primary-text-color, #fff);

    border: none;

    border-radius: 8px;

    padding: 12px 28px;

    font-size: 1.05em;

    cursor: pointer;

    transition: filter 0.15s ease;

}

#revise-gate-overlay .revise-gate-btn:hover {

    background: var(--button-primary-background-fill-hover, #d97706);

    filter: brightness(0.95);

}

</style>

<script>

// --- Revise-check gate modal watcher ---

// Server emits <div id="revise-gate-trigger-NONCE"> in the done_panel when

// the participant clicks End Session but their current argument is still

// > 90% similar to the initial submission. Watcher creates a full-screen

// modal; the "Go back and revise" button dismisses it so they can edit.

(function() {

    if (!window.__LOCKDOWN || !window.__LOCKDOWN.reviseCheck) return;

    const SEEN = new Set();

    function buildOverlay() {

        let existing = document.getElementById('revise-gate-overlay');

        if (existing) existing.remove();

        const overlay = document.createElement('div');

        overlay.id = 'revise-gate-overlay';

        overlay.innerHTML =

            '<div class="revise-gate-modal">' +

              '<div class="revise-gate-body">' +

                'Please revise at least 10% of your argument before submitting your final version.' +

              '</div>' +

              '<button type="button" class="revise-gate-btn"><b>Go back to argument</b></button>' +

            '</div>';

        document.body.appendChild(overlay);

        overlay.querySelector('.revise-gate-btn').addEventListener('click', function() {

            overlay.remove();

        });

    }

    function scan() {

        document.querySelectorAll('[id^="revise-gate-trigger-"]').forEach(function(el) {

            if (SEEN.has(el.id)) return;

            SEEN.add(el.id);

            buildOverlay();

        });

    }

    function start() {

        if (!document.body) { setTimeout(start, 100); return; }

        scan();

        const obs = new MutationObserver(scan);

        obs.observe(document.body, { childList: true, subtree: true });

    }

    if (document.readyState === 'loading') {

        document.addEventListener('DOMContentLoaded', start);

    } else {

        start();

    }

})();

</script>

"""


from core.content_sync import sync_chapters_from_ssot
from core.perfect_answer import generate_session_artifacts
from core.config_loader import client as OAI_CLIENT, MODEL as OAI_MODEL, GENERAL_CHAT_PROMPT


# Mirror generator inputs (case_analysis.md, ethics-frameworks.md) from
# shared_content/ into local data/. Local-only, no-op on HF Space.
sync_chapters_from_ssot()


# ============================================================
# Content
# ============================================================

CONTENT_DIR = BASE_DIR / "content"


def _load(name):
    p = CONTENT_DIR / name
    if p.exists():
        return p.read_text(encoding="utf-8")
    return f"*[Missing: content/{name}]*"


CASE_TEXT = _load("case_1.md")

# Display version of the case strips the leading H1 ("# Case: ...") so the
# title is not shown in the chatbot panel. The LLM still receives the full
# CASE_TEXT if any future flow needs it.
def _strip_leading_h1(md: str) -> str:
    lines = md.lstrip("\n").split("\n")
    if lines and lines[0].lstrip().startswith("# "):
        return "\n".join(lines[1:]).lstrip("\n")
    return md
CASE_TEXT_DISPLAY = _strip_leading_h1(CASE_TEXT)


INTRO_MESSAGE = (
    "**Thanks for submitting your initial argument.**\n\n"
    "Below is a more developed and refined version based on your argument. "
    "**Read it carefully, and decide how, or whether, you want to use it "
    "when revising your argument on the right.** You may optionally continue "
    "chatting with the AI assistant if you want to ask about the generated "
    "version or explore the issue further.\n\n"
    "When you are happy with your revised version, click "
    "**'End session & finalize'** on the right to lock your submission "
    "and end the session."
)


# ============================================================
# UI constants
# ============================================================

INITIAL_CHATBOT_VALUE = [{"role": "assistant", "content": CASE_TEXT_DISPLAY}]

SUBMIT_INITIAL_LABEL = "Submit initial argument"
SUBMIT_INITIAL_CONFIRM_LABEL = "✓ Click again to confirm submission"
END_SESSION_LABEL = "End session & finalize · no return"
END_SESSION_CONFIRM_LABEL = "✓ Click again to confirm end session"
ARM_TTL = 10.0


# ============================================================
# End-of-session "completion code" modal — shown when the participant
# confirms End Session. The code (5-char alphanumeric, generated in
# SessionLogger.start_session) is what participants paste into the
# Qualtrics survey page so the researcher can join the dialogue log to
# the rest of the survey response. Same modal also appears on upload
# failure (with a warning tone) so the participant can still complete
# Qualtrics and so the researcher gets the code to recover manually.
# ============================================================

SAVING_PANEL_HTML = (
    '<div class="saving-panel">'
    '<h3>⏳ Submitting your session to our records.</h3>'
    '<p>This can take up to a minute under heavy server load. '
    "Please don't close the page.</p>"
    '</div>'
)


def _completion_modal_html(flush_result):
    """Build the full-screen completion-code modal HTML.

    The participant-facing display string is `BotThanksU` + the 5-digit

    code (e.g. `BotThanksU23548`); the log filename and the

    `completion_code` field stored in the log envelope contain ONLY the

    5 digits. The decorative prefix is added here at display time so the

    Qualtrics paste-back is recognisable as having come from the bot."""
    status = (flush_result or {}).get("status", "no_logger")
    code = (flush_result or {}).get("completion_code") or ""
    display_code = f"BotThanksU{code}" if code else "UNKNOWN"
    if status in ("uploaded_primary", "uploaded_recovery"):
        title = "✅ Session complete"
        message = (
            "Your session has been saved. Copy the completion code below "
            "and paste it into the Qualtrics survey page to continue."
        )
        warning_cls = ""
    elif status == "all_failed":
        title = "⚠ Session ended"
        message = (
            "Your session is finished, but the upload could not be confirmed. "
            "Copy the completion code below — paste it into the Qualtrics "
            "page <em>and</em> share it with the researcher so they can "
            "recover your data."
        )
        warning_cls = " completion-warning"
    else:  # no_logger / unexpected
        title = "Session ended"
        message = (
            "Copy the code below and paste it into the Qualtrics survey "
            "page to continue."
        )
        warning_cls = ""
    js_close = ("document.getElementById('completion-overlay-root')"
                ".style.display='none';")
    # Inline copy-to-clipboard: replace the button label with 'Copied ✓'
    # for 2 seconds, then restore.
    js_copy = (
        f"var b=this;navigator.clipboard.writeText('{display_code}').then("
        "function(){b.textContent='Copied \\u2713';"
        "setTimeout(function(){b.textContent='Copy';},2000);});"
    )
    return (
        f'<div class="completion-overlay{warning_cls}" '
        f'id="completion-overlay-root">'
        f'<div class="completion-modal-box">'
        f'<button class="completion-close" type="button" '
        f'title="Close" onclick="{js_close}">×</button>'
        f'<div class="completion-title">{title}</div>'
        f'<div class="completion-instructions">{message}</div>'
        f'<div class="completion-code-row">'
        f'<div class="completion-code" id="completion-code-value">{display_code}</div>'
        f'<button class="completion-copy" type="button" '
        f'onclick="{js_copy}">Copy</button>'
        f'</div>'
        f'</div>'
        f'</div>'
    )


COMPLETION_MODAL_CSS = """

/* End-of-session completion-code modal overlay (full-screen). */

.completion-overlay {

    position: fixed;

    top: 0; left: 0; right: 0; bottom: 0;

    background: rgba(0, 0, 0, 0.55);

    z-index: 99999;

    display: flex;

    align-items: center;

    justify-content: center;

    padding: 20px;

}

.completion-modal-box {

    position: relative;

    background: white;

    border-radius: 12px;

    padding: 36px 40px 28px;

    max-width: 560px;

    width: 100%;

    box-shadow: 0 24px 64px rgba(0, 0, 0, 0.35);

    font-size: 1.05em;

    line-height: 1.55;

}

.completion-overlay.completion-warning .completion-modal-box {

    border-top: 4px solid #f59e0b;

}

.completion-close {

    position: absolute;

    top: 8px; right: 12px;

    background: transparent;

    border: none;

    font-size: 1.5em;

    color: #6b7280;

    cursor: pointer;

    line-height: 1;

    padding: 4px 10px;

    border-radius: 4px;

}

.completion-close:hover { color: #111827; background: #f3f4f6; }

.completion-title {

    font-size: 1.4em;

    font-weight: 600;

    margin-bottom: 14px;

    color: #16a34a;

}

.completion-overlay.completion-warning .completion-title { color: #b45309; }

.completion-instructions {

    margin-bottom: 22px;

    color: #1f2937;

}

.completion-code-row {

    display: flex;

    align-items: stretch;

    gap: 10px;

    margin-bottom: 14px;

}

.completion-code {

    font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;

    font-size: 1.7em;

    font-weight: 700;

    letter-spacing: 0.18em;

    padding: 14px 18px;

    background: #f3f4f6;

    border-radius: 8px;

    flex: 1;

    user-select: all;

    text-align: center;

    color: #111827;

}

.completion-copy {

    padding: 0 24px;

    background: #2563eb;

    color: white;

    border: none;

    border-radius: 8px;

    cursor: pointer;

    font-size: 1em;

    font-weight: 500;

    white-space: nowrap;

}

.completion-copy:hover { background: #1d4ed8; }

.completion-note {

    font-size: 0.9em;

    color: #6b7280;

}



/* Inline saving panel (shown while flush is running, before the modal). */

.saving-panel {

    padding: 16px 22px;

    background: #fefce8;

    border: 1px solid #fde68a;

    border-radius: 8px;

    margin-top: 12px;

}

.saving-panel h3 { margin: 0 0 6px 0; font-size: 1.05em; font-weight: 600; }

.saving-panel p { margin: 0; color: #57534e; }

"""


CUSTOM_CSS = """

/* Hide Gradio's built-in copy button on chatbot messages. Aha/ugh buttons

   live in custom HTML siblings so this selector only catches the

   framework's copy icon. */

#chatbot-main button[aria-label*="opy" i],

#chatbot-main button[title*="opy" i],

#chatbot-main .copy-button,

#chatbot-main .message-buttons-copy,

#chatbot-main [data-testid*="copy" i] {

    display: none !important;

}



/* Hide Gradio Chatbot top-bar chrome: the "Chatbot" label badge in the

   upper-left and the share / clear (trash) icons in the upper-right.

   show_label=False on gr.Chatbot covers the label in theory, but Gradio

   6.11 still renders a label badge plus share + clear buttons (and the

   chatbot class has no show_share_button kwarg), so we suppress them

   here. */

#chatbot-main label,

#chatbot-main > .label-wrap,

#chatbot-main > div > .label-wrap,

#chatbot-main button[aria-label*="hare" i],

#chatbot-main button[aria-label*="lear" i],

#chatbot-main button[aria-label*="elete" i],

#chatbot-main button[aria-label*="rash" i],

#chatbot-main button[title*="hare" i],

#chatbot-main button[title*="lear" i],

#chatbot-main button[title*="elete" i],

#chatbot-main button[title*="rash" i] {

    display: none !important;

}

/* NOTE: do NOT blanket-hide .icon-button-wrapper — the aha!/ugh.

   buttons (repurposed Like/Dislike) live in the same wrapper class

   as the share/clear/delete buttons. */



/* Extend Gradio container to full browser width. */

.gradio-container, .main, .wrap {

    max-width: 100% !important;

}

.gradio-container {

    padding-left: 12px !important;

    padding-right: 12px !important;

}



/* Right column: keep it inside the row's equal_height stretch. */

#right-col {

    gap: 4px !important;

}



/* Argument textbox: outer block has explicit 65vh height so the inner

   absolute-positioned textarea has a real container to fill. */

#right-essay {

    height: 55vh !important;

    position: relative !important;

    padding: 0 !important;

    margin: 0 !important;

    border: 1px solid var(--border-color-primary, #d1d5db) !important;

    border-radius: 8px !important;

    background: var(--background-fill-primary, #ffffff) !important;

    box-sizing: border-box !important;

    overflow: hidden !important;

}

#right-essay > div,

#right-essay .container,

#right-essay .input-container {

    position: static !important;

    transform: none !important;

    padding: 0 !important;

    margin: 0 !important;

    border: none !important;

    background: transparent !important;

    height: 100% !important;

    width: 100% !important;

}

#right-essay textarea {

    position: absolute !important;

    top: 10px !important;

    right: 10px !important;

    bottom: 10px !important;

    left: 10px !important;

    width: auto !important;

    height: auto !important;

    max-height: none !important;

    min-height: 0 !important;

    margin: 0 !important;

    padding: 12px 14px !important;

    border: 1px solid var(--border-color-primary, #e5e7eb) !important;

    border-radius: 6px !important;

    background: var(--background-fill-secondary, #f9fafb) !important;

    font-size: 1.25em !important;

    line-height: 1.6 !important;

    resize: none !important;

    box-sizing: border-box !important;

}



/* Custom label row: strip Gradio block padding + clamp with max-height

   so the row is exactly one line tall. */

#arg-label-row {

    margin: 0 4px 0 4px !important;

    padding: 0 !important;

    border: none !important;

    background: transparent !important;

    min-height: 0 !important;

    max-height: 40px !important;

    height: auto !important;

    overflow: visible !important;

}

#arg-label-row > *,

#arg-label-row > * > *,

#arg-label-row > * > * > * {

    margin: 0 !important;

    padding: 0 !important;

    border: none !important;

    background: transparent !important;

    min-height: 0 !important;

    height: auto !important;

}

.arg-label-row {

    display: flex !important;

    justify-content: space-between !important;

    align-items: baseline !important;

    width: 100%;

    line-height: 1.0 !important;

    white-space: nowrap;

}

#arg-label-row .arg-label-text {

    font-weight: 700 !important;

    font-size: 1.7em !important;

    color: var(--body-text-color, #111827) !important;

}

#arg-label-row #wc-display {

    font-weight: 600 !important;

    font-size: 1.5em !important;

    color: #b91c1c !important;

    transition: color 0.15s ease;

    white-space: nowrap;

}

#arg-label-row #wc-display.sufficient {

    color: #15803d !important;

}

/* Argument-side notice (the "Do not use external AI tools" reminder

   placed between the Your argument label row and the textbox). Same

   wrapper-flattening pattern as #arg-label-row so the gr.HTML block

   doesn't add Gradio padding. */

#arg-notice {

    margin: 6px 4px 8px 4px !important;

    padding: 0 !important;

    border: none !important;

    background: transparent !important;

    min-height: 0 !important;

    height: auto !important;

    overflow: visible !important;

    flex: none !important;

}

#arg-notice > *,

#arg-notice > * > *,

#arg-notice > * > * > * {

    margin: 0 !important;

    padding: 0 !important;

    border: none !important;

    background: transparent !important;

    min-height: 0 !important;

    height: auto !important;

    overflow: visible !important;

}

.arg-notice {

    background: #fef9c3 !important;

    border-left: 4px solid #d97706 !important;

    border-radius: 6px !important;

    padding: 8px 12px !important;

    font-size: 1.08em !important;

    line-height: 1.4 !important;

    color: #422006 !important;

}



/* Bottom-row buttons stay one-row tall (msg input is allowed to grow — see next rule) */

#send-btn button,

#bottom-action-col button {

    min-height: 42px !important;

    max-height: 42px !important;

}



/* Chat input auto-grows from 1 line up to ~6 lines, then scrolls internally.

   Pairs with lines=1, max_lines=6 on the gr.Textbox. */

#chat-input textarea {

    min-height: 42px !important;

    max-height: 160px !important;

}



/* Bottom-row symmetry. chat-row uses flex-end so Send stays at the bottom

   of the (possibly grown) input; action col stays centred. */

#chat-row { align-items: flex-end !important; justify-content: center !important; gap: 8px !important; }

#bottom-action-col { align-items: center !important; justify-content: center !important; gap: 8px !important; }

#send-btn { align-self: flex-end !important; flex-grow: 0 !important; }



#chatbot-main .message,

#chatbot-main .message p,

#chatbot-main .message li,

#chatbot-main .prose p,

#chatbot-main .prose li,

#chatbot-main .markdown p,

#chatbot-main .markdown li {

    font-size: 1.08em !important;

    line-height: 1.55 !important;

}



#feedback-hint {

    margin: 8px 4px 4px 4px !important;

    padding: 0 !important;

}

#guide-col {

    min-width: 0;

}

#feedback-hint {

    margin: 0 !important;

    padding: 0 !important;

}

.discussion-intro {

    background: #fef9c3;

    border-left: 4px solid #d97706;

    border-radius: 6px;

    padding: 10px 14px;

    font-size: 1.08em;

    line-height: 1.55;

    color: #713f12;

}

.discussion-intro-title {

    font-weight: 700;

    font-size: 1.05em;

    margin-bottom: 6px;

    color: #422006;

}

.discussion-intro-line {

    margin: 5px 0;

}

.discussion-intro-bullets {

    margin: 4px 0 0 0;

    padding-left: 18px;

}

.discussion-intro-bullets li {

    margin: 2px 0;

}

.discussion-intro-line svg,

.discussion-intro-bullets svg {

    vertical-align: -0.3em;

    margin: 0 2px;

}

/* Old .discussion-intro-title/body/feedback removed — replaced by compact

   2-line .discussion-intro-line layout above. */



/* Force the like/dislike buttons (which we repurpose as ✨/😳) to always

   be visible — Gradio's default is hover-only. Larger hit area too. */

button[aria-label="Like" i],

button[aria-label="Dislike" i],

button[aria-label="like" i],

button[aria-label="dislike" i] {

    opacity: 1 !important;

    visibility: visible !important;

    width: auto !important;

    min-width: 28px !important;

}



/* Highlight the currently-selected ✨/😳 button on a message. The

   data-emoji-active attribute is toggled by the click handler in

   EMOJI_SWAP_HEAD; same-emoji second click clears it (cancel). */

button[data-emoji-active="1"] {

    background-color: rgba(99, 102, 241, 0.18) !important;

    border: 1px solid rgba(99, 102, 241, 0.7) !important;

    border-radius: 6px !important;

    box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.15) !important;

}

"""


EMOJI_SWAP_HEAD = """

<script>

(function() {

    // Find the controls container that scopes a single message's aha!/ugh. pair.

    // Gradio renders both buttons as siblings; we clear the sibling when one

    // is activated so the pair is mutually exclusive per message.

    const findGroup = (btn) => btn.parentElement || btn;



    const onEmojiClick = (e) => {

        const btn = e.currentTarget;

        const wasActive = btn.dataset.emojiActive === '1';

        // Clear active state on all swapped buttons in the same group.

        findGroup(btn).querySelectorAll('button[data-emoji-swapped="1"]').forEach(b => {

            b.removeAttribute('data-emoji-active');

        });

        // Same-emoji second click = cancel; otherwise activate this one.

        if (!wasActive) btn.dataset.emojiActive = '1';

    };



    // detectKind: identify whether a button is the Gradio chatbot's

    // "like" or "dislike" button, robust across browser locales (the

    // target audience includes US users with English / Spanish (incl.

    // Mexican + Latin American) / French / Chinese (simplified +

    // traditional) / Hindi / Portuguese / German / etc. browsers).

    //

    // Layered detection in priority order:

    //   1. SVG class hint  (e.g. "lucide-thumbs-up" / "lucide-thumbs-down")

    //   2. SVG path data   (Lucide thumbs-up starts with "M7 10",

    //                       thumbs-down starts with "M17 14")

    //   3. aria-label substring match across locales

    //   4. title attribute substring match across locales

    // Returns 'like' | 'dislike' | null.

    const DISLIKE_TOKENS = [

        'dislike', 'thumbs down', 'thumb down',

        'unhelpful', 'not helpful', 'mark as dislike', 'rate down',

        'gefällt mir nicht', 'nicht gefällt', 'daumen runter', 'daumen nach unten',

        "je n'aime pas", "n'aime pas", 'pouce vers le bas', 'pouce en bas',

        'no me gusta', 'no gusta', 'pulgar abajo', 'pulgar hacia abajo',

        'não gostei', 'descurtir', 'não gosto', 'polegar para baixo',

        'non mi piace', 'pollice giù',

        '踩', '不喜欢', '不赞', '点踩',

        '不讚', '不喜歡', '倒讚',

        'नापसंद', 'napasand', 'na pasand',

        'よくない', '良くない', '싫어', 'не нравится',

    ];

    const LIKE_TOKENS = [

        'like', 'thumbs up', 'thumb up',

        'helpful', 'mark as like', 'rate up',

        'gefällt mir', 'daumen hoch', 'daumen nach oben',

        "j'aime", 'aime', 'pouce vers le haut', 'pouce en haut',

        'me gusta', 'pulgar arriba', 'pulgar hacia arriba',

        'gostei', 'curtir', 'gosto', 'polegar para cima',

        'mi piace', 'pollice su',

        '赞', '喜欢', '点赞',

        '讚', '喜歡',

        'पसंद', 'pasand',

        'いいね', '좋아', 'нравится',

    ];

    const matchTokens = (s, tokens) => {

        for (const k of tokens) {

            if (s.indexOf(k) !== -1) return true;

        }

        return false;

    };

    const detectKind = (btn) => {

        if (btn.querySelector('svg[class*="thumbs-up"]')) return 'like';

        if (btn.querySelector('svg[class*="thumbs-down"]')) return 'dislike';

        const paths = btn.querySelectorAll('svg path[d]');

        for (const path of paths) {

            const d = (path.getAttribute('d') || '').trim();

            if (d.startsWith('M7 10')) return 'like';

            if (d.startsWith('M17 14')) return 'dislike';

        }

        const al = (btn.getAttribute('aria-label') || '').trim().toLowerCase();

        if (al) {

            if (matchTokens(al, DISLIKE_TOKENS)) return 'dislike';

            if (matchTokens(al, LIKE_TOKENS)) return 'like';

        }

        const title = (btn.getAttribute('title') || '').trim().toLowerCase();

        if (title) {

            if (matchTokens(title, DISLIKE_TOKENS)) return 'dislike';

            if (matchTokens(title, LIKE_TOKENS)) return 'like';

        }

        return null;

    };



    const apply = (btn) => {

        if (btn.dataset.emojiSwapped === '1') return;

        const kind = detectKind(btn);

        if (kind === 'like') {

            btn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="2 6 116 54" aria-label="aha" style="height:20px;width:auto;display:block;overflow:visible"><g fill="#F59E0B" stroke="#D97706" stroke-width="1.3" stroke-linejoin="round" paint-order="stroke"><path transform="rotate(-8 17 44) translate(8 50) scale(0.016602 -0.016602)" d="M965 -66Q919 -66 819 34Q727 -10 657.0 -32.5Q587 -55 538 -55Q297 -55 176.5 74.0Q56 203 56 460Q56 701 234.0 872.5Q412 1044 660 1044Q755 1044 880 990Q1031 925 1031 839Q1031 803 1008 776Q998 736 992.5 675.5Q987 615 987 534Q987 343 1014 259Q1017 250 1060 155Q1099 69 1099 57Q1099 4 1058.5 -31.0Q1018 -66 965 -66ZM717 620Q717 652 721.5 693.5Q726 735 735 786Q715 796 699.5 800.5Q684 805 673 805Q537 805 435.0 698.5Q333 592 333 452Q333 318 381.0 250.5Q429 183 525 183Q587 183 642.5 203.5Q698 224 747 264Q717 502 717 620Z"/><path transform="rotate(5 41 34) translate(29 43) scale(0.020020 -0.020020)" d="M399 915Q472 987 555.5 1022.5Q639 1058 734 1058Q905 1058 980 962Q1036 890 1048 741Q1053 618 1059 494Q1075 333 1079 298Q1093 187 1113 104Q1118 83 1118 67Q1118 11 1075.5 -25.5Q1033 -62 976 -62Q875 -62 845 38Q821 119 801 266Q783 407 783 498Q783 523 785.5 573.5Q788 624 788 649Q788 723 786 735Q777 790 734 790Q623 790 533 688Q487 637 407 494Q407 132 372 58Q333 -24 248 -24Q192 -24 148.5 13.5Q105 51 105 106Q105 125 116 159Q123 181 128 429Q123 630 130 1098L132 1131Q138 1249 138 1289Q138 1320 128.5 1380.5Q119 1441 119 1472Q119 1529 160.0 1565.5Q201 1602 259 1602Q358 1602 392 1496Q411 1436 411 1312Q411 1212 405 1109Q399 1011 399 915Z"/><path transform="rotate(-6 62 45) translate(53 51) scale(0.016602 -0.016602)" d="M965 -66Q919 -66 819 34Q727 -10 657.0 -32.5Q587 -55 538 -55Q297 -55 176.5 74.0Q56 203 56 460Q56 701 234.0 872.5Q412 1044 660 1044Q755 1044 880 990Q1031 925 1031 839Q1031 803 1008 776Q998 736 992.5 675.5Q987 615 987 534Q987 343 1014 259Q1017 250 1060 155Q1099 69 1099 57Q1099 4 1058.5 -31.0Q1018 -66 965 -66ZM717 620Q717 652 721.5 693.5Q726 735 735 786Q715 796 699.5 800.5Q684 805 673 805Q537 805 435.0 698.5Q333 592 333 452Q333 318 381.0 250.5Q429 183 525 183Q587 183 642.5 203.5Q698 224 747 264Q717 502 717 620Z"/></g><g fill="#F59E0B" stroke="#D97706" stroke-width="1" stroke-linejoin="round"><rect x="82" y="17" width="4" height="23" rx="2" transform="rotate(13 84 28.5)"/><circle cx="82.5" cy="50" r="3.5"/><rect x="92" y="17" width="4" height="23" rx="2" transform="rotate(13 94 28.5)"/><circle cx="92.5" cy="50" r="3.5"/><rect x="102" y="17" width="4" height="23" rx="2" transform="rotate(13 104 28.5)"/><circle cx="102.5" cy="50" r="3.5"/></g></svg>`;

            btn.title = 'Aha \\u2014 this clicked for me (click again to cancel)';

            btn.dataset.emojiSwapped = '1';

            btn.addEventListener('click', onEmojiClick);

        } else if (kind === 'dislike') {

            btn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="2 6 115 64" aria-label="ugh." style="height:23px;width:auto;display:block;overflow:visible"><g fill="#8E7398" stroke="#5E4865" stroke-width="1.3" stroke-linejoin="round" paint-order="stroke"><path transform="rotate(6 18 42) translate(8 46) scale(0.017090 -0.017090)" d="M978 578Q978 511 979.0 376.0Q980 241 980 174Q980 153 983.5 111.5Q987 70 987 49Q987 -7 946.5 -43.5Q906 -80 847 -80Q764 -80 726 -5Q598 -52 461 -52Q319 -52 222 8Q113 77 92 209Q53 459 53 656Q53 786 83 953Q103 1066 218 1066Q276 1066 317.0 1029.5Q358 993 358 937Q358 893 343.5 799.0Q329 705 329 656Q329 515 338.5 409.5Q348 304 367 235Q392 224 415.5 218.0Q439 212 461 212Q572 212 705 244Q705 321 704 419Q702 536 702 587Q702 792 721 941Q736 1060 857 1060Q916 1060 958.0 1023.0Q1000 986 997 930Q978 549 978 578Z"/><path transform="rotate(3 43 40) translate(31 49) scale(0.018066 -0.018066)" d="M1029 596Q987 361 979 100Q969 -223 871 -369Q740 -564 407 -564Q18 -564 18 -410Q18 -355 53.0 -321.0Q88 -287 145 -287Q190 -287 274.0 -304.0Q358 -321 423 -321Q572 -321 643 -230Q711 -141 723 53Q672 1 608.0 -25.0Q544 -51 468 -51Q269 -51 144.5 78.5Q20 208 20 410Q20 682 186 850Q358 1024 651 1024Q745 1024 813.0 1001.0Q881 978 923 931Q1050 916 1050 781Q1050 714 1029 596ZM641 796Q472 796 378 685Q294 584 294 423Q294 304 339.0 244.0Q384 184 474 184Q556 184 639 279Q717 369 728 457Q747 553 772 756Q738 776 705.0 786.0Q672 796 641 796Z"/><path transform="rotate(8 67 38) translate(55 45) scale(0.018066 -0.018066)" d="M399 915Q472 987 555.5 1022.5Q639 1058 734 1058Q905 1058 980 962Q1036 890 1048 741Q1053 618 1059 494Q1075 333 1079 298Q1093 187 1113 104Q1118 83 1118 67Q1118 11 1075.5 -25.5Q1033 -62 976 -62Q875 -62 845 38Q821 119 801 266Q783 407 783 498Q783 523 785.5 573.5Q788 624 788 649Q788 723 786 735Q777 790 734 790Q623 790 533 688Q487 637 407 494Q407 132 372 58Q333 -24 248 -24Q192 -24 148.5 13.5Q105 51 105 106Q105 125 116 159Q123 181 128 429Q123 630 130 1098L132 1131Q138 1249 138 1289Q138 1320 128.5 1380.5Q119 1441 119 1472Q119 1529 160.0 1565.5Q201 1602 259 1602Q358 1602 392 1496Q411 1436 411 1312Q411 1212 405 1109Q399 1011 399 915Z"/></g><circle cx="84" cy="51" r="3.5" fill="#8E7398" stroke="#5E4865" stroke-width="1" stroke-linejoin="round"/><circle cx="96" cy="51" r="3.5" fill="#8E7398" stroke="#5E4865" stroke-width="1" stroke-linejoin="round"/><circle cx="108" cy="51" r="3.5" fill="#8E7398" stroke="#5E4865" stroke-width="1" stroke-linejoin="round"/></svg>`;

            btn.title = 'Stress \\u2014 this made me uncomfortable (click again to cancel)';

            btn.dataset.emojiSwapped = '1';

            btn.addEventListener('click', onEmojiClick);

        }

    };

    // aha (like) must sit on the LEFT, ugh (dislike) on the RIGHT. Gradio's

    // default sibling order is not guaranteed, so enforce it; only move when

    // out of order to avoid per-tick DOM churn.

    const reorder = () => {

        // Locale-independent reorder: identify swapped buttons via the

        // aria-label of our injected aha / ugh inner SVG (which we control),

        // not via Gradio's button aria-label (which is localized).

        document.querySelectorAll('button[data-emoji-swapped="1"] svg[aria-label="ugh."]').forEach(sv => {

            const dis = sv.closest('button');

            if (!dis) return;

            const grp = dis.parentElement;

            if (!grp) return;

            const likeSvg = grp.querySelector('svg[aria-label="aha"]');

            const like = likeSvg ? likeSvg.closest('button') : null;

            if (like && (like.compareDocumentPosition(dis) & Node.DOCUMENT_POSITION_PRECEDING)) {

                grp.insertBefore(like, dis);

            }

        });

    };

    const sweep = () => {

        document.querySelectorAll('button[aria-label]').forEach(apply);

        reorder();

    };

    // Run every 400ms — cheap, and catches buttons no matter when Gradio renders them.

    setInterval(sweep, 400);

    // Also run on DOM ready in case the interval hasn't ticked yet.

    if (document.readyState !== 'loading') sweep();

    else document.addEventListener('DOMContentLoaded', sweep);

})();

</script>

<script>

// Live word counter for the argument textbox + submit-button gate.

// Pure JS: listens to input event on the textarea, updates count display

// every keystroke with zero server round-trip. Threshold 100 words.

// When count < 100, the submit-initial-btn is disabled (visual + click).

(function() {

    const THRESHOLD = 100;

    function countWords(text) {

        const t = (text || '').trim();

        if (!t) return 0;

        return t.split(/\\s+/).length;

    }

    function findSubmitBtn() {

        return document.querySelector('button#submit-initial-btn')

            || document.querySelector('#submit-initial-btn button')

            || document.querySelector('#submit-initial-btn');

    }

    function update() {

        const ta = document.querySelector('#right-essay textarea');

        const disp = document.querySelector('#wc-display');

        if (!ta) return;

        const n = countWords(ta.value);

        const ok = n >= THRESHOLD;

        const wordWord = n === 1 ? ' word' : ' words';

        const text = ok

            ? n + wordWord + ' ✓'

            : n + wordWord + ' (need at least ' + THRESHOLD + ')';

        if (disp) {

            disp.textContent = text;

            if (ok) disp.classList.add('sufficient');

            else disp.classList.remove('sufficient');

        }

        const btn = findSubmitBtn();

        if (btn && btn.tagName === 'BUTTON') {

            btn.disabled = !ok;

            btn.style.opacity = ok ? '' : '0.5';

            btn.style.cursor = ok ? '' : 'not-allowed';

            btn.title = ok ? '' : 'Write at least ' + THRESHOLD + ' words to enable';

        }

    }

    function attach() {

        const ta = document.querySelector('#right-essay textarea');

        if (ta && ta.dataset.wcAttached !== '1') {

            ta.addEventListener('input', update);

            ta.dataset.wcAttached = '1';

        }

        update();

    }

    setInterval(attach, 500);

    if (document.readyState !== 'loading') attach();

    else document.addEventListener('DOMContentLoaded', attach);

})();

</script>

"""


# ============================================================
# Hide HuggingFace Spaces floating widget that appears on .hf.space
# direct URLs. The widget shows the repo name, a like button, and an
# X to dismiss. We want it to never appear for participants.
# CSS targets HF's common class patterns; JS sweeps top-level body
# children that match an HF Spaces signature and removes them.
# ============================================================

HIDE_HF_WIDGET_HEAD = """

<style>

/* Broad CSS targeting HF Spaces injected chrome. Class names are unstable

   so we shotgun common patterns, and also nuke any anchor that links back

   to huggingface.co at the top level. */

.space-header, .hf-spaces-header, .spaces-banner,

[class*="space-header"],

[class*="spaces-header"],

[class*="spaces-tag"],

[class*="spaces-card"],

[class*="spaces-banner"],

[class*="hf-spaces"],

[class*="HfSpace"],

[class*="SpaceHeader"],

[class*="SpaceTag"],

[id*="space-header"],

[id*="hf-spaces"],

[data-testid*="space-header"],

[data-testid*="space-info"] {

    display: none !important;

    visibility: hidden !important;

    pointer-events: none !important;

    height: 0 !important;

    width: 0 !important;

    overflow: hidden !important;

}

/* Body-direct anchors to HF (the floating "powered by" badge usually links there) */

body > a[href*="huggingface.co"],

body > a[href*="hf.co"] {

    display: none !important;

}

</style>

<script>

(function() {

    // HF injects a floating widget on .hf.space direct URLs. Class names

    // change, so we use 3 detection strategies:

    //   (1) text signatures (repo path, "Built with", "Hugging Face"),

    //   (2) link signature (contains a link to huggingface.co / hf.co),

    //   (3) position heuristic (small fixed/absolute element in a corner,

    //       not inside our gradio container, not our own toast).

    const SIGNATURES = [

        'AE-Talk-bot/',

        'huggingface.co/',

        'hf.co/',

        'Hugging Face',

        'Built with',

    ];

    const SAFE_IDS = new Set([

        'root', 'gradio-app',

        '__arg_lockdown_toast__'

    ]);

    function isSafe(el) {

        if (!el) return true;

        if (SAFE_IDS.has(el.id)) return true;

        if (el.classList && el.classList.contains('gradio-container')) return true;

        if (el.tagName === 'SCRIPT' || el.tagName === 'STYLE' ||

            el.tagName === 'LINK' || el.tagName === 'META' ||

            el.tagName === 'NOSCRIPT' || el.tagName === 'IFRAME') return true;

        // If the element CONTAINS our gradio root, it must not be hidden

        if (el.querySelector && el.querySelector('.gradio-container, #root, #gradio-app, gradio-app')) return true;

        return false;

    }

    function looksLikeHfWidget(el) {

        if (!el || el.nodeType !== 1) return false;

        if (isSafe(el)) return false;

        const txt = (el.textContent || '').trim();

        // Strategy 1: text signatures (small badge text only)

        if (txt.length > 0 && txt.length < 400) {

            for (const sig of SIGNATURES) {

                if (txt.includes(sig)) return true;

            }

        }

        // Strategy 2: contains a link to HF

        if (el.querySelector && el.querySelector('a[href*="huggingface.co"], a[href*="hf.co"]')) {

            return true;

        }

        // Strategy 3: HF-shaped class / id names

        const cls = (el.className && el.className.toString) ? el.className.toString() : '';

        if (/(^|[^a-z])(hf|huggingface)[-_]/i.test(cls)) return true;

        if (/space[s-]?(header|tag|banner|card|info|badge|widget|overlay)/i.test(cls)) return true;

        const idAttr = el.id || '';

        if (/(^|[^a-z])(hf|huggingface)[-_]/i.test(idAttr)) return true;

        // Strategy 4: position heuristic for small floating badges

        try {

            const style = window.getComputedStyle(el);

            if ((style.position === 'fixed' || style.position === 'absolute') &&

                txt.length > 0 && txt.length < 200) {

                const rect = el.getBoundingClientRect();

                if (rect.width > 0 && rect.width < 400 &&

                    rect.height > 0 && rect.height < 120) {

                    const inCorner =

                        (rect.top < 120 || rect.bottom > window.innerHeight - 120) &&

                        (rect.left < 120 || rect.right > window.innerWidth - 120);

                    if (inCorner) return true;

                }

            }

        } catch (e) { /* ignore */ }

        return false;

    }

    function nuke(el) {

        try {

            el.style.setProperty('display', 'none', 'important');

            el.style.setProperty('visibility', 'hidden', 'important');

            el.setAttribute('hidden', '');

            console.log('[hf-widget-hide] removed', el.tagName, el.id || '', el.className || '');

        } catch (e) { /* ignore */ }

    }

    function sweep() {

        if (!document.body) return;

        // Direct body children first

        Array.from(document.body.children).forEach(el => {

            if (looksLikeHfWidget(el)) nuke(el);

        });

        // Also check direct html children (some injection patterns put nodes there)

        Array.from(document.documentElement.children).forEach(el => {

            if (el.tagName === 'BODY' || el.tagName === 'HEAD') return;

            if (looksLikeHfWidget(el)) nuke(el);

        });

        // Sweep any body-level <a> pointing to HF

        document.querySelectorAll('body > a[href*="huggingface.co"], body > a[href*="hf.co"]').forEach(nuke);

    }

    if (document.readyState === 'loading') {

        document.addEventListener('DOMContentLoaded', sweep);

    } else {

        sweep();

    }

    function attachObserver() {

        if (!document.body) return;

        const obs = new MutationObserver(sweep);

        obs.observe(document.body, { childList: true, subtree: false });

        obs.observe(document.documentElement, { childList: true, subtree: false });

    }

    if (document.body) {

        attachObserver();

    } else {

        document.addEventListener('DOMContentLoaded', attachObserver);

    }

    // Fallback: re-sweep every 1.5s for the first 30s, in case HF injects late

    let ticks = 0;

    const iv = setInterval(() => {

        sweep();

        if (++ticks >= 20) clearInterval(iv);

    }, 1500);

})();

</script>

"""


_AHA_INLINE_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="2 6 116 54" aria-label="aha" style="height:1.2em;width:auto;display:inline-block;overflow:visible"><g fill="#F59E0B" stroke="#D97706" stroke-width="1.3" stroke-linejoin="round" paint-order="stroke"><path transform="rotate(-8 17 44) translate(8 50) scale(0.016602 -0.016602)" d="M965 -66Q919 -66 819 34Q727 -10 657.0 -32.5Q587 -55 538 -55Q297 -55 176.5 74.0Q56 203 56 460Q56 701 234.0 872.5Q412 1044 660 1044Q755 1044 880 990Q1031 925 1031 839Q1031 803 1008 776Q998 736 992.5 675.5Q987 615 987 534Q987 343 1014 259Q1017 250 1060 155Q1099 69 1099 57Q1099 4 1058.5 -31.0Q1018 -66 965 -66ZM717 620Q717 652 721.5 693.5Q726 735 735 786Q715 796 699.5 800.5Q684 805 673 805Q537 805 435.0 698.5Q333 592 333 452Q333 318 381.0 250.5Q429 183 525 183Q587 183 642.5 203.5Q698 224 747 264Q717 502 717 620Z"/><path transform="rotate(5 41 34) translate(29 43) scale(0.020020 -0.020020)" d="M399 915Q472 987 555.5 1022.5Q639 1058 734 1058Q905 1058 980 962Q1036 890 1048 741Q1053 618 1059 494Q1075 333 1079 298Q1093 187 1113 104Q1118 83 1118 67Q1118 11 1075.5 -25.5Q1033 -62 976 -62Q875 -62 845 38Q821 119 801 266Q783 407 783 498Q783 523 785.5 573.5Q788 624 788 649Q788 723 786 735Q777 790 734 790Q623 790 533 688Q487 637 407 494Q407 132 372 58Q333 -24 248 -24Q192 -24 148.5 13.5Q105 51 105 106Q105 125 116 159Q123 181 128 429Q123 630 130 1098L132 1131Q138 1249 138 1289Q138 1320 128.5 1380.5Q119 1441 119 1472Q119 1529 160.0 1565.5Q201 1602 259 1602Q358 1602 392 1496Q411 1436 411 1312Q411 1212 405 1109Q399 1011 399 915Z"/><path transform="rotate(-6 62 45) translate(53 51) scale(0.016602 -0.016602)" d="M965 -66Q919 -66 819 34Q727 -10 657.0 -32.5Q587 -55 538 -55Q297 -55 176.5 74.0Q56 203 56 460Q56 701 234.0 872.5Q412 1044 660 1044Q755 1044 880 990Q1031 925 1031 839Q1031 803 1008 776Q998 736 992.5 675.5Q987 615 987 534Q987 343 1014 259Q1017 250 1060 155Q1099 69 1099 57Q1099 4 1058.5 -31.0Q1018 -66 965 -66ZM717 620Q717 652 721.5 693.5Q726 735 735 786Q715 796 699.5 800.5Q684 805 673 805Q537 805 435.0 698.5Q333 592 333 452Q333 318 381.0 250.5Q429 183 525 183Q587 183 642.5 203.5Q698 224 747 264Q717 502 717 620Z"/></g><g fill="#F59E0B" stroke="#D97706" stroke-width="1" stroke-linejoin="round"><rect x="82" y="17" width="4" height="23" rx="2" transform="rotate(13 84 28.5)"/><circle cx="82.5" cy="50" r="3.5"/><rect x="92" y="17" width="4" height="23" rx="2" transform="rotate(13 94 28.5)"/><circle cx="92.5" cy="50" r="3.5"/><rect x="102" y="17" width="4" height="23" rx="2" transform="rotate(13 104 28.5)"/><circle cx="102.5" cy="50" r="3.5"/></g></svg>'

_UGH_INLINE_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="2 6 115 64" aria-label="ugh." style="height:1.35em;width:auto;display:inline-block;overflow:visible"><g fill="#8E7398" stroke="#5E4865" stroke-width="1.3" stroke-linejoin="round" paint-order="stroke"><path transform="rotate(6 18 42) translate(8 46) scale(0.017090 -0.017090)" d="M978 578Q978 511 979.0 376.0Q980 241 980 174Q980 153 983.5 111.5Q987 70 987 49Q987 -7 946.5 -43.5Q906 -80 847 -80Q764 -80 726 -5Q598 -52 461 -52Q319 -52 222 8Q113 77 92 209Q53 459 53 656Q53 786 83 953Q103 1066 218 1066Q276 1066 317.0 1029.5Q358 993 358 937Q358 893 343.5 799.0Q329 705 329 656Q329 515 338.5 409.5Q348 304 367 235Q392 224 415.5 218.0Q439 212 461 212Q572 212 705 244Q705 321 704 419Q702 536 702 587Q702 792 721 941Q736 1060 857 1060Q916 1060 958.0 1023.0Q1000 986 997 930Q978 549 978 578Z"/><path transform="rotate(3 43 40) translate(31 49) scale(0.018066 -0.018066)" d="M1029 596Q987 361 979 100Q969 -223 871 -369Q740 -564 407 -564Q18 -564 18 -410Q18 -355 53.0 -321.0Q88 -287 145 -287Q190 -287 274.0 -304.0Q358 -321 423 -321Q572 -321 643 -230Q711 -141 723 53Q672 1 608.0 -25.0Q544 -51 468 -51Q269 -51 144.5 78.5Q20 208 20 410Q20 682 186 850Q358 1024 651 1024Q745 1024 813.0 1001.0Q881 978 923 931Q1050 916 1050 781Q1050 714 1029 596ZM641 796Q472 796 378 685Q294 584 294 423Q294 304 339.0 244.0Q384 184 474 184Q556 184 639 279Q717 369 728 457Q747 553 772 756Q738 776 705.0 786.0Q672 796 641 796Z"/><path transform="rotate(8 67 38) translate(55 45) scale(0.018066 -0.018066)" d="M399 915Q472 987 555.5 1022.5Q639 1058 734 1058Q905 1058 980 962Q1036 890 1048 741Q1053 618 1059 494Q1075 333 1079 298Q1093 187 1113 104Q1118 83 1118 67Q1118 11 1075.5 -25.5Q1033 -62 976 -62Q875 -62 845 38Q821 119 801 266Q783 407 783 498Q783 523 785.5 573.5Q788 624 788 649Q788 723 786 735Q777 790 734 790Q623 790 533 688Q487 637 407 494Q407 132 372 58Q333 -24 248 -24Q192 -24 148.5 13.5Q105 51 105 106Q105 125 116 159Q123 181 128 429Q123 630 130 1098L132 1131Q138 1249 138 1289Q138 1320 128.5 1380.5Q119 1441 119 1472Q119 1529 160.0 1565.5Q201 1602 259 1602Q358 1602 392 1496Q411 1436 411 1312Q411 1212 405 1109Q399 1011 399 915Z"/></g><circle cx="84" cy="51" r="3.5" fill="#8E7398" stroke="#5E4865" stroke-width="1" stroke-linejoin="round"/><circle cx="96" cy="51" r="3.5" fill="#8E7398" stroke="#5E4865" stroke-width="1" stroke-linejoin="round"/><circle cx="108" cy="51" r="3.5" fill="#8E7398" stroke="#5E4865" stroke-width="1" stroke-linejoin="round"/></svg>'

FEEDBACK_HINT_HTML = (
    '<div class="discussion-intro">'
      '<div class="discussion-intro-title">How to use this reading</div>'
      '<div class="discussion-intro-line">'
        '<b>1.</b> The AI will provide you with a discussion of the case, '
        'generated based on your argument. Read it carefully. While reading, '
        '<b><i><u>revise your argument</u></i></b> on the right and submit '
        'the final revised version when you\'re ready.'
      '</div>'
      '<div class="discussion-intro-line">'
        '<b>2.</b> Read it <b><i><u>at your own pace</u></i></b>; take from '
        'it what\'s useful to you.'
      '</div>'
      '<div class="discussion-intro-line">'
        '<b>3.</b> The reading takes a moment to generate. Please wait, '
        'it\'s being written specifically for your argument.'
      '</div>'
      '<div class="discussion-intro-line">'
        '<b>4.</b> While reading, you can tag passages:'
        '<ul class="discussion-intro-bullets">'
          '<li>Click ' + _AHA_INLINE_SVG + ' if a passage <b><i><u>helped'
          '</u></i></b> you notice or rethink something new.</li>'
          '<li>Click ' + _UGH_INLINE_SVG + ' if a passage felt <b><i><u>'
          'frustrating</u></i></b> or off.</li>'
          '<li>If you do not feel either reaction, you can also leave it '
          'unclicked.</li>'
        '</ul>'
      '</div>'
    '</div>'
)



def _label_row_html(text, *, with_counter=True):
    """Build the HTML for the custom label row above the argument textbox.

    The word-counter span has id='wc-display' so the JS in EMOJI_SWAP_HEAD

    can write into it on every keystroke."""
    counter = (
        '<span id="wc-display" class="wc-status">'
        '0 words (need at least 100)'
        '</span>'
    ) if with_counter else ''
    return (
        '<div class="arg-label-row">'
        f'<span class="arg-label-text">{text}</span>'
        f'{counter}'
        '</div>'
    )


ARG_NOTICE_HTML = (
    '<div class="arg-notice">'
    'Please <b><i><u>Do not use external AI tools or other online writing '
    'assistants.</u></i></b> You may use only the material provided in this '
    'system.'
    '</div>'
)


ARG_LABEL_PHASE1 = _label_row_html("Your argument", with_counter=True)
ARG_LABEL_PHASE2 = _label_row_html(
    "Your argument and revision",
    with_counter=False,
)
ARG_LABEL_LOCKED = _label_row_html(
    "Your argument (locked — submitted)", with_counter=False,
)


# See socratic/app.py for full commentary. JS that takes over scroll behavior
# from Gradio's built-in autoscroll (we set autoscroll=False on the Chatbot):
# initial load → top; new content → bottom (via MutationObserver).
_CHATBOT_SCROLL_JS = """

() => {

    const setup = (tries) => {

        tries = tries || 0;

        if (tries > 40) return;

        const cb = document.querySelector('#chatbot-main');

        if (!cb) { setTimeout(() => setup(tries+1), 100); return; }

        const inner = cb.querySelector('.bubble-wrap')

                   || cb.querySelector('[class*="bubble-wrap"]')

                   || cb.querySelector('.message-wrap')

                   || cb.querySelector('[class*="message-wrap"]')

                   || cb;

        if (!inner || inner.scrollHeight <= inner.clientHeight + 4) {

            setTimeout(() => setup(tries+1), 100);

            return;

        }

        inner.scrollTop = 0;

        setTimeout(() => { inner.scrollTop = 0; }, 200);

        setTimeout(() => { inner.scrollTop = 0; }, 600);

        setTimeout(() => { inner.scrollTop = 0; }, 1200);

        setTimeout(() => {

            const obs = new MutationObserver(() => {

                inner.scrollTop = inner.scrollHeight;

            });

            obs.observe(inner, {

                childList: true, subtree: true, characterData: true

            });

        }, 1600);

    };

    setup();

}

"""


with gr.Blocks(title="B", fill_height=True) as demo:

    # ====== TOP ROW: reading | argument/essay textbox ======
    # guide-col (yellow feedback hint) is visible=False — collapsed by
    # Gradio so the chatbot panel expands to the left edge.
    with gr.Row(equal_height=True):
        with gr.Column(scale=1, elem_id="guide-col", visible=False):
            gr.HTML(
                FEEDBACK_HINT_HTML,
                elem_id="feedback-hint",
            )
        with gr.Column(scale=3):
            chatbot = gr.Chatbot(
                value=INITIAL_CHATBOT_VALUE,
                height="65vh",
                group_consecutive_messages=False,
                autoscroll=False,
                show_label=False,
                elem_id="chatbot-main",
            )
        with gr.Column(scale=2, elem_id="right-col"):
            arg_label_row = gr.HTML(
                ARG_LABEL_PHASE1, elem_id="arg-label-row",
            )
            arg_notice = gr.HTML(
                ARG_NOTICE_HTML, elem_id="arg-notice",
            )
            arg_input = gr.Textbox(
                show_label=False,
                placeholder=(
                    "Type your initial argument here.\n"
                    "You need at least 100 words to receive a more developed version "
                    "of your argument. After that, you may chat with the AI assistant "
                    "if you wish.\n"
                    "Start by saying whether you think the AI system is ethically "
                    "acceptable, ethically unacceptable, or acceptable only under "
                    "certain conditions. Then explain why."
                ),
                lines=15,
                max_lines=20,
                interactive=True,
                elem_id="right-essay",
            )

    # ====== BOTTOM ROW: action buttons (right column only) ======
    # Top guide-col is visible=False (collapses), so top row is 3:2. Bottom
    # row drops the scale=1 mirror and keeps scale=3 empty + scale=2 action
    # col so action buttons stay under the right-col argument textbox.
    with gr.Row(equal_height=True):
        with gr.Column(scale=3):
            # Chat input + Send button. Initially disabled; enabled after the
            # perfect-answer essay is shown so the participant can chat with
            # the AI assistant about the generated version.
            with gr.Row(elem_id="chat-row"):
                msg_input = gr.Textbox(
                    placeholder="Submit your initial argument first to enable chat",
                    show_label=False,
                    interactive=False,
                    scale=6,
                    lines=1,
                    max_lines=6,
                    elem_id="chat-input",
                )
                send_btn = gr.Button(
                    "Send", interactive=False, scale=1, variant="primary",
                    elem_id="send-btn",
                )
        with gr.Column(scale=2, elem_id="bottom-action-col"):
            submit_initial_btn = gr.Button(
                SUBMIT_INITIAL_LABEL, variant="primary", visible=True,
                elem_id="submit-initial-btn",
            )
            end_session_btn = gr.Button(
                END_SESSION_LABEL,
                variant="secondary",
                visible=False,
                interactive=False,
            )

    # Hidden elements for session-recovery (see RECOVERY_HEAD comment).
    # visible=True + CSS display:none keeps them in the DOM so the JS layer
    # can write to the textbox and click the button.
    recover_session_id_input = gr.Textbox(
        value="", visible=True, elem_id="recover-session-id-input",
        elem_classes=["soc-hidden-helper"],
    )
    recover_btn = gr.Button(
        "recover", visible=True, elem_id="recover-btn",
        elem_classes=["soc-hidden-helper"],
    )
    recovery_payload = gr.Textbox(
        value="", visible=True, elem_id="recovery-payload",
        elem_classes=["soc-hidden-helper"],
    )

    # 2-click confirmation states
    arm_state = gr.State(0.0)
    revert_timer = gr.Timer(value=2.5, active=False)
    submit_initial_arm_state = gr.State(0.0)
    submit_initial_revert_timer = gr.Timer(value=2.5, active=False)

    # Periodic notepad snapshot timer (no_ai only). Fires every 60s while
    # active. Activated when submit_initial confirms, deactivated when
    # end_session confirms. Captures argument-revision trajectory in the
    # reading-only condition where there are no per-event triggers like
    # chat_send. Server-side; doesn't fire when browser tab is closed.
    snapshot_timer = gr.Timer(value=60.0, active=False)

    # Per-session SessionLogger. Lazy-init guard for gradio_client (which
    # bypasses demo.load); pin via the State output every handler call.
    logger_state = gr.State()

    # Hidden Textbox carrying walkthrough-finished timestamp from JS to
    # the on_submit_initial handler via the submit button's js= wrapper.
    walkthrough_ts_input = gr.Textbox(
        value="",
        visible=False,
        elem_id="walkthrough-ts-input",
    )

    done_panel = gr.HTML(value="", visible=False)

    # ============================================================
    # Handlers
    # ============================================================

    def on_submit_initial(arg_text, history, arm_at, logger, walkthrough_ts):
        """Phase 1 → Phase 2 with 2-click confirmation.



        `walkthrough_ts` is the unix-seconds string captured client-side

        at the walkthrough's "Start" click; injected via the submit

        button's js= wrapper.



        Outputs (10): chatbot, arg_input, submit_initial_btn, end_session_btn,

                      submit_initial_arm_state, submit_initial_revert_timer,

                      logger_state, snapshot_timer, arg_label_row,

                      recovery_payload

        """
        if logger is None:
            logger = SessionLogger()
        now = time.time()

        if arm_at and (now - arm_at) <= ARM_TTL:
            logger.start_session()
            # Round-robin assign one OpenAI key from the pool. Stored on
            # the logger so the same key is used for essay + chat across
            # the whole session, and reproducible from the JSON log via
            # the `assigned_key_idx` field.
            try:
                _key_idx, _session_client = get_next_client()
                logger.set_assigned_key(_key_idx)
                logger._session_oai_client = _session_client
                print(f"[key_pool] session {logger.session_id} -> key_idx={_key_idx}",
                      flush=True)
            except Exception as _e:
                logger._session_oai_client = None
                print(f"[key_pool] failed to assign key: {_e}", flush=True)
            try:
                ts_float = float(walkthrough_ts) if walkthrough_ts else None
                if ts_float and ts_float > 0:
                    logger.walkthrough_started_at = ts_float
            except (ValueError, TypeError):
                pass
            logger.set_essay("argument", arg_text)
            logger.add_argument_snapshot(
                trigger="submit_initial_confirm",
                text=arg_text,
            )
            # Trigger ③: persist initial argument + walkthrough timing to HF.
            # Protects users who submit initial then close tab before any
            # chat turn happens (otherwise the only push would be at first
            # turn completion).
            logger.checkpoint()

            # Yield 1: append participant arg + status; flip phase-2 layout;
            # disable both action buttons during generation. Snapshot timer
            # stays inactive during the 15-30s generator wait.
            # Also write a "submitted" JSON event into recovery_payload so
            # the chained .then(js=...) writes session_id to localStorage.
            import json as _json_local
            history_with_status = history + [
                {"role": "user", "content": arg_text},
                {"role": "assistant",
                 "content": "*Reading your argument and preparing the discussion. "
                            "This takes about 15-30 seconds... "
                            "Please keep this page open and do not refresh it during this time.*"},
            ]
            save_payload = _json_local.dumps({
                "event": "submitted",
                "sid": logger.session_id,
                "code": logger.completion_code or "",
            })
            yield (
                history_with_status,
                gr.update(value=arg_text, placeholder=""),
                gr.update(visible=False, value=SUBMIT_INITIAL_LABEL,
                          variant="primary"),
                gr.update(visible=True, interactive=False),
                gr.update(interactive=False,
                          placeholder="Preparing the discussion…"),
                gr.update(interactive=False),
                0.0,
                gr.update(active=False),
                logger,
                gr.update(active=False),
                gr.update(value=ARG_LABEL_PHASE2),
                gr.update(value=save_payload),
            )

            # Generate the per-session essay + plan.
            try:
                arts = generate_session_artifacts(
                    arg_text,
                    client=getattr(logger, "_session_oai_client", None),
                )
                if arts.get("perfect_answer"):
                    logger.set_perfect_answer(arts["perfect_answer"])
                if arts.get("discussion_plan"):
                    logger.set_discussion_plan(arts["discussion_plan"])
                if arts.get("dominant_framework"):
                    logger.set_dominant_framework(arts["dominant_framework"])
                    print(f"[framework] {arts['dominant_framework']}", flush=True)
                essay = arts.get("perfect_answer") or ""
            except Exception as e:
                print(f"[session_artifacts] generation failed: {e}", flush=True)
                essay = ""
            finally:
                # Trigger ① for artifact-gen step: persist PA + plan + framework
                # together. Without this, the next push would not happen until
                # the user's first chat turn — losing artifacts if user closes
                # tab between submit and first turn.
                try:
                    logger.checkpoint()
                except Exception as e:
                    print(f"[session_artifacts] checkpoint failed: {e}", flush=True)

            # Yield 2: clear status, show two assistant messages (intro + essay),
            # enable end-session button, START the 60s notepad-snapshot timer.
            if essay:
                history_final = history + [
                    {"role": "user", "content": arg_text},
                    {"role": "assistant", "content": INTRO_MESSAGE},
                    {"role": "assistant", "content": essay},
                ]
            else:
                # Fallback if generation failed: show a graceful note.
                history_final = history + [
                    {"role": "user", "content": arg_text},
                    {"role": "assistant",
                     "content": "*Discussion content could not be prepared. "
                                "Please end the session.*"},
                ]
            yield (
                history_final,
                gr.update(),
                gr.update(),
                gr.update(interactive=True),
                gr.update(interactive=True,
                          placeholder="Type your message to the AI assistant…"),
                gr.update(interactive=True),
                gr.update(),
                gr.update(),
                logger,
                gr.update(active=True),
                gr.update(),
                gr.update(),
            )
            return

        if not arg_text.strip():
            gr.Warning("Please write your argument before submitting.")
            yield (
                gr.update(), gr.update(), gr.update(), gr.update(),
                gr.update(), gr.update(),
                arm_at, gr.update(),
                logger,
                gr.update(),
                gr.update(),
                gr.update(),
            )
            return

        # ARM
        yield (
            gr.update(),
            gr.update(),
            gr.update(value=SUBMIT_INITIAL_CONFIRM_LABEL, variant="stop"),
            gr.update(),
            gr.update(),
            gr.update(),
            now,
            gr.update(active=True),
            logger,
            gr.update(),
            gr.update(),
            gr.update(),
        )

    def on_submit_initial_tick(arm_at):
        if not arm_at:
            return arm_at, gr.update(active=False), gr.update()
        if (time.time() - arm_at) > ARM_TTL:
            return (
                0.0,
                gr.update(active=False),
                gr.update(value=SUBMIT_INITIAL_LABEL, variant="primary"),
            )
        return arm_at, gr.update(), gr.update()

    def on_end_session(arm_at, arg_text, logger):
        """2-click end-session/finalize. Generator: yields a 'saving…' state

        first, then a final status reflecting whether the upload succeeded.

        CONFIRM also stops the 60s periodic snapshot timer.



        The 8th output (recovery_payload) carries an "ended" event JSON on

        the CONFIRM second yield, which the chained .then(js=...) reads to

        clear localStorage. Other yields leave it untouched.



        Outputs (10): arg_input, end_session_btn, done_panel,

                      arm_state, revert_timer, snapshot_timer, arg_label_row,

                      recovery_payload, msg_input, send_btn

        """
        now = time.time()
        is_first_click = not (arm_at and (now - arm_at) <= ARM_TTL)
        # Revise-check gate. Run only on first click and only when the
        # `lockdown.revise_check` config flag is on. Compare current arg_text
        # against the initial argument; if word-level similarity is > 0.9
        # (i.e. the participant changed less than ~10%), show a modal asking
        # them to revise more before finalising.
        if LOCKDOWN_REVISE_CHECK and is_first_click and logger is not None:
            initial_text = (
                (logger.essays.get("argument") if logger.essays else None) or {}
            ).get("text", "")
            sim = _arg_word_similarity(initial_text, arg_text)
            print(
                f"[revise-check] similarity={sim:.3f} "
                f"threshold={REVISE_SIMILARITY_THRESHOLD}",
                flush=True,
            )
            if initial_text and sim > REVISE_SIMILARITY_THRESHOLD:
                yield (
                    gr.update(),
                    gr.update(),
                    gr.update(value=_revise_gate_trigger_html(), visible=True),
                    arm_at,
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    gr.update(),  # recovery_payload (no event)
                    gr.update(),  # msg_input
                    gr.update(),  # send_btn
                )
                return

        if arm_at and (now - arm_at) <= ARM_TTL:
            yield (
                gr.update(interactive=False),
                gr.update(visible=False, value=END_SESSION_LABEL,
                          variant="secondary"),
                gr.update(value=SAVING_PANEL_HTML, visible=True),
                0.0,
                gr.update(active=False),
                gr.update(active=False),
                gr.update(value=ARG_LABEL_LOCKED),
                gr.update(),  # recovery_payload (clear happens in next yield)
                gr.update(interactive=False),  # msg_input
                gr.update(interactive=False),  # send_btn
            )
            flush_result = {"status": "no_logger", "session_id": None,
                            "completion_code": None}
            if logger is not None:
                logger.add_argument_snapshot(
                    trigger="end_session_confirm", text=arg_text,
                )
                flush_result = logger.flush()
            modal_html = _completion_modal_html(flush_result)
            import json as _json_local
            yield (
                gr.update(),
                gr.update(),
                gr.update(value=modal_html, visible=True),
                gr.update(),
                gr.update(),
                gr.update(),
                gr.update(),
                gr.update(value=_json_local.dumps({"event": "ended"})),
                gr.update(),  # msg_input
                gr.update(),  # send_btn
            )
            return
        if logger is not None:
            logger.add_argument_snapshot(
                trigger="end_session_arm", text=arg_text,
            )
        yield (
            gr.update(),
            gr.update(value=END_SESSION_CONFIRM_LABEL, variant="stop"),
            gr.update(),
            now,
            gr.update(active=True),
            gr.update(),
            gr.update(),
            gr.update(),  # recovery_payload (no event)
            gr.update(),  # msg_input
            gr.update(),  # send_btn
        )

    def on_timer_tick(arm_at):
        if not arm_at:
            return arm_at, gr.update(active=False), gr.update()
        if (time.time() - arm_at) > ARM_TTL:
            return (
                0.0,
                gr.update(active=False),
                gr.update(value=END_SESSION_LABEL, variant="secondary"),
            )
        return arm_at, gr.update(), gr.update()

    def on_snapshot_tick(arg_text, logger):
        """Fires every 60s while snapshot_timer is active (between

        submit_initial_confirm and end_session_confirm). Records the current

        notepad state with trigger='periodic_1min'. Pure local + HF persistence;

        no LLM involvement. Intended for the no_ai control where the

        participant is reading the perfect-answer essay and may revise their

        argument over many minutes without producing chat / feedback events

        that would otherwise trigger snapshots."""
        if logger is None or not logger.session_id:
            return
        logger.add_argument_snapshot(
            trigger="periodic_1min",
            text=arg_text,
        )

    def on_feedback(arg_text, logger, data: gr.LikeData):
        """Every click is recorded as a timestamped event in the feedback list;

        clicking the already-active emoji cancels the reaction (logged as

        kind='none'). Logger derives feedback_current at upload time. Also

        snapshots the notepad textbox at click time for revision tracking."""
        if logger is None:
            return
        new_kind = "aha" if data.liked else "stress"
        idx = data.index if isinstance(data.index, int) else (
            data.index[0] if data.index else -1
        )
        current = logger.get_current_kind(idx)
        kind = "none" if current == new_kind else new_kind

        def _flatten(v):
            if isinstance(v, str):
                return v
            if isinstance(v, dict):
                return v.get("text") or v.get("content") or ""
            if isinstance(v, list):
                return " ".join(_flatten(x) for x in v if x)
            return str(v or "")
        excerpt = _flatten(data.value).strip()
        logger.add_feedback(message_index=idx, kind=kind,
                            message_excerpt=excerpt[:200])
        logger.add_argument_snapshot(
            trigger="feedback_click",
            text=arg_text,
            context={"message_index": idx, "kind": kind},
        )

    def on_recover_session(session_id_str):
        """Session-recovery handler. Fired by the hidden recover_btn that JS

        clicks programmatically when the participant chooses 'Continue' on

        the recovery modal.



        no_ai has no chat turns — sessions consist of the reference essay

        (perfect_answer) plus the participant's argument-revision history.

        Recovery rebuilds the chatbot as

        [case, user_arg, INTRO_MESSAGE, perfect_answer], restores the

        argument textbox to the latest snapshot, re-enables End Session,

        and re-starts the 60s notepad-snapshot timer.



        Outputs (10): same shape as on_submit_initial — chatbot, arg_input,

                      submit_initial_btn, end_session_btn,

                      submit_initial_arm_state, submit_initial_revert_timer,

                      logger_state, snapshot_timer, arg_label_row,

                      recovery_payload

        """
        import json as _json
        sid = (session_id_str or "").strip()

        def _err(reason):
            print(f"[recover] FAIL ({reason}); sid={sid!r}", flush=True)
            outs = list(gr.update() for _ in range(11))
            outs.append(gr.update(value=_json.dumps({
                "event": "error", "reason": reason
            })))
            return tuple(outs)

        if not sid:
            return _err("empty session_id")

        try:
            from core.config_loader import (
                hf_api as _hf_api, HF_DATASET, HF_TOKEN, LOG_PATH,
            )
            if not _hf_api or not HF_DATASET:
                return _err("HF api/dataset not configured")
            files = _hf_api.list_repo_files(HF_DATASET, repo_type="dataset")
            mode_prefix = LOG_PATH.rsplit("/", 1)[0] + "/" if "/" in LOG_PATH else ""
            target = next(
                (f for f in files
                 if f.endswith(".json") and f"/{sid}_" in f
                 and (not mode_prefix or f.startswith(mode_prefix))),
                None,
            )
            if not target:
                print(f"[recover] sid={sid!r} not in {len(files)} files; "
                      f"LOG_PATH={LOG_PATH!r}", flush=True)
                return _err(f"session file not found (looked for /{sid}_*.json)")
            print(f"[recover] matched {target}", flush=True)
            from huggingface_hub import hf_hub_download
            local = hf_hub_download(
                repo_id=HF_DATASET, filename=target, repo_type="dataset",
                token=HF_TOKEN, force_download=True,
            )
            data = _json.loads(_Path(local).read_text(encoding="utf-8"))
        except Exception as e:
            return _err(f"{type(e).__name__}: {e}")

        new_logger = SessionLogger.from_dict(data)
        if new_logger is None:
            return _err("from_dict returned None (malformed payload)")

        # Restore the per-session OpenAI client by looking up the assigned
        # key index against the current pool. If the index is unknown, fall
        # back to the round-robin counter (logged on the new logger so the
        # next upload reflects reality).
        from core.config_loader import KEY_POOL as _KP
        _restored_client = None
        for _idx, _c in _KP:
            if _idx == new_logger.assigned_key_idx:
                _restored_client = _c
                break
        if _restored_client is None:
            try:
                _new_idx, _restored_client = get_next_client()
                new_logger.set_assigned_key(_new_idx)
                print(f"[recover] re-assigned key_idx={_new_idx}", flush=True)
            except Exception as _e:
                print(f"[recover] could not assign client: {_e}", flush=True)
        new_logger._session_oai_client = _restored_client

        initial_arg = (data.get("essays") or {}).get("argument", {}).get("text", "")
        pa = data.get("perfect_answer") or {}
        essay = pa.get("text", "")

        # Rebuild the chatbot: case display + user argument + intro + essay
        # (mirroring on_submit_initial yield 2). If essay generation had
        # failed in the original session, fall back to the same note shown
        # at that time.
        history = list(INITIAL_CHATBOT_VALUE) + [
            {"role": "user", "content": initial_arg},
        ]
        if essay:
            history.append({"role": "assistant", "content": INTRO_MESSAGE})
            history.append({"role": "assistant", "content": essay})
        else:
            history.append({
                "role": "assistant",
                "content": "*Discussion content could not be prepared. "
                           "Please end the session.*",
            })

        snapshots = data.get("argument_snapshots") or []
        arg_text = snapshots[-1].get("text") if snapshots else initial_arg

        print(f"[recover] OK: sid={sid}, "
              f"essay={'yes' if essay else 'no'}, "
              f"{len(data.get('feedback') or [])} feedback events, "
              f"{len(snapshots)} snapshots", flush=True)

        # Trigger ⑤: persist the 'session_resumed' snapshot that from_dict()
        # appended in-memory. Without this, a second tab-close before the
        # next chat turn would lose the resume marker.
        try:
            new_logger.checkpoint()
        except Exception as e:
            print(f"[recover] checkpoint failed: {e}", flush=True)

        save_payload = _json.dumps({
            "event": "submitted",
            "sid": new_logger.session_id,
            "code": new_logger.completion_code or "",
        })

        return (
            history,
            gr.update(value=arg_text, placeholder=""),
            gr.update(visible=False, value=SUBMIT_INITIAL_LABEL,
                      variant="primary"),
            gr.update(visible=True, interactive=True,
                      variant="secondary",
                      value=END_SESSION_LABEL),
            gr.update(interactive=True,
                      placeholder="Type your message to the AI assistant…"),
            gr.update(interactive=True),
            0.0,
            gr.update(active=False),
            new_logger,
            gr.update(active=True),  # restart snapshot_timer
            gr.update(value=ARG_LABEL_PHASE2),
            gr.update(value=save_payload),
        )

    # ============================================================
    # Post-essay general chat (B condition)
    # ============================================================
    #
    # After perfect_answer is shown, msg_input + send_btn become interactive.
    # The participant can chat freely with an AI assistant about the case
    # and the developed version. Each turn:
    #   1. Build a system prompt with case_text + initial_argument +
    #      perfect_answer substituted in. The discussion_plan is NEVER
    #      exposed.
    #   2. Append the full prior chat history (user/assistant alternation)
    #      from the chatbot display.
    #   3. Append the participant's new message.
    #   4. Call the LLM; append the assistant's reply to the chatbot.
    #   5. Log the turn via SessionLogger.add_turn (manager_verdict=None,
    #      plan_control=None, since there is no manager in this condition).

    def _build_general_chat_messages(logger, history, user_msg):
        """Assemble OpenAI chat messages for the post-essay chat turn.



        history is the gradio Chatbot value (list of {role, content} dicts).

        It already includes the case display, the user's initial argument,

        INTRO_MESSAGE, and the essay. We slice that history into a system

        prompt + role-alternated messages.

        """
        # The initial argument and perfect_answer are stored on the logger
        # at submit time; fall back to scanning history if missing.
        initial_arg = ""
        perfect_answer = ""
        try:
            initial_arg = (logger.essays or {}).get("argument", {}).get("text", "")
        except Exception:
            initial_arg = ""
        try:
            pa = getattr(logger, "perfect_answer", None) or {}
            perfect_answer = pa.get("text", "") if isinstance(pa, dict) else (pa or "")
        except Exception:
            perfect_answer = ""

        system_text = GENERAL_CHAT_PROMPT.format(
            case_text=CASE_TEXT,
            initial_argument=initial_arg,
            perfect_answer=perfect_answer,
        )

        # Convert the displayed chat into the OpenAI alternation. Skip the
        # case-display block (the first INITIAL_CHATBOT_VALUE entries),
        # the user's initial argument, the INTRO_MESSAGE, and the essay
        # itself — they are already baked into the system prompt.
        #
        # We keep only assistant/user pairs that came AFTER the essay was
        # rendered. Heuristic: the essay assistant message is the one whose
        # content equals the perfect_answer text. Drop everything up to and
        # including it.
        chat_msgs = []
        post_essay = False
        for m in history:
            if not isinstance(m, dict):
                continue
            role = m.get("role")
            content = m.get("content", "")
            if not post_essay:
                if role == "assistant" and content == perfect_answer:
                    post_essay = True
                continue
            if role in ("user", "assistant") and content:
                chat_msgs.append({"role": role, "content": content})

        messages = [{"role": "system", "content": system_text}]
        messages.extend(chat_msgs)
        messages.append({"role": "user", "content": user_msg})
        return messages

    def on_send(msg, history, logger, arg_text):
        """Post-essay chat turn. msg is the participant's new message; history

        is the current chatbot list (already includes prior turns). arg_text

        snapshots the current argument textbox for the logger."""
        if not msg.strip():
            yield history, "", logger
            return
        if logger is None:
            logger = SessionLogger()

        # Snapshot the argument on chat_send (lets us track revision activity
        # at message-level granularity, complementing the 60s timer).
        try:
            logger.add_argument_snapshot(
                trigger="chat_send",
                text=arg_text or "",
                context={
                    "next_turn_n": len(logger.turns) + 1,
                    "user_msg_excerpt": msg[:120],
                },
            )
        except Exception as e:
            print(f"[on_send] snapshot failed: {e}", flush=True)

        # Show the user message immediately.
        history = history + [{"role": "user", "content": msg}]
        yield history, "", logger

        # Build and dispatch. Use the per-session OpenAI client (assigned
        # at session start via get_next_client()) if available; otherwise
        # fall back to the module-level default.
        _api = getattr(logger, "_session_oai_client", None) or OAI_CLIENT
        t0 = time.perf_counter()
        try:
            try:
                messages = _build_general_chat_messages(logger, history[:-1], msg)
                resp = _api.chat.completions.create(
                    model=OAI_MODEL,
                    messages=messages,
                    reasoning_effort=CONFIG.get("reasoning_effort", "medium"),
                )
                reply = resp.choices[0].message.content or ""
            except Exception as e:
                reply = ("*Sorry — I couldn't generate a reply this time. "
                         f"({type(e).__name__})*")
                print(f"[on_send] LLM call failed: {e}", flush=True)

            history = history + [{"role": "assistant", "content": reply}]
            yield history, "", logger

            # Log the turn (manager_verdict + plan_control are None for this
            # condition — there is no manager in post-essay chat).
            try:
                logger.add_turn(
                    user_message=msg,
                    manager_verdict=None,
                    plan_control=None,
                    assistant_response=reply,
                    latency_s=round(time.perf_counter() - t0, 3),
                )
            except Exception as e:
                print(f"[on_send] log_turn failed: {e}", flush=True)
        finally:
            # Trigger ①: persist this turn + interim events (chat_send
            # snapshot, any feedback events between turns). Runs on both
            # success and failure paths so we never lose the user's message
            # even if the LLM call or log_turn raises.
            if logger:
                try:
                    logger.checkpoint()
                except Exception as e:
                    print(f"[on_send] checkpoint failed: {e}", flush=True)

    # ============================================================
    # Wire events
    # ============================================================

    initial_outputs = [
        chatbot,
        arg_input,
        submit_initial_btn,
        end_session_btn,
        msg_input,
        send_btn,
    ]

    _RECOVERY_SAVE_JS = """(payload) => {

        console.log('[recovery] .then(js) received payload:', payload);

        if (!payload) return payload;

        try {

            const obj = JSON.parse(payload);

            if (obj.event === 'submitted' && obj.sid &&

                window.__RECOVERY) {

                window.__RECOVERY.saveSession(obj.sid, obj.code || '');

                window.__RECOVERY.dismissModalIfLoading();

            } else if (obj.event === 'error' && window.__RECOVERY) {

                console.error('[recovery] server returned error:', obj.reason);

                window.__RECOVERY.markModalError(obj.reason || 'unknown');

            }

        } catch (e) {

            console.warn('[recovery] save-js parse failed', e, 'payload:', payload);

        }

        return payload;

    }"""

    _RECOVERY_CLEAR_JS = """(payload) => {

        if (!payload) return payload;

        try {

            const obj = JSON.parse(payload);

            if (obj.event === 'ended' && window.__RECOVERY) {

                window.__RECOVERY.clearState();

            }

        } catch (e) {}

        return payload;

    }"""

    submit_initial_btn.click(
        on_submit_initial,
        inputs=[arg_input, chatbot, submit_initial_arm_state, logger_state, walkthrough_ts_input],
        outputs=initial_outputs + [submit_initial_arm_state,
                                   submit_initial_revert_timer, logger_state,
                                   snapshot_timer, arg_label_row,
                                   recovery_payload],
        js="""(arg_text, history, arm_at, logger, ts_in) => {

            var ts = window.__walkthroughStartedAt;

            return [arg_text, history, arm_at, logger, ts ? String(ts) : ''];

        }""",
    ).then(
        fn=None,
        inputs=[recovery_payload],
        outputs=[recovery_payload],
        js=_RECOVERY_SAVE_JS,
    )

    recover_btn.click(
        on_recover_session,
        inputs=[recover_session_id_input],
        outputs=initial_outputs + [submit_initial_arm_state,
                                   submit_initial_revert_timer, logger_state,
                                   snapshot_timer, arg_label_row,
                                   recovery_payload],
    ).then(
        fn=None,
        inputs=[recovery_payload],
        outputs=[recovery_payload],
        js=_RECOVERY_SAVE_JS,
    )

    submit_initial_revert_timer.tick(
        on_submit_initial_tick,
        inputs=[submit_initial_arm_state],
        outputs=[submit_initial_arm_state, submit_initial_revert_timer, submit_initial_btn],
    )

    end_session_btn.click(
        on_end_session,
        inputs=[arm_state, arg_input, logger_state],
        outputs=[arg_input, end_session_btn, done_panel, arm_state, revert_timer,
                 snapshot_timer, arg_label_row, recovery_payload,
                 msg_input, send_btn],
    ).then(
        fn=None,
        inputs=[recovery_payload],
        outputs=[recovery_payload],
        js=_RECOVERY_CLEAR_JS,
    )

    # Post-essay chat: send by button click or Enter on msg_input.
    send_btn.click(
        on_send,
        inputs=[msg_input, chatbot, logger_state, arg_input],
        outputs=[chatbot, msg_input, logger_state],
    )
    msg_input.submit(
        on_send,
        inputs=[msg_input, chatbot, logger_state, arg_input],
        outputs=[chatbot, msg_input, logger_state],
    )

    revert_timer.tick(
        on_timer_tick,
        inputs=[arm_state],
        outputs=[arm_state, revert_timer, end_session_btn],
    )

    # 60s periodic notepad snapshot — only the no_ai condition needs this
    # because the reading flow has no chat_send / few feedback events to drive
    # event-based snapshots. Active between submit_initial_confirm (yield 2)
    # and end_session_confirm.
    snapshot_timer.tick(
        on_snapshot_tick,
        inputs=[arg_input, logger_state],
        outputs=None,
    )

    # ✨ aha / 😳 stress reactions on the perfect-answer essay (and the
    # intro message; participants may click on either, both are logged).
    # arg_input passed so notepad gets snapshotted at click time.
    chatbot.like(on_feedback, inputs=[arg_input, logger_state], outputs=None)

    demo.load(
        fn=lambda: SessionLogger(),
        inputs=None,
        outputs=logger_state,
        js=_CHATBOT_SCROLL_JS,
    )


def _start_auto_restart():
    """Background thread: poll the HF dataset for the latest session log;

    if the latest is older than `idle_threshold_hours`, restart the Space.

    Same machinery as socratic / explanatory."""
    import os
    import threading
    from datetime import datetime
    from core.config_loader import CONFIG, HF_TOKEN, HF_DATASET, LOG_PATH
    from core import AEST

    cfg = CONFIG.get("auto_restart") or {}
    env_override = os.environ.get("AUTO_RESTART_ENABLED", "").strip().lower()
    enabled = (env_override in {"1", "true", "yes"}) or (env_override == "" and cfg.get("enabled"))
    if not enabled:
        return
    if not (HF_TOKEN and HF_DATASET):
        print("[auto-restart] HF token / dataset missing — skipping.", flush=True)
        return
    space_id = cfg.get("space_id")
    if not space_id:
        return

    check_hours = cfg.get("check_interval_hours", 12)
    idle_hours = cfg.get("idle_threshold_hours", 24)

    from huggingface_hub import HfApi
    api = HfApi(token=HF_TOKEN)

    # Thread-uptime fallback: if the dataset has no logs yet (fresh Space, no
    # participants) we still want to restart once the Space itself has been
    # running ≥ idle_hours, otherwise zero-log Spaces never auto-recover.
    started_at = now_aest()

    def _check_and_restart():
        while True:
            time.sleep(check_hours * 3600)
            now = now_aest()
            print(f"[auto-restart] {now.strftime('%Y-%m-%d %H:%M:%S')} — idle check…", flush=True)
            try:
                files = api.list_repo_files(HF_DATASET, repo_type="dataset")
                log_files = sorted(
                    f for f in files if f.startswith(LOG_PATH + "/") and f.endswith(".json")
                )
                if log_files:
                    latest = log_files[-1].rsplit("/", 1)[-1].removesuffix(".json")
                    # Filenames are "<YYYYMMDD>_<HHMMSS>_<session_code>" — strptime the timestamp only.
                    ts = "_".join(latest.split("_")[:2])
                    latest_dt = datetime.strptime(ts, "%Y%m%d_%H%M%S").replace(tzinfo=AEST)
                    idle_h = (now - latest_dt).total_seconds() / 3600
                    src = f"latest log {latest}"
                else:
                    idle_h = (now - started_at).total_seconds() / 3600
                    src = "no logs yet — using thread uptime"
                print(f"[auto-restart] Idle source: {src} ({idle_h:.1f}h ago)", flush=True)
                if idle_h > idle_hours:
                    print(f"[auto-restart] Idle {idle_h:.1f}h > {idle_hours}h — restarting {space_id}.", flush=True)
                    api.restart_space(space_id)
                else:
                    print(f"[auto-restart] Active within {idle_hours}h — no restart.", flush=True)
            except Exception as e:
                print(f"[auto-restart] Check failed: {e}", flush=True)

    threading.Thread(target=_check_and_restart, daemon=True).start()
    print(f"[auto-restart] Started — checking every {check_hours}h, "
          f"restart if idle > {idle_hours}h, watching {LOG_PATH}/", flush=True)


if __name__ == "__main__":
    _start_auto_restart()
    demo.queue(default_concurrency_limit=None).launch(
        css=CUSTOM_CSS + COMPLETION_MODAL_CSS, head=_LOCKDOWN_FLAGS_JS + EMOJI_SWAP_HEAD + HIDE_HF_WIDGET_HEAD + RECOVERY_HEAD + TUTORIAL_HEAD + REVISE_GATE_HEAD,
    )