A
File size: 135,609 Bytes
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9acdc0
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9acdc0
 
 
 
 
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9acdc0
 
 
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ad33ca
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c467b4
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e69ce8
a7d00d8
247e731
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e10e5a0
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d93dc5
 
 
 
 
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d93dc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d93dc5
 
 
 
 
 
 
 
 
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d93dc5
 
 
 
 
 
 
 
 
 
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34ef029
 
 
 
 
 
 
 
 
 
 
a7d00d8
 
 
 
 
 
 
 
 
 
34ef029
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9acdc0
 
 
 
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9acdc0
 
 
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d93dc5
 
 
 
 
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9acdc0
 
 
 
a7d00d8
b9acdc0
a7d00d8
 
 
 
 
 
 
 
 
 
 
b9acdc0
 
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd3bf73
 
 
a7d00d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
"""Gradio app for the Socratic AI condition (v4 two-agent architecture).



Single-layout design (no visible stage labels):

  - Left: chat area. The case is the first 'assistant' message.

  - Right: a text input that doubles as initial-argument writing in Phase 1

    and a participant notepad in Phase 2.



Phases (implicit, driven by button clicks):

  Phase 1 (entry): chatbot shows the case; right input is for initial

                   argument; chat input DISABLED.

  Phase 2 (after Submit Initial confirm): host code calls

                   `core.perfect_answer.generate_session_artifacts` (around

                   15-30s blocking) to produce the per-session essay +

                   discussion plan. The plan is parsed and pinned into the

                   session cache. Each subsequent chat turn runs a manager

                   agent + main bot agent (see core.orchestrator). Right

                   input becomes a notepad; chat ENABLED.

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



Per-message aha!/ugh. reactions: same as v3. Gradio's like/dislike buttons

swapped via EMOJI_SWAP_HEAD; clicks land in `logger.add_feedback`.



Two-agent flow per chat turn (post-Phase 1):

  1. Manager agent classifies the turn (~2-4s blocking).

  2. Host builds PLAN CONTROL block from the verdict.

  3. Main bot streams its reply.

  4. Host logs the turn (user_message + verdict + plan_control + bot reply

     + scratch + latencies).

"""

import threading
import time
import gradio as gr

from core import client, get_next_client, MODEL, REASONING_EFFORT, VERBOSITY
from core import SessionLogger, now_aest
from core.config_loader import BASE_DIR, CONFIG

# Participant-side lockdown flags read from config.yaml. Defaults are FALSE
# (test mode). For an actual experiment run, set all three to true in the
# config (or via Space Variables) and redeploy.
_LOCKDOWN_CFG = (CONFIG.get("lockdown") if isinstance(CONFIG, dict) else None) or {}
LOCKDOWN_ARG_CLIPBOARD = bool(_LOCKDOWN_CFG.get("arg_clipboard", False))
LOCKDOWN_CHAT_COPY = bool(_LOCKDOWN_CFG.get("chat_copy", False))
ENFORCE_END_SESSION_GATE = bool(_LOCKDOWN_CFG.get("end_session_gate", False))
LOCKDOWN_REVISE_CHECK = bool(_LOCKDOWN_CFG.get("revise_check", False))
print(
    f"[lockdown] arg_clipboard={LOCKDOWN_ARG_CLIPBOARD} "
    f"chat_copy={LOCKDOWN_CHAT_COPY} "
    f"end_session_gate={ENFORCE_END_SESSION_GATE} "
    f"revise_check={LOCKDOWN_REVISE_CHECK}",
    flush=True,
)


# ============================================================
# 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 text + 'Start walkthrough'),

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

          text slides (Msg2, Msg3); each step has a 'Next' button at the

          footer, except the last which shows 'Start' to close the overlay.



    Slides in order:

        1-3: tutorial images 01..03

        4:   Msg2 text panel

        5:   Msg3 text panel

        6-7: tutorial images 04..05



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

    they match the right-side 'Submit initial argument' button.



    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

    // without the welcome overlay sitting underneath.

    try {

        var raw = localStorage.getItem('socratic_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 / Msg3 HTML — kept here as constants for easy edit.

    var MSG2_HTML =

        'The AI assistant will discuss your argument with you and help you ' +

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

        'As you go, <b>revise your argument</b> on the right. ' +

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

    var MSG3_HTML =

        'During the discussion, you can <b>ask for clarification</b>, ' +

        '<b>disagree</b> with the AI assistant, or <b>ask it to rephrase ' +

        'anything that feels unclear</b>. The AI assistant may take a few ' +

        'seconds to reply. Please wait — this is normal.';



    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;

        // Mixed slide deck: image, image, image, text(Msg2), text(Msg3), 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: 'text',  html: MSG3_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() {

            // Record the walkthrough-finished timestamp client-side. This

            // value is read at argument-submit time via the js= wrapper on

            // submit_initial_btn.click and passed into the Python handler,

            // which stores it on the SessionLogger.

            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 (`socratic_ca_session_v1` / `socratic_ca_tab_id`) so other A_Ethic
# condition Spaces opened in the same browser do not collide. The global JS
# helper is exposed as `window.__RECOVERY` (same name across conditions for
# the .then(js=...) snippets, but each Space defines its own copy on load).
# ============================================================
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 = 'socratic_ca_session_v1';

    const TAB_KEY = 'socratic_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() {

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

            const sendBtn = e.target.closest('#send-btn button, #send-btn');

            if (sendBtn) touchSession();

        }, true);

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

            if (e.key !== 'Enter' || e.shiftKey) return;

            const input = e.target.closest('#chat-input textarea, #chat-input input');

            if (input) 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>

"""


from core.content_sync import sync_chapters_from_ssot
from core.perfect_answer import generate_session_artifacts
from core import plan_parsing
from core import orchestrator
from core import main_agent
from core.manager_agent import ManagerVerdict
from core.main_agent import BotResponse


# 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()


# ============================================================
# Session cache keys (held inside a Gradio State dict)
# ============================================================

PERFECT_ANSWER_KEY = "__perfect_answer__"     # str, the essay (kept for log)
PLAN_TEXT_KEY = "__plan_text__"               # str, raw markdown of plan
PLAN_SUBPROBES_KEY = "__plan_subprobes__"     # list[dict] from plan_parsing
MANAGER_HISTORY_KEY = "__manager_history__"   # list[dict], cumulative verdicts
SESSION_CLIENT_KEY = "__session_client__"     # OpenAI client assigned to this
                                              # session by get_next_client() —
                                              # rotates across OPENAI_KEY_01..10
                                              # so concurrent sessions hit
                                              # different OpenAI keys / quotas.
INITIAL_ARG_KEY = "__initial_argument__"      # str, the full essay the
                                              # participant submitted at
                                              # Phase 1 — passed to manager
                                              # on every turn so its overall
                                              # stance never falls out of
                                              # the recent-turns window.


# ============================================================
# 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 (including the title) via stream_turn.
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)


# ============================================================
# Per-turn pipeline (manager then main bot, synchronous)
# ============================================================

THINKING_TEXT = "*Thinking…*"

# ============================================================
# Multi-message output for `opening` and `transition-due`.
#
# The main-agent prompt instructs the LLM to emit `<<<MSG-BREAK>>>` on its
# own line to split its reply into multiple chat messages, ONLY for these
# two turn types. The host (stream_turn below) splits on this marker after
# the LLM finishes streaming, and replaces the single assembled bot message
# in chatbot history with multiple discrete assistant messages.
#
# For `opening` specifically, the LLM is told NOT to write the greeting /
# "I'm here to help you think through your argument" framing — that text
# is HARDCODED below (OPENING_M1_HARDCODED) and prepended by the host as
# the first message. This guarantees the framing wording is exact and
# never drifts under prompt jitter.
#
# Wording in OPENING_M1_HARDCODED is locked by collaborator request — do
# NOT edit without explicit sign-off.
# ============================================================

MSG_BREAK_MARKER = "<<<MSG-BREAK>>>"

OPENING_M1_HARDCODED = (
    "Thanks for sharing your argument. I've read it carefully.\n\n"
    "I'm here to **help you think through your argument, rather than think "
    "for you**. So, in the following discussion, **I'll ask you questions** to "
    "**help you examine your reasoning** and decide how you want to revise "
    "your argument."
)


def stream_turn(user_msg, history, case_text, cache, result):
    """Run one chat turn end-to-end. Synchronous: manager (blocking ~2-5s),

    then main bot stream (yielding deltas).



    `history` already contains the participant's message as its last entry.

    `result` is a caller-supplied dict that this function populates with:

      - "verdict": ManagerVerdict or None

      - "plan_control_text": str

      - "bot_response": BotResponse or None

      - "manager_latency_ms": int



    Yields successive history snapshots for the Gradio chatbot.



    The caller iterates with a for loop and reads `result` after the loop

    ends; logging happens in the caller (NOT in a post-yield block, which

    is unreliable under Gradio's streaming framework).

    """
    plan_subprobes = cache.get(PLAN_SUBPROBES_KEY, [])
    plan_text = cache.get(PLAN_TEXT_KEY, "")
    manager_history = cache.get(MANAGER_HISTORY_KEY, [])
    initial_argument = cache.get(INITIAL_ARG_KEY, "")

    # Bot-slot placeholder while the manager call is running.
    history = history + [{"role": "assistant", "content": THINKING_TEXT}]
    yield history

    # Per-session OpenAI client (assigned at session start via get_next_client();
    # may be None on legacy/recovered sessions, in which case downstream falls
    # back to the module-level default client).
    session_client = cache.get(SESSION_CLIENT_KEY)

    # 1. Manager call (blocking).
    verdict = None
    manager_latency_ms = 0
    if plan_subprobes:
        t0 = time.perf_counter()
        try:
            verdict = orchestrator.run_manager(
                discussion_plan_subprobes=plan_subprobes,
                manager_history=manager_history,
                history=history[:-1],
                current_msg=user_msg,
                initial_argument=initial_argument,
                client=session_client,
            )
        except Exception as e:
            print(f"[manager] failed: {e!r}", flush=True)
        manager_latency_ms = int((time.perf_counter() - t0) * 1000)
    result["verdict"] = verdict
    result["manager_latency_ms"] = manager_latency_ms

    # 2. PLAN CONTROL block.
    if verdict is not None and plan_subprobes:
        plan_control_text = main_agent.build_plan_control(verdict, plan_subprobes)
    else:
        plan_control_text = (
            "=== PLAN CONTROL (host-managed) ===\n"
            "(no discussion plan available for this session; respond using "
            "your own judgement on the participant's argument)\n"
            "=== END PLAN CONTROL ==="
        )
    result["plan_control_text"] = plan_control_text

    # 3. Stream main bot.
    messages = main_agent.build_messages(
        history=history[:-1],
        case_text=case_text,
        discussion_plan_text=plan_text or "(no plan)",
        plan_control_text=plan_control_text,
    )
    accumulated = ""
    bot_response = None
    streaming_started = False

    try:
        for ev in main_agent.stream(messages, client=session_client):
            if ev[0] == "delta":
                if not streaming_started:
                    streaming_started = True
                    accumulated = ev[1]
                else:
                    accumulated += ev[1]
                # While streaming, hide the raw MSG-BREAK marker so the
                # participant doesn't see "<<<MSG-BREAK>>>" appearing as
                # literal text. Replace with paragraph break for display
                # only — the actual split into discrete bubbles happens
                # at "done" below.
                display = accumulated.replace(MSG_BREAK_MARKER, "\n\n")
                history[-1] = {"role": "assistant", "content": display}
                yield history
            elif ev[0] == "done":
                bot_response = ev[1]
                history = _finalize_multi_message_history(
                    history,
                    bot_response.visible,
                    turn_type=getattr(verdict, "turn_type", None) if verdict else None,
                )
                yield history
                break
    except Exception as e:
        history[-1] = {"role": "assistant", "content": f"*Error during bot reply: {e!r}*"}
        yield history
        print(f"[main_bot] failed: {e!r}", flush=True)

    result["bot_response"] = bot_response


def _finalize_multi_message_history(history, raw_visible, turn_type):
    """Replace the single streaming bot message at history[-1] with one or

    more discrete assistant messages.



    Logic:

      - Split raw_visible on `<<<MSG-BREAK>>>` into segments

      - If turn_type == "opening", prepend OPENING_M1_HARDCODED as the

        first segment (fixed wording, host-injected, not LLM-authored)

      - Replace history[-1] (the assembled message) with one assistant

        entry per segment



    Logging note: the raw LLM output (with MSG_BREAK_MARKER intact) is

    still preserved on bot_response.visible by the caller, so the session

    log records the model's actual output — only the chat UI gets split.

    """
    segments = [
        s.strip()
        for s in raw_visible.split(MSG_BREAK_MARKER)
        if s.strip()
    ]

    if turn_type == "opening":
        segments = [OPENING_M1_HARDCODED] + segments

    # If only one segment remains (no MSG-BREAK + not opening), keep the
    # existing single-message behaviour to avoid disturbing other turn
    # types like engaging-default / needs-clarification / plan-complete.
    if len(segments) <= 1:
        history[-1] = {"role": "assistant", "content": segments[0] if segments else raw_visible}
        return history

    # Multi-segment: drop the streaming placeholder, append discrete
    # assistant messages.
    history = history[:-1]
    for seg in segments:
        history.append({"role": "assistant", "content": seg})
    return history


def _log_turn(user_msg, cache, logger, result, total_t0):
    """Apply per-turn state changes to cache + logger. Called by the

    handler AFTER stream_turn's for loop finishes. This function is NOT a

    generator: it runs to completion synchronously."""
    verdict = result.get("verdict")
    plan_control_text = result.get("plan_control_text", "")
    bot_response = result.get("bot_response")
    manager_latency_ms = result.get("manager_latency_ms", 0)

    if verdict is not None:
        mh = cache.get(MANAGER_HISTORY_KEY)
        if mh is None:
            mh = []
            cache[MANAGER_HISTORY_KEY] = mh
        mh.append(verdict.to_dict())
        logger.add_manager_verdict(verdict.to_dict())

    logger.add_turn(
        user_message=user_msg,
        manager_verdict=verdict.to_dict() if verdict else None,
        plan_control=plan_control_text,
        assistant_response=bot_response.visible if bot_response else "",
        scratch=bot_response.scratch if bot_response else {},
        latency_s={
            "manager_ms": manager_latency_ms,
            "ttft_ms": bot_response.ttft_ms if bot_response else None,
            "main_ms": bot_response.latency_ms if bot_response else None,
            "total_ms": int((time.perf_counter() - total_t0) * 1000),
        },
    )
    print(f"[logger] add_turn done; turn count now = {len(logger.turns)}", flush=True)


# ============================================================
# 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  # seconds before armed state auto-reverts

# End Session gate: participant cannot end the session until EITHER
#   (a) the discussion has advanced past (n_active_probes - 2) probes
#       (where n_active = non-well-addressed sub-probes in this session's
#        plan, typically 5-6), OR
#   (b) plan-complete has fired (manager closed the whole plan), OR
#   (c) at least END_GATE_TIMEOUT_SECONDS have elapsed since the
#       participant submitted the initial argument (safety escape hatch).
# Both Path-A (gap satisfied) and Path-B (stuck) transitions count
# toward (a) — manager already made the judgement, UI follows.
END_GATE_TIMEOUT_SECONDS = 15 * 60  # 15 minutes


def _count_non_well_addressed_probes(plan_obj):
    """plan_obj is the dict stored in logger.discussion_plan (has 'text' key,

    plan body in the 7-component scaffold). Counts sub-probes whose `gap:`

    line does NOT begin with 'well-addressed'. Returns 0 if no plan."""
    if not plan_obj:
        return 0
    text = plan_obj.get("text", "") if isinstance(plan_obj, dict) else ""
    if not text:
        return 0
    n = 0
    for line in text.split("\n"):
        s = line.strip()
        if s.startswith("gap:"):
            body = s[4:].strip().lower()
            if not body.startswith("well-addressed"):
                n += 1
    return n


def _can_end_session(logger_obj):
    """Returns True if the End Session button should proceed; False to gate.

    See END_GATE_TIMEOUT_SECONDS comment for the three release conditions."""
    if logger_obj is None:
        return True  # no logger state, fall through (don't block)
    mh = getattr(logger_obj, "manager_history", None) or []
    # (b) plan-complete ever fired → unconditionally allow
    for v in mh:
        if v.get("turn_type") == "plan-complete":
            return True
    # (c) 20-minute timeout since argument submission → allow
    arg_at = getattr(logger_obj, "argument_submitted_at", None)
    if arg_at and (time.time() - arg_at) >= END_GATE_TIMEOUT_SECONDS:
        return True
    # (a) probe threshold
    n_active = _count_non_well_addressed_probes(
        getattr(logger_obj, "discussion_plan", None)
    )
    if n_active <= 2:
        return True  # too few non-well-addressed probes to gate meaningfully
    n_transitions = sum(1 for v in mh if v.get("advanced_this_turn"))
    return n_transitions >= (n_active - 2)


def _gate_toast_trigger_html():
    """Returns a tiny hidden element whose id contains a fresh nonce.

    The JS watcher in INPUT_LOCKDOWN_HEAD spots the new id and fires

    the toast. Nonce-per-click is what makes a repeated click re-toast."""
    nonce = str(int(time.time() * 1000))
    return f'<div id="session-gate-trigger-{nonce}" style="display:none"></div>'


# Revise-check gate: word-level similarity ratio between initial argument
# and current argument. > REVISE_SIMILARITY_THRESHOLD means the participant
# has not revised enough — block End Session with a modal.
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>'


# ============================================================
# 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 = """

/* Revise-check modal — shown when participant tries to end the session

   with an argument too similar to their initial submission. Styled to

   match the tutorial overlay. */

#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;

    /* Match the rest of the app's font (Gradio default sans-serif).

       The modal is appended to document.body so it escapes Gradio's

       font scope and would otherwise fall back to the browser's serif

       default — pin a sans-serif stack here and let children inherit. */

    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: #2563eb;

    color: #fff;

    border: none;

    border-radius: 8px;

    padding: 12px 28px;

    font-size: 1.05em;

    cursor: pointer;

    transition: background 0.15s ease;

}

#revise-gate-overlay .revise-gate-btn:hover { background: #1d4ed8; }



/* 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 (the small clipboard left of aha/ugh). */

#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. Aha/ugh and the rest of the message actions live inside

   .message-buttons-* so they stay visible. */

#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. The aria-label / title matchers

   above already target exactly the toolbar buttons we want gone. */



/* Extend the Gradio outer container to the full browser width (height is

   handled by vh-based heights on the chatbot + textbox so the layout stays

   responsive to browser zoom). */

.gradio-container, .main, .wrap {

    max-width: 100% !important;

}

.gradio-container {

    padding-left: 12px !important;

    padding-right: 12px !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 aligns to flex-end so Send button stays

   with the bottom of the (possibly grown) input, not floating mid-row. */

#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;

}



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

   matches the left column = chatbot 65vh + feedback panel). Only tighten

   the inter-row gap; let Gradio handle column display. */

#right-col {

    gap: 4px !important;

}



/* Argument textbox: two nested rectangles. The OUTER rectangle is the

   Gradio block (#right-essay) — explicit fixed height (65vh) so it

   doesn't collapse. The INNER rectangle is the <textarea>, absolute-

   positioned with 6px inset on all four sides so the gap between outer

   and inner border is exactly equal everywhere. position:relative on the

   block establishes the positioning context for the textarea's absolute. */

#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;

}

/* Ensure no intermediate Gradio wrapper establishes its own positioning

   context — we want the textarea positioned relative to #right-essay. */

#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;

}



#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;

}

/* Custom label row: gr.HTML wraps its content in a Gradio block that

   has its own padding + min-height of ~80px. We force the block + every

   level of inner wrapper to be flush so the row is exactly one line tall,

   and clamp with max-height as a hard ceiling. */

#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;

}

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

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



/* Force the like/dislike buttons (repurposed as aha!/ugh.) to always be visible */

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;

}



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: replace Gradio's Like/Dislike thumbs with the custom
# aha!/ugh. SVG glyphs. Same script as v3.
EMOJI_SWAP_HEAD = """

<script>

(function() {

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



    const onEmojiClick = (e) => {

        const btn = e.currentTarget;

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

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

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

        });

        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 = [

        // English (and variants)

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

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

        // German

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

        // French

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

        // Spanish (Spain, Mexico, Latin American)

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

        // Portuguese (Brazilian + EU)

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

        // Italian

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

        // Chinese simplified

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

        // Chinese traditional

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

        // Hindi (devanagari + romanized)

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

        // Japanese / Korean / Russian (covered for completeness)

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

    ];

    const LIKE_TOKENS = [

        // English (and variants)

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

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

        // German

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

        // French

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

        // Spanish (Spain, Mexico, Latin American)

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

        // Portuguese (Brazilian + EU)

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

        // Italian

        'mi piace', 'pollice su',

        // Chinese simplified

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

        // Chinese traditional

        '讚', '喜歡',

        // Hindi (devanagari + romanized)

        'पसंद', 'pasand',

        // Japanese / Korean / Russian (covered for completeness)

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

    ];

    const matchTokens = (s, tokens) => {

        for (const k of tokens) {

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

        }

        return false;

    };

    const detectKind = (btn) => {

        // Signal 1: SVG class hint

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

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

        // Signal 2: SVG path d= (Lucide-style)

        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';

        }

        // Signal 3: aria-label substring (DISLIKE tokens FIRST, since many

        // contain LIKE as substring, e.g. "dislike" or "no me gusta").

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

        if (al) {

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

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

        }

        // Signal 4: title attribute substring (same logic).

        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);

        }

    };

    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();

    };

    setInterval(sweep, 400);

    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() {

        // Gradio renders Button as <button> directly with the elem_id on it,

        // or wraps in a div. Try both.

        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');

        }

        // Gate the submit button.

        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';

        }

        // Always re-run update; Gradio may re-render the button (e.g. on

        // ARM/CONFIRM state changes) so the disabled state needs reapplying.

        update();

    }

    setInterval(attach, 500);

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

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

})();

</script>

"""


# ============================================================
# Participant-side lockdown:
#   1. Force light theme regardless of browser dark-mode preference or
#      ?__theme query param being missing. Implemented by stripping the
#      'dark' class from <html>/<body> on load and re-stripping via a
#      MutationObserver if Gradio / SSR re-adds it.
#   2. Block paste/copy/cut/drag on the participant's argument textbox
#      (#right-essay) so they can't paste outside-AI text in nor copy the
#      running argument out. Both Phase 1 (initial argument) and Phase 2
#      (notepad) use the same textarea, so one guard covers both. JS
#      re-attaches via MutationObserver in case Gradio re-mounts the
#      textarea.
# ============================================================

# Injected at the very top of the head so the lockdown IIFEs below can
# check window.__LOCKDOWN.{argClipboard, chatCopy, endSessionGate} and
# bail out early when the corresponding feature is OFF in config.
_LOCKDOWN_FLAGS_JS = f"""<script>

window.__LOCKDOWN = {{

    argClipboard: {str(LOCKDOWN_ARG_CLIPBOARD).lower()},

    chatCopy: {str(LOCKDOWN_CHAT_COPY).lower()},

    endSessionGate: {str(ENFORCE_END_SESSION_GATE).lower()},

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

}};

</script>"""


INPUT_LOCKDOWN_HEAD = """

<style>

.arg-lockdown-toast {

    position: fixed;

    top: 16px;

    left: 50%;

    transform: translateX(-50%) translateY(-12px);

    background: rgba(31, 41, 55, 0.95);

    color: #fff;

    padding: 10px 18px;

    border-radius: 8px;

    font-size: 0.95em;

    line-height: 1.4;

    z-index: 100000;

    opacity: 0;

    pointer-events: none;

    transition: opacity 0.18s ease, transform 0.18s ease;

    box-shadow: 0 6px 24px rgba(0, 0, 0, 0.25);

    max-width: 520px;

    text-align: center;

}

.arg-lockdown-toast.show {

    opacity: 1;

    transform: translateX(-50%) translateY(0);

}

</style>

<script>

// --- Force light theme ---

(function() {

    function stripDark() {

        document.documentElement.classList.remove('dark');

        if (document.body) document.body.classList.remove('dark');

        document.documentElement.setAttribute('data-theme', 'light');

    }

    stripDark();

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

        document.addEventListener('DOMContentLoaded', stripDark);

    }

    // Observe and re-strip if Gradio / SSR re-adds .dark

    const obs = new MutationObserver(stripDark);

    obs.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme'] });

    if (document.body) {

        obs.observe(document.body, { attributes: true, attributeFilter: ['class'] });

    } else {

        document.addEventListener('DOMContentLoaded', () => {

            obs.observe(document.body, { attributes: true, attributeFilter: ['class'] });

        });

    }

})();



// --- Clipboard / drag lockdown on #right-essay textarea ---

(function() {

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

    const TOAST_ID = '__arg_lockdown_toast__';

    const BLOCKED = ['paste', 'copy', 'cut', 'drop', 'dragstart'];

    const MESSAGES = {

        paste: 'Pasting is disabled for this study. Please type your text directly.',

        copy:  'Copying out of this box is disabled for this study.',

        cut:   'Cut is disabled for this study.',

        drop:  'Dragging text into this box is disabled.',

        dragstart: 'Dragging text out of this box is disabled.'

    };



    function ensureToast() {

        let t = document.getElementById(TOAST_ID);

        if (t) return t;

        t = document.createElement('div');

        t.id = TOAST_ID;

        t.className = 'arg-lockdown-toast';

        document.body.appendChild(t);

        return t;

    }



    let hideTimer = null;

    function showToast(msg) {

        const t = ensureToast();

        t.textContent = msg;

        t.classList.add('show');

        if (hideTimer) clearTimeout(hideTimer);

        hideTimer = setTimeout(() => { t.classList.remove('show'); hideTimer = null; }, 2200);

    }



    const handler = (ev) => {

        ev.preventDefault();

        ev.stopPropagation();

        const msg = MESSAGES[ev.type] || 'Action disabled for this study.';

        showToast(msg);

        return false;

    };



    const attached = new WeakSet();

    function attachTo(el) {

        if (!el || attached.has(el)) return;

        BLOCKED.forEach(evt => el.addEventListener(evt, handler, { capture: true }));

        attached.add(el);

        console.log('[arg-lockdown] attached to', el.tagName, el);

    }



    function scan() {

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

        if (!root) return;

        root.querySelectorAll('textarea, input[type="text"]').forEach(attachTo);

    }



    function setup(tries) {

        tries = tries || 0;

        if (tries > 60) return;

        if (!document.querySelector('#right-essay')) {

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

            return;

        }

        scan();

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

        const obs = new MutationObserver(() => scan());

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

        console.log('[arg-lockdown] observer attached on #right-essay');

    }

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

        document.addEventListener('DOMContentLoaded', () => setup(0));

    } else {

        setup(0);

    }

})();



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

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

// clicks End Session but their current argument is still > 90% similar

// to the initial submission. Watcher creates a full-screen modal styled

// like the tutorial overlay; the "Go back and revise" button dismisses it.

(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();

    }

})();



// --- End-Session gate toast watcher ---

// When the server gates an End Session click (because the participant

// has not advanced through enough probes yet and the 20-minute timeout

// has not elapsed), it injects a hidden <div id="session-gate-trigger-NONCE">

// into the done_panel. This watcher spots the new id and shows a toast

// asking the participant to keep discussing. The nonce ensures repeated

// gated clicks each trigger the toast.

(function() {

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

    const SEEN = new Set();

    function showGateToast() {

        let t = document.getElementById('__arg_lockdown_toast__');

        if (!t) {

            t = document.createElement('div');

            t.id = '__arg_lockdown_toast__';

            t.className = 'arg-lockdown-toast';

            document.body.appendChild(t);

        }

        t.textContent = 'Your argument can still be refined. Please continue discussing with the AI before ending the session.';

        t.classList.add('show');

        setTimeout(function(){ t.classList.remove('show'); }, 3500);

    }

    function scan() {

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

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

            SEEN.add(el.id);

            showGateToast();

        });

    }

    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();

    }

})();



// --- Copy lockdown on #chatbot-main (the chat history / bot replies) ---

// Participants can still select text (so they can re-read or visually trace),

// but copy / cut / drag-out events are blocked. Reuses the arg-lockdown toast.

(function() {

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

    const ROOT_SEL = '#chatbot-main';

    const TOAST_ID = '__arg_lockdown_toast__';

    const BLOCKED = ['copy', 'cut', 'dragstart'];

    const MESSAGES = {

        copy:  'Copying from the chat is disabled for this study.',

        cut:   'Cut is disabled for this study.',

        dragstart: 'Dragging text out of the chat is disabled.'

    };



    function ensureToast() {

        let t = document.getElementById(TOAST_ID);

        if (t) return t;

        t = document.createElement('div');

        t.id = TOAST_ID;

        t.className = 'arg-lockdown-toast';

        document.body.appendChild(t);

        return t;

    }

    let hideTimer = null;

    function showToast(msg) {

        const t = ensureToast();

        t.textContent = msg;

        t.classList.add('show');

        if (hideTimer) clearTimeout(hideTimer);

        hideTimer = setTimeout(() => { t.classList.remove('show'); hideTimer = null; }, 2200);

    }

    const handler = (ev) => {

        ev.preventDefault();

        ev.stopPropagation();

        const msg = MESSAGES[ev.type] || 'Action disabled for this study.';

        showToast(msg);

        return false;

    };



    function setup(tries) {

        tries = tries || 0;

        if (tries > 60) return;

        const root = document.querySelector(ROOT_SEL);

        if (!root) {

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

            return;

        }

        BLOCKED.forEach(evt => root.addEventListener(evt, handler, { capture: true }));

        console.log('[chat-lockdown] attached on #chatbot-main', BLOCKED);

    }

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

        document.addEventListener('DOMContentLoaded', () => setup(0));

    } else {

        setup(0);

    }

})();

</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>

/* CSS targeting common HF Spaces floating widget classes */

.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"],

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

    display: none !important;

    visibility: hidden !important;

    pointer-events: none !important;

    height: 0 !important;

    width: 0 !important;

    overflow: hidden !important;

}

</style>

<script>

(function() {

    // HF Spaces floating widget signature: top-level element near top-right

    // that mentions the Space repo path or an HF Spaces-style breadcrumb.

    // We sweep on load and on every DOM mutation.

    const SIGNATURES = [

        'AE-Talk-bot/',

        'huggingface.co/spaces/',

        'Built with',

    ];

    function looksLikeHfWidget(el) {

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

        // Don't touch our own gradio app

        if (el.id === 'root' || el.id === 'gradio-app' ||

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

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

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

        if (txt.length > 400) return false;  // too big, not a small badge

        // Must match at least one signature

        for (const sig of SIGNATURES) {

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

        }

        // Also flag obviously-HF class names

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

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

        return false;

    }

    function sweep() {

        // Only check direct body children to keep this cheap

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

            if (looksLikeHfWidget(el)) {

                el.style.display = 'none';

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

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

            }

        });

    }

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

        document.addEventListener('DOMContentLoaded', sweep);

    } else {

        sweep();

    }

    // Re-sweep on every mutation in case HF injects later

    const obs = new MutationObserver(sweep);

    if (document.body) {

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

    } else {

        document.addEventListener('DOMContentLoaded', () => {

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

        });

    }

})();

</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>'

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,
)


FEEDBACK_HINT_HTML = (
    '<div class="discussion-intro">'
      '<div class="discussion-intro-title">How to use this discussion</div>'
      '<div class="discussion-intro-line">'
        '<b>1.</b> The chatbot will analyze your argument and discuss some '
        'related questions with you. As you go, <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> During the <b><i><u>discussion</u></i></b>, you can '
        '<b><i><u>ask for clarification, disagree, or explain what feels '
        'unclear</u></i></b>.'
      '</div>'
      '<div class="discussion-intro-line">'
        '<b>3.</b> The bot may take a few seconds to think before each reply. '
        'Please be patient — that\'s normal.'
      '</div>'
      '<div class="discussion-intro-line">'
        '<b>4.</b> After each bot reply, you can tag it:'
        '<ul class="discussion-intro-bullets">'
          '<li>Click ' + _AHA_INLINE_SVG + ' if it <b><i><u>helped</u></i></b>'
          ' you notice or rethink something new.</li>'
          '<li>Click ' + _UGH_INLINE_SVG + ' if it 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>'
)


# ============================================================
# Blocks
# ============================================================

# JS that takes over scroll behavior from Gradio's built-in autoscroll
# (we set autoscroll=False on the Chatbot):
#   1. On initial load: scroll to TOP of the chatbot so participants read the
#      case from the start (Gradio's default lands at the bottom).
#   2. While the bot is thinking/streaming OR any new message arrives: scroll
#      to BOTTOM via MutationObserver on the inner scroll container.
# The observer is armed only AFTER initial render is settled, so it doesn't
# fight the initial scroll-to-top.
_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;

        }

        // Initial: scroll to top, and re-assert a few times in case any late

        // layout pass tries to push us back down.

        inner.scrollTop = 0;

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

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

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

        // After initial render is settled, watch for ANY content change and

        // pin scroll to bottom. This covers: user message added, bot reply

        // streaming token-by-token, final reply settled.

        setTimeout(() => {

            const obs = new MutationObserver(() => {

                inner.scrollTop = inner.scrollHeight;

            });

            obs.observe(inner, {

                childList: true, subtree: true, characterData: true

            });

        }, 1600);

    };

    setup();

}

"""

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

    # Per-session cache dict. Holds parsed plan + manager_history.
    cache_state = gr.State({})

    # Per-session SessionLogger. Initialized in demo.load (Gradio 6.11
    # doesn't call callable defaults of gr.State).
    logger_state = gr.State()

    # Hidden Textbox carrying the walkthrough-finished timestamp from JS
    # (set by the walkthrough's "Start" button at the last slide) to the
    # Python on_submit_initial handler. The submit button's js= wrapper
    # reads window.__walkthroughStartedAt and overrides this value before
    # the Python handler runs.
    walkthrough_ts_input = gr.Textbox(
        value="",
        visible=False,
        elem_id="walkthrough-ts-input",
    )

    # ====== TOP ROW (tall): guide | chatbot | argument textbox ======
    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 start the discussion with the AI assistant.\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: chat input + send | action buttons ======
    # The top row's guide column is visible=False (collapsed by Gradio),
    # so the chatbot column expands left. The bottom row matches: no mirror
    # column, just chat-row (scale=3) + action-col (scale=2) aligned under
    # the chatbot (scale=3) and the argument textbox (scale=2) above.
    with gr.Row(equal_height=True):
        with gr.Column(scale=3):
            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 state for end_session_btn (Phase 2 to 3):
    arm_state = gr.State(0.0)
    revert_timer = gr.Timer(value=2.5, active=False)

    # 2-click confirmation state for submit_initial_btn (Phase 1 to 2):
    submit_initial_arm_state = gr.State(0.0)
    submit_initial_revert_timer = gr.Timer(value=2.5, active=False)

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

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

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



        `walkthrough_ts` is a string carrying the unix-seconds timestamp

        the participant clicked "Start" at the end of the walkthrough. It

        is injected by the js= wrapper on submit_initial_btn.click, which

        reads `window.__walkthroughStartedAt` (set client-side at the

        moment of the walkthrough Start click).



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

                      msg_input, send_btn, cache_state,

                      submit_initial_arm_state, submit_initial_revert_timer,

                      logger_state, arg_label_row, recovery_payload

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

        if arm_at and (now - arm_at) <= ARM_TTL:
            # CONFIRMED
            logger.start_session()
            # Assign one OpenAI key from the pool for this whole session
            # (round-robin across OPENAI_KEY_01..10). The same client is
            # then threaded through to manager + main bot + essay
            # generation for the rest of the session.
            try:
                _key_idx, _session_client = get_next_client()
                logger.set_assigned_key(_key_idx)
                print(f"[key_pool] session {logger.session_id} -> key_idx={_key_idx}",
                      flush=True)
            except Exception as _e:
                _key_idx, _session_client = None, None
                print(f"[key_pool] failed to assign key: {_e}", flush=True)
            # Persist the walkthrough-finished timestamp the JS handler
            # captured at the walkthrough-end "Start" click. Robust to
            # empty / malformed input.
            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.argument_submitted_at = now  # gates End Session by time
            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()
            cache = {INITIAL_ARG_KEY: arg_text,
                     SESSION_CLIENT_KEY: _session_client}

            history = history + [{"role": "user", "content": arg_text}]

            # Yield 1: phase-2 layout with a "preparing" status, chat disabled
            # while we generate the per-session essay + discussion plan.
            # 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": "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),
                cache,
                0.0,
                gr.update(active=False),
                logger,
                gr.update(value=ARG_LABEL_PHASE2),
                gr.update(value=save_payload),
            )

            # Generate the essay + plan. On any failure, fall back to no
            # plan (the main bot will freestyle without PLAN CONTROL).
            try:
                arts = generate_session_artifacts(arg_text, client=_session_client)
                if arts.get("perfect_answer"):
                    cache[PERFECT_ANSWER_KEY] = arts["perfect_answer"]
                    logger.set_perfect_answer(arts["perfect_answer"])
                if arts.get("dominant_framework"):
                    logger.set_dominant_framework(arts["dominant_framework"])
                    print(f"[framework] {arts['dominant_framework']}",
                          flush=True)
                if arts.get("discussion_plan"):
                    cache[PLAN_TEXT_KEY] = arts["discussion_plan"]
                    logger.set_discussion_plan(arts["discussion_plan"])
                    subprobes = plan_parsing.parse_plan(arts["discussion_plan"])
                    cache[PLAN_SUBPROBES_KEY] = subprobes
                    cache[MANAGER_HISTORY_KEY] = []
                    print(f"[plan_parsing] parsed {len(subprobes)} sub-probes",
                          flush=True)
            except Exception as e:
                print(f"[session_artifacts] generation failed: {e}", flush=True)

            # Yield 2: enable chat input, clear the status, prepare to stream
            # the bot's first reply.
            yield (
                history,
                gr.update(), gr.update(), gr.update(),
                gr.update(interactive=True,
                          placeholder="Type your response..."),
                gr.update(interactive=True),
                cache,
                gr.update(), gr.update(),
                logger,
                gr.update(),
                gr.update(),
            )

            # Stream the first bot reply. The participant's argument is the
            # 'user message' for turn 1 from the bot's perspective.
            t0 = time.perf_counter()
            turn_result = {}
            try:
                for history in stream_turn(arg_text, history, CASE_TEXT, cache, turn_result):
                    yield (
                        history,
                        gr.update(), gr.update(), gr.update(),
                        gr.update(), gr.update(), cache,
                        gr.update(), gr.update(),
                        logger,
                        gr.update(),
                        gr.update(),
                    )
                # After streaming finishes, persist this turn (manager_verdict +
                # plan_control + assistant_response + scratch + latencies).
                _log_turn(arg_text, cache, logger, turn_result, t0)
            finally:
                # Trigger ① on auto-first-turn: covers the manager-generated
                # perfect_answer + discussion_plan + dominant_framework (set
                # earlier in this handler) together with the first turn data.
                # In try/finally so PA/plan/framework get persisted even when
                # stream_turn raises (e.g. OpenAI mid-stream failure).
                if logger:
                    logger.checkpoint()

            # ENABLE end_session_btn.
            yield (
                gr.update(),
                gr.update(), gr.update(),
                gr.update(interactive=True),
                gr.update(), gr.update(),
                cache,
                gr.update(), gr.update(),
                logger,
                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(), cache,
                arm_at, gr.update(),
                logger,
                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(),
            cache,
            now,
            gr.update(active=True),
            logger,
            gr.update(),
            gr.update(),
        )

    def on_submit_initial_tick(arm_at):
        """1Hz tick: auto-revert submit_initial_btn after ARM_TTL."""
        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_send(msg, history, cache, logger, arg_text):
        """Regular chat turn: snapshot notepad, show user message, then run

        manager + main bot via the two-agent orchestrator. `arg_text` is the

        current notepad value (snapshotted to logger, never sent to bot).



        Trigger ① (per-turn push): exactly one HF upload at the end of this

        handler, covering everything accumulated since last upload:

          - chat_send snapshot

          - any feedback events / textbox snapshots between turns

          - this turn (user_message + manager_verdict + assistant_response)

        Bot-failure path also gets one push (try/finally) so a failed turn

        doesn't lose the user's message."""
        if not msg.strip():
            yield history, "", cache
            return

        logger.add_argument_snapshot(
            trigger="chat_send",
            text=arg_text,
            context={
                "next_turn_n": len(logger.turns) + 1,
                "user_msg_excerpt": msg[:120],
            },
        )

        history = history + [{"role": "user", "content": msg}]
        yield history, "", cache

        t0 = time.perf_counter()
        turn_result = {}
        try:
            for history in stream_turn(msg, history, CASE_TEXT, cache, turn_result):
                yield history, "", cache
            _log_turn(msg, cache, logger, turn_result, t0)
        finally:
            # Trigger ①: persist this turn + interim events. Runs on both
            # success and failure paths so we never lose the user's message
            # even if stream_turn raises mid-stream.
            if logger:
                logger.checkpoint()

    def on_end_session(arm_at, arg_text, logger):
        """2-click end-session/finalize. Generator so we can show an

        intermediate 'Uploading your session…' state while flush runs (up

        to ~165s of retries under HF rate-limit), then a final status

        message reflecting whether the upload actually succeeded.



        The 9th 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 (9): arg_input, end_session_btn, msg_input, send_btn,

                     done_panel, arm_state, revert_timer, arg_label_row,

                     recovery_payload

        """
        now = time.time()
        # Gate check on FIRST click only (when not yet armed / arm expired).
        # If the participant has not advanced through enough probes and
        # the 20-minute timeout hasn't elapsed, do not arm — instead emit
        # a toast asking them to keep discussing. Plan-complete sessions
        # always pass _can_end_session. Bypassed entirely if the
        # `lockdown.end_session_gate` config flag is false (test mode).
        is_first_click = not (arm_at and (now - arm_at) <= ARM_TTL)
        if ENFORCE_END_SESSION_GATE and is_first_click and not _can_end_session(logger):
            yield (
                gr.update(),  # arg_input
                gr.update(),  # end_session_btn (stays in normal state)
                gr.update(),  # msg_input
                gr.update(),  # send_btn
                gr.update(value=_gate_toast_trigger_html(), visible=True),
                arm_at,
                gr.update(),
                gr.update(),
                gr.update(),  # recovery_payload (no event)
            )
            return

        # Gate 2: revise-check. Fires at most once per session: compare the
        # current arg_text against the initial argument the participant
        # submitted at Phase-1; if word-level similarity is too high, they
        # have not revised — show the modal and block this click. Any later
        # End Session click goes through regardless of similarity.
        if (
            LOCKDOWN_REVISE_CHECK
            and is_first_click
            and logger is not None
            and not getattr(logger, "revise_warned", False)
        ):
            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:
                logger.revise_warned = True
                yield (
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    gr.update(value=_revise_gate_trigger_html(), visible=True),
                    arm_at,
                    gr.update(),
                    gr.update(),
                    gr.update(),  # recovery_payload (no event)
                )
                return

        if arm_at and (now - arm_at) <= ARM_TTL:
            # CONFIRMED. First yield: lock the UI + show 'uploading' state.
            yield (
                gr.update(interactive=False),
                gr.update(visible=False, value=END_SESSION_LABEL,
                          variant="secondary"),
                gr.update(interactive=False,
                          placeholder="Session ended. Saving your data…", value=""),
                gr.update(interactive=False),
                gr.update(value=SAVING_PANEL_HTML, visible=True),
                0.0,
                gr.update(active=False),
                gr.update(value=ARG_LABEL_LOCKED),
                gr.update(),  # recovery_payload (clear happens in next yield)
            )

            # Now run the actual flush (blocks for up to ~165s of retries).
            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()

            # Second yield: full-screen modal with the completion code.
            # Also emit "ended" event so the chained .then(js=...) clears
            # localStorage now that the session has been finalised.
            import json as _json_local
            yield (
                gr.update(),
                gr.update(),
                gr.update(),
                gr.update(),
                gr.update(value=_completion_modal_html(flush_result), visible=True),
                gr.update(),
                gr.update(),
                gr.update(),
                gr.update(value=_json_local.dumps({"event": "ended"})),
            )
            return

        # ARM (single yield equivalent to the original 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(),
            gr.update(),
            gr.update(),
            now,
            gr.update(active=True),
            gr.update(),
            gr.update(),  # recovery_payload (no event)
        )

    def on_timer_tick(arm_at):
        """1Hz tick: revert end_session_btn if not confirmed within ARM_TTL."""
        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_feedback(arg_text, logger, data: gr.LikeData):
        """Participant clicked aha! or ugh. on a bot message."""
        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.



        All three conditions (A/B/C) share the same HF dataset

        (`AE-Talk-bot/log-Jun-17-2026`), so the file lookup is restricted to

        this Space's mode prefix (LOG_PATH's parent) to prevent picking up a

        session belonging to a different condition.



        Outputs (12): same shape as on_submit_initial.

        """
        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")
            # Restrict to this Space's mode_prefix (e.g. "A-soc/" /
            # "B-ans/" / "C-non/") so a session belonging to a different
            # condition in the same shared dataset does not match.
            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)")

        initial_arg = (data.get("essays") or {}).get("argument", {}).get("text", "")
        # Resolve the assigned OpenAI key back to its pool client. The index
        # was preserved across the recovery boundary (from_dict restored it
        # on the logger). If we can't find a matching pool entry, fall back
        # to whatever get_next_client returns now.
        from core.config_loader import KEY_POOL as _KP
        _restored_client = None
        _restored_idx = new_logger.assigned_key_idx
        if _restored_idx is not None:
            for _idx, _c in _KP:
                if _idx == _restored_idx:
                    _restored_client = _c
                    break
        if _restored_client is None:
            try:
                _restored_idx, _restored_client = get_next_client()
                new_logger.set_assigned_key(_restored_idx)
                print(f"[recover] no original key match; re-assigned key_idx={_restored_idx}",
                      flush=True)
            except Exception as _e:
                print(f"[recover] failed to assign client on recovery: {_e}", flush=True)
        cache = {INITIAL_ARG_KEY: initial_arg,
                 SESSION_CLIENT_KEY: _restored_client}
        pa = data.get("perfect_answer")
        if pa and pa.get("text"):
            cache[PERFECT_ANSWER_KEY] = pa["text"]
        dp = data.get("discussion_plan")
        if dp and dp.get("text"):
            cache[PLAN_TEXT_KEY] = dp["text"]
            try:
                cache[PLAN_SUBPROBES_KEY] = plan_parsing.parse_plan(dp["text"])
            except Exception as e:
                print(f"[recover] plan re-parse failed: {e}", flush=True)
        cache[MANAGER_HISTORY_KEY] = list(data.get("manager_history") or [])

        history = []
        for t in (data.get("turns") or []):
            um = t.get("user_message")
            ar = t.get("assistant_response")
            if um:
                history.append({"role": "user", "content": um})
            if ar:
                history.append({"role": "assistant", "content": ar})

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

        print(f"[recover] OK: sid={sid}, "
              f"{len(history)//2} chat exchanges, "
              f"{len(cache.get(MANAGER_HISTORY_KEY) or [])} verdicts, "
              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.
        new_logger.checkpoint()

        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 response..."),
            gr.update(interactive=True),
            cache,
            0.0,
            gr.update(active=False),
            new_logger,
            gr.update(value=ARG_LABEL_PHASE2),
            gr.update(value=save_payload),
        )

    _initial_outputs = [
        chatbot,
        arg_input,
        submit_initial_btn,
        end_session_btn,
        msg_input,
        send_btn,
        cache_state,
    ]

    _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, cache_state, submit_initial_arm_state, logger_state, walkthrough_ts_input],
        outputs=_initial_outputs + [submit_initial_arm_state, submit_initial_revert_timer, logger_state, arg_label_row, recovery_payload],
        js="""(arg_text, history, cache, arm_at, logger, ts_in) => {

            // Override the hidden walkthrough-ts input with the value JS

            // captured at the walkthrough-end Start click. Empty string

            // if the participant somehow skipped the walkthrough.

            var ts = window.__walkthroughStartedAt;

            return [arg_text, history, cache, 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, 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],
    )

    send_btn.click(
        on_send,
        inputs=[msg_input, chatbot, cache_state, logger_state, arg_input],
        outputs=[chatbot, msg_input, cache_state],
    )
    msg_input.submit(
        on_send,
        inputs=[msg_input, chatbot, cache_state, logger_state, arg_input],
        outputs=[chatbot, msg_input, cache_state],
    )

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

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

    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,
    )


# ============================================================
# Auto-restart (unchanged from v3)
# ============================================================

def _start_auto_restart():
    import os
    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)

    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 + INPUT_LOCKDOWN_HEAD + HIDE_HF_WIDGET_HEAD + RECOVERY_HEAD + TUTORIAL_HEAD,
        show_error=True,
    )