File size: 110,904 Bytes
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06adb09
532e19f
 
 
 
 
 
06adb09
 
 
 
 
 
 
 
 
 
 
532e19f
 
 
 
 
da114c3
532e19f
 
 
 
 
8b26302
 
532e19f
8b26302
532e19f
 
 
 
88c8f94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532e19f
 
da114c3
 
 
 
 
 
 
8b26302
 
 
 
da114c3
 
 
 
8b26302
da114c3
 
 
 
 
 
8b26302
 
 
 
da114c3
 
 
 
8b26302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532e19f
 
 
 
 
7bca098
 
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0d4a14
 
 
 
4966a08
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0d4a14
 
 
 
 
532e19f
 
 
 
 
 
 
 
7bca098
532e19f
 
 
7bca098
 
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0d4a14
 
 
 
 
 
 
 
 
 
 
 
 
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0d4a14
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4966a08
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc924c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
f462d79
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
19e14ce
532e19f
 
19e14ce
 
 
532e19f
 
 
 
 
 
 
 
19e14ce
 
 
 
 
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19e14ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0d4a14
 
 
 
 
 
 
 
 
 
 
 
 
 
532e19f
 
f462d79
 
532e19f
 
 
 
 
 
f462d79
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f462d79
532e19f
f462d79
532e19f
f462d79
532e19f
f462d79
532e19f
f462d79
532e19f
 
 
a5b1f73
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1514fe9
532e19f
 
 
 
 
 
 
 
 
 
 
1514fe9
 
 
 
 
532e19f
1514fe9
532e19f
 
 
 
1514fe9
 
 
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0d4a14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac423d6
d0d4a14
 
 
 
88c8f94
d0d4a14
 
 
 
 
 
 
 
da114c3
 
8b26302
da114c3
8b26302
d0d4a14
 
 
 
 
 
 
88c8f94
 
 
d0d4a14
 
 
 
4966a08
d0d4a14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac423d6
 
d0d4a14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da114c3
8b26302
d0d4a14
 
 
 
 
 
 
532e19f
 
 
 
 
 
 
 
 
 
 
88c8f94
 
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f67317
532e19f
 
 
 
 
 
 
ac423d6
532e19f
 
 
 
bc924c8
 
 
966b67b
532e19f
 
 
88c8f94
532e19f
 
 
 
88c8f94
 
 
532e19f
 
 
 
37e69ba
88c8f94
532e19f
 
 
 
 
 
 
37e69ba
88c8f94
37e69ba
88c8f94
 
 
532e19f
 
 
 
 
 
 
 
 
 
 
88c8f94
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd01e62
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c60efa
532e19f
 
 
 
 
 
 
 
 
 
 
 
0f7e56d
 
 
532e19f
9c60efa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532e19f
 
88c8f94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532e19f
 
 
bc924c8
b1b80c1
532e19f
 
 
 
88c8f94
 
 
 
 
 
 
 
 
532e19f
 
 
 
 
b1b80c1
532e19f
 
 
 
 
 
 
 
bc924c8
88c8f94
532e19f
88c8f94
 
532e19f
 
 
88c8f94
532e19f
88c8f94
 
532e19f
9c60efa
bc924c8
532e19f
 
 
 
 
 
88c8f94
 
 
 
 
 
 
 
 
06adb09
 
 
 
 
532e19f
 
 
 
 
88c8f94
06adb09
532e19f
06adb09
532e19f
 
 
 
 
 
 
 
 
06adb09
88c8f94
 
06adb09
 
532e19f
 
 
 
 
06adb09
 
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
06adb09
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88c8f94
 
 
 
 
 
532e19f
 
 
 
 
bc924c8
b1b80c1
532e19f
 
 
 
 
 
 
 
bc924c8
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0d4a14
532e19f
 
 
d0d4a14
 
 
 
532e19f
 
d0d4a14
532e19f
 
 
 
 
 
 
d0d4a14
 
 
 
532e19f
 
 
 
 
 
 
 
d0d4a14
532e19f
 
 
f462d79
 
 
 
d0d4a14
 
 
 
f462d79
 
 
532e19f
 
 
 
 
 
 
 
 
88c8f94
 
 
 
 
 
 
 
 
88ae850
 
 
06adb09
9c60efa
88ae850
 
9c60efa
 
06672ed
88ae850
 
06672ed
88ae850
 
 
 
 
 
 
 
 
 
 
9c60efa
88ae850
 
 
 
 
d0d4a14
 
88ae850
 
 
 
 
88c8f94
 
 
 
 
 
 
 
 
 
 
88ae850
 
 
 
 
 
 
 
 
 
 
 
 
d0d4a14
 
 
 
 
 
 
ac423d6
d0d4a14
 
 
 
88c8f94
d0d4a14
 
8b26302
 
 
 
88ae850
 
06672ed
88ae850
9c60efa
 
06672ed
88ae850
 
06672ed
88ae850
 
8b26302
06672ed
 
d0d4a14
da114c3
 
8b26302
da114c3
 
8b26302
da114c3
06672ed
 
da114c3
06672ed
 
da114c3
06672ed
 
 
 
 
 
 
ac423d6
d0d4a14
06672ed
da114c3
 
 
 
 
 
 
 
06672ed
 
d0d4a14
 
da114c3
 
 
06672ed
d0d4a14
88ae850
06672ed
 
 
c1a20da
88ae850
 
 
 
 
 
9c60efa
88ae850
 
532e19f
88c8f94
 
 
 
 
 
 
 
 
532e19f
 
ac423d6
532e19f
 
 
 
 
ac423d6
 
 
 
 
 
 
 
532e19f
88c8f94
 
 
 
 
 
 
 
532e19f
 
19e14ce
532e19f
 
 
 
 
 
 
ac423d6
 
 
 
 
 
 
532e19f
 
 
 
1514fe9
 
 
 
 
 
ac423d6
532e19f
 
 
 
 
 
 
 
 
d0d4a14
532e19f
d0d4a14
 
532e19f
d0d4a14
 
532e19f
 
 
 
 
0f7e56d
88c8f94
 
532e19f
9c60efa
 
532e19f
 
 
 
 
 
 
 
 
665d2d5
532e19f
 
88c8f94
 
ac423d6
532e19f
 
 
88c8f94
 
ac423d6
532e19f
 
cc66fcd
 
 
 
 
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f67317
532e19f
 
 
ac423d6
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd01e62
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0d4a14
 
 
 
 
532e19f
 
d0d4a14
532e19f
 
 
d0d4a14
 
 
 
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac423d6
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0d4a14
 
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0d4a14
 
 
 
 
 
 
ac423d6
d0d4a14
 
 
 
 
8b26302
 
 
 
 
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac423d6
532e19f
 
ac423d6
532e19f
 
 
 
 
 
 
19e14ce
532e19f
 
 
 
 
 
 
ac423d6
 
 
 
 
 
 
532e19f
 
 
 
1514fe9
 
 
 
 
 
ac423d6
532e19f
 
 
 
 
d0d4a14
532e19f
d0d4a14
 
532e19f
 
 
 
 
 
 
 
ac423d6
532e19f
 
 
 
 
 
 
 
 
 
 
 
ac423d6
 
532e19f
 
 
ac423d6
 
532e19f
 
cc66fcd
 
 
 
532e19f
5371d91
 
 
 
 
 
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
"""
Student Interface β€” Gradio GUI for the Legacy Code Challenge.

Two-page flow:
  Page 1 (Setup):     student name, GitHub URL, nesting level, num-bugs, options β†’ Start
  Page 2 (Challenge): README, Code Editor, Test runner + AI Assistant sidebar
  Page 3 (Results):   Score breakdown, diffs, test results, hints review
"""

from __future__ import annotations

import difflib
import json
import os
import sys
import threading
import logging
from io import StringIO
from datetime import datetime
from pathlib import Path

import gradio as gr

# Configure detailed logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
    handlers=[
        logging.FileHandler('app.log', encoding='utf-8'),
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger(__name__)

from orchestrator.scoring import evaluate_submission
from orchestrator.hint_graph import get_hint

# Optional Google Sheets logging
try:
    from google_sheets_logger import diagnose_google_sheets, log_to_google_sheets
    GOOGLE_SHEETS_AVAILABLE = True
except ImportError:
    GOOGLE_SHEETS_AVAILABLE = False

try:
    from supabase_submissions_logger import upload_submission_to_supabase
    SUPABASE_AVAILABLE = True
except ImportError:
    SUPABASE_AVAILABLE = False


# ── API Key Validation ────────────────────────────────────────────────────────

from llm_config import llm_api_key_context, validate_api_key as validate_openai_key

HF_OAUTH_REQUIRED = bool(os.getenv("SPACE_ID"))


def _configured_llm_api_key() -> str:
    provider = os.getenv("LLM_PROVIDER", "openai").lower()
    env_var = "GROQ_API_KEY" if provider == "groq" else "OPENAI_API_KEY"
    return os.getenv(env_var, "")


def _hf_oauth_identity(profile: gr.OAuthProfile | None) -> dict | None:
    if profile is None:
        return None
    username = str(profile.username or "").strip()
    if not username:
        return None
    return {
        "provider": "huggingface",
        "provider_user_id": username,
        "profile_url": str(profile.profile or ""),
        "display_name": str(profile.name or username).strip(),
    }


def _hf_auth_required(profile: gr.OAuthProfile | None) -> bool:
    return HF_OAUTH_REQUIRED and _hf_oauth_identity(profile) is None


def _google_sheets_configured() -> bool:
    return bool(os.getenv("GOOGLE_SHEET_ID")) and (
        bool(os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON"))
        or Path("google-service-account.json").exists()
    )


def _supabase_configured() -> bool:
    return bool(os.getenv("SUPABASE_URL")) and bool(
        os.getenv("SUPABASE_SECRET_KEY") or os.getenv("SUPABASE_SERVICE_ROLE_KEY")
    )


def _cloud_upload_capabilities() -> dict[str, dict[str, str | bool]]:
    google_configured = _google_sheets_configured()
    supabase_configured = _supabase_configured()
    return {
        "google_sheets": {
            "available": GOOGLE_SHEETS_AVAILABLE,
            "configured": google_configured,
            "reason": "" if google_configured else "Missing GOOGLE_SHEET_ID or service account credentials",
        },
        "supabase": {
            "available": SUPABASE_AVAILABLE,
            "configured": supabase_configured,
            "reason": "" if supabase_configured else "Missing SUPABASE_URL or Supabase server secret",
        },
    }


def _save_submission_to_supabase(log: "SubmissionLog", log_path: Path, record: dict) -> dict[str, str]:
    capability = _cloud_upload_capabilities()["supabase"]
    if not capability["available"] or not capability["configured"]:
        result = {"status": "disabled", "error": str(capability["reason"])}
    else:
        try:
            ok, reason = upload_submission_to_supabase(record)
            result = {
                "status": "success" if ok else "failed",
                "error": "" if ok else reason,
            }
        except Exception as exc:
            result = {"status": "failed", "error": type(exc).__name__}

    log.update(log_path, {"cloud": {"supabase": result}})
    if result["status"] == "success":
        logger.info("Submission %s stored in Supabase", record.get("submission_id", ""))
    else:
        logger.warning("Supabase submission storage %s: %s", result["status"], result["error"])
    return result


# ── Challenge state loader ────────────────────────────────────────────────────

class ChallengeState:
    """Loads and exposes data from challenge_state.json."""

    _HIDDEN_WORKSPACE_FILES = {"challenge_run_secret.py"}

    def __init__(self, workspace_path: str) -> None:
        self.workspace = Path(workspace_path)
        state_file = self.workspace / "challenge_state.json"
        if not state_file.exists():
            raise FileNotFoundError(f"challenge_state.json not found in {workspace_path}")
        with open(state_file, encoding="utf-8") as f:
            data = json.load(f)

        self.github_url:       str  = data.get("github_url", "")
        # Normalise to forward slashes so comparisons work cross-platform
        raw_target = data.get("target_file", "")
        try:
            self.target_file: str = Path(raw_target).resolve().relative_to(self.workspace.resolve()).as_posix()
        except (ValueError, OSError):
            self.target_file = Path(raw_target).as_posix()
        self.original_code:    str  = data.get("original_code", "")
        self.sabotaged_code:   str  = data.get("sabotaged_code", "")
        self.function_name:    str  = data.get("function_name", "")
        self.bug_func_name:           str  = data.get("bug_func_name", "")
        self.original_bug_func_source: str  = data.get("original_bug_func_source", "")
        self.bug_func_names: list = data.get("bug_func_names", []) or (
            [self.bug_func_name] if self.bug_func_name else []
        )
        self.bug_func_sources_list: list = data.get("bug_func_sources_list", [])
        self.original_bug_func_sources_list: list = data.get("original_bug_func_sources_list", [])
        self.public_tests: list = data.get("public_tests", [])
        self.secret_tests: list = data.get("secret_tests", [])
        self.bug_description: str = data.get("bug_description", "")
        self.challenge_created_at: str = data.get("challenge_created_at", "")
        self.challenge_summary: str = data.get("challenge_summary", "")
        self.nesting_level:    int  = data.get("nesting_level", 3)
        self.refactoring_enabled: bool = data.get("refactoring_enabled", False)
        self.debug_mode:       bool = data.get("debug_mode", False)

        # sabotaged_files: {rel_posix_path: content} for every file the
        # saboteur touched.  Primary source: .metadata/ directory
        # written by the deployer immediately after sabotage (always up-to-date).
        # Fallback: sabotaged_files dict in JSON, then single sabotaged_code field.
        snapshot_dir = self.workspace / ".metadata"
        snap_files: dict[str, str] = {}
        if snapshot_dir.exists():
            # Get the target file path from the data for proper mapping
            target_rel_from_json = data.get("target_file", "")
            if target_rel_from_json:
                try:
                    # Convert to workspace-relative posix path
                    target_abs = Path(target_rel_from_json).resolve()
                    target_rel = target_abs.relative_to(self.workspace.resolve()).as_posix()
                except (ValueError, OSError):
                    target_rel = Path(target_rel_from_json).as_posix()
                
                # Find the corresponding snapshot file
                # The snapshot filename has separators replaced with __
                expected_snapshot_name = target_rel.replace("/", "__")
                snapshot_path = snapshot_dir / expected_snapshot_name
                
                if snapshot_path.exists():
                    try:
                        snap_files[target_rel] = snapshot_path.read_text(encoding="utf-8")
                    except Exception:
                        pass

        if snap_files:
            self.sabotaged_files: dict[str, str] = snap_files
        else:
            # Fall back to JSON fields
            stored = data.get("sabotaged_files", {})
            if not stored and self.sabotaged_code:
                try:
                    rel = Path(self.target_file).resolve().relative_to(
                        self.workspace.resolve()
                    ).as_posix()
                except ValueError:
                    rel = Path(self.target_file).name
                stored = {rel: self.sabotaged_code}
            self.sabotaged_files = stored

    @property
    def target_path(self) -> Path:
        return self.workspace / self.target_file

    def read_target(self) -> str:
        if self.target_path.exists():
            return self.target_path.read_text(encoding="utf-8")
        return self.sabotaged_code

    def write_target(self, code: str) -> None:
        self.target_path.write_text(code, encoding="utf-8")

    def write_py_file(self, rel_path: str, code: str) -> None:
        file_path = self.workspace / rel_path
        file_path.parent.mkdir(parents=True, exist_ok=True)
        file_path.write_text(code, encoding="utf-8")

    def reset_target(self) -> None:
        self.write_target(self.sabotaged_code)

    def list_py_files(self) -> list[str]:
        files = sorted(self.workspace.rglob("*.py"))
        return [
            f.relative_to(self.workspace).as_posix() for f in files
            if ".metadata" not in f.parts
            and f.relative_to(self.workspace).as_posix() not in self._HIDDEN_WORKSPACE_FILES
        ]

    def read_py_file(self, rel_path: str) -> str:
        if Path(rel_path).as_posix() in self._HIDDEN_WORKSPACE_FILES:
            return "# File not available in challenge UI."
        full = self.workspace / rel_path
        if full.exists():
            return full.read_text(encoding="utf-8")
        return f"# File not found: {rel_path}"

    def readme(self) -> str:
        readme_path = self.workspace / "STUDENT_README.md"
        if readme_path.exists():
            return readme_path.read_text(encoding="utf-8")
        return "# Challenge\n\nREADME not found."

    def challenge_info(self) -> dict:
        return {
            "function_name":                  self.function_name,
            "bug_func_name":                  self.bug_func_name,
            "target_file":                    self.target_file,
            "nesting_level":                  self.nesting_level,
            "refactoring_enabled":            self.refactoring_enabled,
            "debug_mode":                     self.debug_mode,
            "bug_func_names":                 self.bug_func_names,
            "bug_func_sources_list":          self.bug_func_sources_list,
            "original_bug_func_sources_list": self.original_bug_func_sources_list,
            "original_code":                  self.original_code,
        }


# ── Submission log ────────────────────────────────────────────────────────────

class SubmissionLog:
    """Persists submissions to <workspace>/submissions/ as JSON files."""

    def __init__(self, workspace: Path) -> None:
        self.log_dir = workspace / "submissions"
        self.log_dir.mkdir(exist_ok=True)

    def save(self, entry: dict) -> Path:
        submission_id = entry.get("submission_id") or datetime.now().strftime("%Y%m%d_%H%M%S_%f")
        path = self.log_dir / f"{submission_id}.json"
        with open(path, "w", encoding="utf-8") as f:
            json.dump(entry, f, indent=2, ensure_ascii=False)
        return path

    def update(self, path: Path, updates: dict) -> None:
        if not path.exists():
            return
        with open(path, encoding="utf-8") as f:
            entry = json.load(f)
        _deep_merge_dict(entry, updates)
        with open(path, "w", encoding="utf-8") as f:
            json.dump(entry, f, indent=2, ensure_ascii=False)


# ── Pipeline runner ───────────────────────────────────────────────────────────

def _run_pipeline(github_url: str, nesting_level: int, num_bugs: int, 
                  refactoring_enabled: bool = False, debug_mode: bool = False) -> str:
    """Invoke the architect pipeline and return the workspace path."""
    from architect.graph import build_graph

    graph = build_graph()
    result = graph.invoke({
        "github_url":          github_url,
        "nesting_level":       nesting_level,
        "refactoring_enabled": refactoring_enabled,
        "debug_mode":          debug_mode,
        "num_bugs":            num_bugs,
        "clone_path":          "",
        "target_file":         "",
        "original_code":       "",
        "sabotaged_code":      "",
        "function_name":       "",
        "test_args":           "",
        "expected_output":     "",
        "actual_output":       "",
        "bug_description":     "",
        "detailed_explanation": "",
        "challenge_summary":   "",
        "test_cases":          [],
        "public_tests":        [],
        "secret_tests":        [],
        "candidate_files":     [],
        "bug_func_name":       "",
        "bug_func_source":     "",
        "call_chain":          {},
    })

    workspace_path = result["clone_path"]

    # Read the actual file on disk (may differ from state if extra transforms ran)
    target_file_rel = result.get("target_file", "")
    actual_sabotaged_code = result.get("sabotaged_code", "")
    workspace_path_obj = Path(workspace_path).resolve()
    if target_file_rel:
        target_path = Path(workspace_path) / target_file_rel
        if target_path.exists():
            actual_sabotaged_code = target_path.read_text(encoding="utf-8")

    # Build sabotaged_files: {rel_posix_path: content} for every file the
    # saboteur modified.  Currently always one file (target_file).
    sabotaged_files: dict[str, str] = {}
    if target_file_rel and actual_sabotaged_code:
        try:
            rel_posix = Path(target_file_rel).resolve().relative_to(workspace_path_obj).as_posix()
        except (ValueError, OSError):
            rel_posix = Path(target_file_rel).as_posix()
        sabotaged_files[rel_posix] = actual_sabotaged_code

    # Persist challenge_state.json
    challenge_state = {
        "github_url":          github_url,
        "workspace_path":      workspace_path,
        "challenge_created_at": datetime.now().isoformat(),
        "target_file":         target_file_rel,
        "original_code":       result.get("original_code",    ""),
        "sabotaged_code":      actual_sabotaged_code,
        "sabotaged_files":     sabotaged_files,
        "function_name":       result.get("function_name",    ""),
        "bug_func_name":       result.get("bug_func_name",    ""),
        "bug_func_source":          result.get("bug_func_source",           ""),
        "original_bug_func_source": result.get("original_bug_func_source",  ""),
        "bug_func_names":              result.get("bug_func_names",              []),
        "bug_func_sources_list":       result.get("bug_func_sources_list",       []),
        "original_bug_func_sources_list": result.get("original_bug_func_sources_list", []),
        "test_cases":          result.get("test_cases",       []),
        "public_tests":        result.get("public_tests",     []),
        "secret_tests":        result.get("secret_tests",     []),
        "nesting_level":       nesting_level,
        "refactoring_enabled": refactoring_enabled,
        "debug_mode":          debug_mode,
        "bug_description":     result.get("bug_description",  ""),
        "challenge_summary":   result.get("challenge_summary", ""),
    }
    state_path = Path(workspace_path) / "challenge_state.json"
    with open(state_path, "w", encoding="utf-8") as f:
        json.dump(challenge_state, f, indent=2, ensure_ascii=False)

    return workspace_path


# ── Helpers ───────────────────────────────────────────────────────────────────

PENALTY_TABLE = [0, 2, 6, 12, 20, 30]

# Sets dark mode as the default on first visit and defines window.startTimer.
def _make_js(timer_minutes: int = 0) -> str:
    auto_start = (
        f"""
    (function tryStartTimer() {{
        if (document.getElementById('timer-inner')) {{
            window.startTimer({timer_minutes});
        }} else {{
            setTimeout(tryStartTimer, 150);
        }}
    }})();"""
        if timer_minutes > 0 else ""
    )
    return """() => {
    if (!localStorage.getItem('gradio-theme')) {
        localStorage.setItem('gradio-theme', 'dark');
    }
    window.startTimer = function(minutes) {
        if (!minutes || minutes <= 0) return;
        if (window._timerInterval) clearInterval(window._timerInterval);
        const endTime = Date.now() + minutes * 60 * 1000;
        function tick() {
            const remaining = Math.max(0, endTime - Date.now());
            const m = Math.floor(remaining / 60000);
            const s = Math.floor((remaining % 60000) / 1000);
            const el = document.getElementById('timer-inner');
            if (!el) return;
            if (remaining === 0) {
                el.innerHTML = '<span style="color:#ef4444;font-weight:bold;font-size:1.1em;">⏱️ TIME\\'S UP!</span>';
                clearInterval(window._timerInterval);
            } else {
                const color = remaining < 300000 ? '#ef4444' : (remaining < 600000 ? '#f59e0b' : '#22c55e');
                el.innerHTML = '⏱️ <span style="font-weight:bold;font-size:1.1em;color:' + color + ';">'
                    + String(m).padStart(2,'0') + ':' + String(s).padStart(2,'0') + '</span>';
            }
        }
        tick();
        window._timerInterval = setInterval(tick, 1000);
    };
""" + auto_start + "\n}"


_JS = _make_js(0)

_CSS = """
/* Keep footer visible */
footer svg { display: inline !important; }
.gradio-container { max-width: 100% !important; }

/* Setup page β€” centred card */
.setup-card { max-width: 700px; margin: 40px auto !important; }

/* Account action */
#logout-row {
    display: flex !important;
    justify-content: flex-end !important;
    width: min(100%, 1200px) !important;
    margin: 0 auto 8px !important;
}
#logout-btn {
    flex: 0 0 auto !important;
    width: auto !important;
    min-width: 96px !important;
}
#logout-btn button {
    min-height: 36px !important;
    padding: 0 12px !important;
    border-radius: 6px !important;
    font-weight: 500 !important;
}

/* Code editor β€” scrollable */
#code-editor .cm-scroller { overflow-y: auto !important; max-height: 60vh !important; }
#code-editor .cm-editor   { max-height: 60vh !important; }

/* Chatbot */
#ai-chatbot .wrap { height: 58vh !important; overflow-y: auto !important; }

/* Tab content */
.left-tabs .tabitem { overflow-y: auto !important; max-height: 80vh !important; }

/* Results diff blocks */
.diff-block { font-family: monospace; font-size: 0.85em; padding: 12px;
              border-radius: 8px; overflow-y: auto; max-height: 45vh;
              white-space: pre-wrap; background: #1e1e1e; color: #d4d4d4; }

/* Challenge timer β€” pushed to the right corner of the header */
.header-row { display: flex !important; align-items: center !important;
              width: 100% !important; gap: 8px; }
.header-row > * { flex-shrink: 0 !important; }
.header-row > *:first-child { flex: 1 1 auto !important; min-width: 0; }
#challenge-timer { flex: 0 0 auto !important; font-family: monospace;
                   font-size: 1em; text-align: right; padding: 4px 8px;
                   min-width: 90px; white-space: nowrap; }
"""


def _hint_md(hints_used: int, penalty: int) -> str:
    next_penalty = PENALTY_TABLE[min(hints_used + 1, len(PENALTY_TABLE) - 1)]
    return (
        f"πŸ€– **AI Assistant** &nbsp;|&nbsp; "
        f"Hints used: **{hints_used}** &nbsp;|&nbsp; Current cumulative penalty: **βˆ’{penalty} pts** &nbsp;|&nbsp; "
        f"Next hint: **βˆ’{next_penalty} pts** &nbsp; "
        f"_(schedule: βˆ’2 / βˆ’6 / βˆ’12 / βˆ’20 / βˆ’30)_"
    )


_HINT_DECLINES = {
    "no", "nope", "nah", "not now", "nevermind", "never mind",
    "no thanks", "no thank you", "skip", "cancel", "forget it",
    "don't", "dont", "no hint", "stop",
}
_HINT_AFFIRMATIONS = {
    "yes", "y", "yeah", "yep", "sure", "ok", "okay", "proceed", "go ahead", "do it",
    "please do", "continue", "hint", "give me a hint",
    "Χ›ΧŸ", "Χ›ΧŸ Χ‘Χ‘Χ§Χ©Χ”", "ΧͺΧžΧ©Χ™Χš", "Χͺן Χ¨ΧžΧ–", "Χͺן ΧœΧ™ Χ¨ΧžΧ–", "Χ™ΧΧœΧœΧ”", "Χ‘Χ‘Χ‘Χ”",
}
_CONFIRMATION_KWS = ["would you like", "shall i", "want me to", "proceed", "penalty to your score"]


def _is_decline(msg: str) -> bool:
    m = msg.strip().lower()
    return (
        m in _HINT_DECLINES
        or m.startswith("no ")
        or m.startswith("don't")
        or m.startswith("dont")
        or m.startswith("nope ")
        or m.startswith("nah ")
    )


def _is_confirmation_question(text: str) -> bool:
    t = text.lower()
    return any(kw in t for kw in _CONFIRMATION_KWS)


def _is_affirmation(msg: str) -> bool:
    m = msg.strip().lower()
    return (
        m in _HINT_AFFIRMATIONS
        or m.startswith("yes ")
        or m.startswith("sure ")
        or m.startswith("ok ")
        or m.startswith("okay ")
        or m.startswith("go ahead")
        or m.startswith("continue")
        or m.startswith("Χ›ΧŸ")
        or m.startswith("Χͺן")
        or m.startswith("ΧͺΧžΧ©Χ™Χš")
    )


def _colorise_test_output(raw: str) -> str:
    """Wrap test output lines in coloured HTML spans."""
    html_lines = []
    for line in raw.split("\n"):
        if ": PASS" in line or "ALL PASS" in line:
            html_lines.append(f'<span style="color:#22c55e;font-weight:bold;">{line}</span>')
        elif ": FAIL" in line or ": CRASH" in line or "FAILED" in line:
            html_lines.append(f'<span style="color:#ef4444;font-weight:bold;">{line}</span>')
        else:
            html_lines.append(f'<span style="color:#d4d4d4;">{line}</span>')
    return (
        '<pre style="font-family:monospace;padding:12px;background:#1e1e1e;'
        'color:#d4d4d4;border-radius:8px;overflow-y:auto;max-height:60dvh;'
        'white-space:pre-wrap;">'
        + "<br>".join(html_lines)
        + "</pre>"
    )


def _normalize(code: str) -> str:
    """Strip trailing whitespace per line and normalize line endings."""
    return "\n".join(line.rstrip() for line in code.replace("\r\n", "\n").replace("\r", "\n").splitlines())


def _plain_diff_text(a: str, b: str, from_label: str, to_label: str) -> str:
    a_lines = _normalize(a).splitlines(keepends=True)
    b_lines = _normalize(b).splitlines(keepends=True)
    return "".join(difflib.unified_diff(a_lines, b_lines, fromfile=from_label, tofile=to_label, lineterm=""))


def _deep_merge_dict(target: dict, updates: dict) -> None:
    for key, value in updates.items():
        if isinstance(value, dict) and isinstance(target.get(key), dict):
            _deep_merge_dict(target[key], value)
        else:
            target[key] = value


def _workspace_diff_html(cs: "ChallengeState") -> str:
    """
    Show a unified diff for the target file the student changed.
    Compare the locally stored received-state snapshot vs the current disk content.
    This ensures only the student's changes are shown β€” not the sabotage noise.
    """
    workspace        = cs.workspace.resolve()
    sabotaged_files  = cs.sabotaged_files   # {rel_posix: received_content}
    sections: list[str] = []

    # Show diff for files modified by the saboteur (the target file)
    for rel_posix, received_content in sabotaged_files.items():
        full_path = workspace / rel_posix
        if not full_path.exists():
            continue
        current = full_path.read_text(encoding="utf-8")
        if _normalize(current) == _normalize(received_content):
            continue
        diff = _diff_html(received_content, current, rel_posix, rel_posix)
        sections.append(
            f"<h4 style='color:#94a3b8;margin:10px 0 4px;font-family:monospace;'>"
            f"πŸ“„ {rel_posix}</h4>" + diff
        )

    if not sections:
        return "<div style='color:#22c55e;padding:12px;'>No changes detected in workspace.</div>"

    return "".join(sections)


def _strip_comments_and_docstrings(code: str) -> str:
    """Remove comment-only lines and docstrings, keeping pure code."""
    import ast as _ast
    docstring_lines: set[int] = set()
    try:
        tree = _ast.parse(code)
        for node in _ast.walk(tree):
            if isinstance(node, (_ast.FunctionDef, _ast.AsyncFunctionDef,
                                  _ast.ClassDef, _ast.Module)):
                if (node.body
                        and isinstance(node.body[0], _ast.Expr)
                        and isinstance(node.body[0].value, _ast.Constant)
                        and isinstance(node.body[0].value.value, str)):
                    ds = node.body[0]
                    docstring_lines.update(range(ds.lineno, ds.end_lineno + 1))
    except Exception:
        pass
    result = []
    for i, line in enumerate(code.splitlines(), 1):
        if i in docstring_lines:
            continue
        if line.lstrip().startswith("#"):
            continue
        result.append(line)
    return "\n".join(result)


def _diff_html(a: str, b: str, from_label: str, to_label: str,
               strip_comments: bool = False) -> str:
    """Generate coloured unified-diff HTML between two code strings."""
    if strip_comments:
        a = _strip_comments_and_docstrings(a)
        b = _strip_comments_and_docstrings(b)
    a = _normalize(a)
    b = _normalize(b)
    a_lines = a.splitlines(keepends=True)
    b_lines = b.splitlines(keepends=True)
    diff = list(difflib.unified_diff(a_lines, b_lines,
                                     fromfile=from_label, tofile=to_label, lineterm=""))
    if not diff:
        return '<div class="diff-block" style="color:#22c55e;">No changes detected.</div>'

    html_lines = []
    for line in diff:
        escaped = line.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
        if line.startswith("+++") or line.startswith("---"):
            html_lines.append(f'<span style="color:#888;font-style:italic;">{escaped}</span><br>')
        elif line.startswith("@@"):
            html_lines.append(f'<span style="color:#60a5fa;">{escaped}</span><br>')
        elif line.startswith("+"):
            html_lines.append(f'<span style="color:#22c55e;background:#052e16;padding:2px 4px;">{escaped}</span><br>')
        elif line.startswith("-"):
            html_lines.append(f'<span style="color:#ef4444;background:#2d0a0a;padding:2px 4px;">{escaped}</span><br>')
        else:
            html_lines.append(f'<span style="color:#d4d4d4;">{escaped}</span><br>')

    return (
        '<div class="diff-block">'
        + "".join(html_lines)
        + "</div>"
    )


def _extract_function_source(code: str, func_name: str) -> str:
    """Extract a named function's source lines from code using ast."""
    import ast
    try:
        tree = ast.parse(code)
        for node in ast.walk(tree):
            if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
                if node.name == func_name:
                    lines = code.splitlines()
                    return "\n".join(lines[node.lineno - 1 : node.end_lineno])
    except Exception:
        pass
    return ""


def _apply_one_bug_fix(
    current_code: str,
    func_name: str,
    orig_pre: str,
    sabot_pre: str,
) -> str | None:
    """
    Apply the fix for a single injected bug by surgically patching func_name
    inside current_code.  Returns the patched file content, or None if the
    fix could not be determined.

    Strategy: character-level diff between orig_pre (correct pre-transform
    source) and sabot_pre (buggy pre-transform source) surfaces the exact
    changed tokens.  Those tokens survive obfuscation so we can
    find-and-replace them directly in the fully-obfuscated current_code.
    """
    import difflib

    func_in_code = _extract_function_source(current_code, func_name)
    if not func_in_code:
        return None

    matcher = difflib.SequenceMatcher(None, orig_pre, sabot_pre, autojunk=False)
    opcodes = matcher.get_opcodes()

    fixed_func = func_in_code
    changed = False

    for tag, i1, i2, j1, j2 in opcodes:
        if tag == "equal":
            continue

        orig_frag  = orig_pre[i1:i2]
        sabot_frag = sabot_pre[j1:j2]

        if not orig_frag.strip() and not sabot_frag.strip():
            continue

        if tag in ("replace", "insert"):
            if not sabot_frag.strip():
                continue

            ctx_start_orig  = i1
            ctx_start_sabot = j1
            while ctx_start_orig > 0 and ctx_start_sabot > 0:
                co  = orig_pre[ctx_start_orig - 1]
                cs_ = sabot_pre[ctx_start_sabot - 1]
                if co != cs_ or not (co.isalnum() or co == "_"):
                    break
                ctx_start_orig  -= 1
                ctx_start_sabot -= 1

            search_str  = sabot_pre[ctx_start_sabot:j2]
            replace_str = orig_pre[ctx_start_orig:i2]

            if search_str and search_str in fixed_func:
                fixed_func = fixed_func.replace(search_str, replace_str, 1)
                changed = True
            elif sabot_frag and sabot_frag in fixed_func:
                fixed_func = fixed_func.replace(sabot_frag, orig_frag, 1)
                changed = True

        elif tag == "delete":
            if not orig_frag.strip():
                continue

            ctx_left      = sabot_pre[max(0, j1 - 30):j1]
            ctx_right_raw = sabot_pre[j2:j2 + 20]
            nl            = ctx_right_raw.find("\n")
            ctx_right     = ctx_right_raw[:nl] if nl != -1 else ctx_right_raw

            for trim in range(len(ctx_left)):
                search_str  = ctx_left[trim:] + ctx_right
                replace_str = ctx_left[trim:] + orig_frag + ctx_right
                if search_str and search_str in fixed_func:
                    fixed_func = fixed_func.replace(search_str, replace_str, 1)
                    changed = True
                    break

    if not changed or fixed_func == func_in_code:
        return None

    fixed = current_code.replace(func_in_code, fixed_func, 1)
    return fixed if fixed != current_code else None


def _compute_expected_fixed_code(cs: "ChallengeState") -> str | None:
    """
    Compute the expected correct version of the sabotaged file by applying
    surgical fixes for every injected bug.  Supports num_bugs > 1 by
    iterating over all (func_name, orig_pre, sabot_pre) triples stored in
    challenge_state.json.
    
    IMPORTANT: After inflate_hierarchy, the sources are POST-INFLATE (include wrappers).
    This ensures surgical patching works correctly even when wrapper layers exist.
    
    Returns None if no fix could be determined.
    """
    import json as _json

    try:
        _data = _json.loads((cs.workspace / "challenge_state.json").read_text(encoding="utf-8"))
    except Exception:
        _data = {}

    # Multi-bug lists (written by the new pipeline). Fall back to single-bug
    # fields for workspaces generated before this change.
    # NOTE: These are POST-INFLATE sources (updated by inflate_hierarchy)
    bug_func_names      = _data.get("bug_func_names") or cs.bug_func_names
    sabot_sources_list  = _data.get("bug_func_sources_list") or []
    orig_sources_list   = _data.get("original_bug_func_sources_list") or []

    # Single-bug fallback: wrap scalar fields in lists
    if not bug_func_names and cs.bug_func_name:
        bug_func_names = [cs.bug_func_name]
    if not sabot_sources_list:
        sabot_sources_list = [_data.get("bug_func_source", "")]
    if not orig_sources_list:
        orig_sources_list = [
            cs.original_bug_func_source
            or _extract_function_source(cs.original_code, cs.bug_func_name)
        ]

    if not bug_func_names:
        return None

    # Use the snapshot as the starting point (matches what the student received).
    try:
        target_rel = cs.target_path.resolve().relative_to(cs.workspace.resolve()).as_posix()
    except ValueError:
        target_rel = ""
    current_code = cs.sabotaged_files.get(target_rel) or cs.sabotaged_code

    any_changed = False
    for func_name, orig_pre, sabot_pre in zip(bug_func_names, orig_sources_list, sabot_sources_list):
        if not (orig_pre and sabot_pre):
            continue
        result = _apply_one_bug_fix(current_code, func_name, orig_pre, sabot_pre)
        if result is not None:
            current_code = result
            any_changed = True

    return current_code if any_changed else None


def _expected_fix_diff_html(cs: "ChallengeState", submitted_code: str = "") -> str:
    """
    Show two sections:
    1. What the expected fix looks like (buggy β†’ expected).
    2. How the student's submission compares to the expected fix
       (expected β†’ submitted): empty if perfect, otherwise shows extra/wrong changes.
    """
    func = cs.bug_func_name

    # Resolve the received (snapshot) content for the target file
    try:
        target_rel = cs.target_path.resolve().relative_to(cs.workspace.resolve()).as_posix()
    except ValueError:
        target_rel = ""
    received_code = cs.sabotaged_files.get(target_rel) or cs.sabotaged_code

    expected_fixed = _compute_expected_fixed_code(cs)

    # ── Fallback: function-level or full-file diff ────────────────────────────
    if expected_fixed is None:
        approx = received_code
        for fn in cs.bug_func_names:
            sabot_func = _extract_function_source(approx, fn)
            orig_func  = _extract_function_source(cs.original_code, fn)
            if sabot_func and orig_func:
                candidate = approx.replace(sabot_func, orig_func, 1)
                if candidate != approx:
                    approx = candidate
        if approx != received_code:
            expected_fixed = approx
        else:
            return _diff_html(received_code, cs.original_code, target_rel, target_rel,
                              strip_comments=True)

    # ── Section 1: expected fix ───────────────────────────────────────────────
    section1 = (
        "<h4 style='color:#94a3b8;margin:8px 0 4px;'>🎯 Expected fix</h4>"
        + _diff_html(received_code, expected_fixed, target_rel, target_rel,
                     strip_comments=True)
    )

    if not submitted_code:
        return section1

    # ── Section 2: workspace-wide comparison ─────────────────────────────────
    # "Perfect fix" = target file matches expected AND no other files were changed.
    def _ast_equivalent(a: str, b: str) -> bool:
        try:
            import ast as _ast
            return _ast.dump(_ast.parse(a)) == _ast.dump(_ast.parse(b))
        except SyntaxError:
            return _normalize(a) == _normalize(b)

    target_file_ok = _ast_equivalent(expected_fixed, submitted_code)

    # Check whether the student touched any files outside the sabotaged set.
    # Known-modified files = snapshot keys + the challenge target file itself.
    known_changed = set(cs.sabotaged_files.keys()) | ({target_rel} if target_rel else set())
    import subprocess as _sp
    try:
        proc = _sp.run(
            ["git", "diff", "HEAD", "--name-only"],
            cwd=str(cs.workspace.resolve()), capture_output=True,
            text=True, encoding="utf-8", timeout=10,
        )
        extra_changed = [
            f.replace("\\", "/") for f in proc.stdout.splitlines()
            if f.replace("\\", "/") not in known_changed
        ]
    except Exception:
        extra_changed = []

    is_perfect = target_file_ok and not extra_changed

    if is_perfect:
        verdict = (
            "<div style='margin-top:12px;padding:10px 14px;background:#052e16;"
            "border:1px solid #22c55e;border-radius:6px;color:#22c55e;font-weight:600;'>"
            "βœ… Perfect fix β€” you changed exactly the right lines and nothing more."
            "</div>"
        )
    else:
        verdict = (
            "<div style='margin-top:12px;padding:10px 14px;background:#2d1a00;"
            "border:1px solid #f59e0b;border-radius:6px;color:#f59e0b;font-weight:600;'>"
            "⚠️ Your fix differs from the expected solution β€” see Your Changes on the left."
            "</div>"
        )

    return section1 + verdict


def _combined_changes_html(cs: "ChallengeState", submitted_code: str = "") -> str:
    """
    Render the "Changes & Expected" tab as a single HTML block.

    For each file in the union of (student-changed files βˆͺ expected-fix files),
    a row is rendered with two side-by-side diff panels:
      - Left:  student's diff (vs received sabotaged code)
      - Right: expected fix diff (vs received sabotaged code)
    If one side has no changes for a given file, a "No changes" placeholder is shown.
    A verdict banner spans the full width at the bottom.
    """
    import subprocess as _sp

    workspace = cs.workspace.resolve()
    try:
        target_rel = cs.target_path.resolve().relative_to(workspace).as_posix()
    except ValueError:
        target_rel = ""

    sabotaged_files = cs.sabotaged_files
    received_code   = sabotaged_files.get(target_rel) or cs.sabotaged_code

    # ── Collect student-changed files ─────────────────────────────────────────
    # student_changes: {rel_posix: (received_content, current_content)}
    student_changes: dict[str, tuple[str, str]] = {}

    for rel_posix, received_content in sabotaged_files.items():
        full_path = workspace / rel_posix
        if not full_path.exists():
            continue
        current = full_path.read_text(encoding="utf-8")
        if _normalize(current) != _normalize(received_content):
            student_changes[rel_posix] = (received_content, current)

    try:
        proc = _sp.run(
            ["git", "diff", "HEAD", "--name-only"],
            cwd=str(workspace), capture_output=True, text=True,
            encoding="utf-8", timeout=10,
        )
        for changed_rel in proc.stdout.splitlines():
            changed_posix = changed_rel.replace("\\", "/")
            if changed_posix in sabotaged_files:
                continue
            if not changed_rel.endswith(".py"):
                continue
            orig_proc = _sp.run(
                ["git", "show", f"HEAD:{changed_rel}"],
                cwd=str(workspace), capture_output=True, text=True,
                encoding="utf-8", timeout=10,
            )
            if orig_proc.returncode != 0:
                continue
            full_path = workspace / changed_rel
            if not full_path.exists():
                continue
            current = full_path.read_text(encoding="utf-8")
            if _normalize(current) != _normalize(orig_proc.stdout):
                student_changes[changed_posix] = (orig_proc.stdout, current)
    except Exception:
        pass

    # ── Compute expected fix for target file ──────────────────────────────────
    expected_fixed = _compute_expected_fixed_code(cs)
    if expected_fixed is None and cs.bug_func_name:
        sabot_func = _extract_function_source(received_code, cs.bug_func_name)
        orig_func  = _extract_function_source(cs.original_code, cs.bug_func_name)
        if sabot_func and orig_func:
            ef = received_code.replace(sabot_func, orig_func, 1)
            if ef != received_code:
                expected_fixed = ef

    # ── Build union of files to show ──────────────────────────────────────────
    expected_files = {target_rel} if (target_rel and expected_fixed is not None) else set()
    all_files = sorted(set(student_changes.keys()) | expected_files)

    # ── Column header row ─────────────────────────────────────────────────────
    col_headers = (
        "<div style='display:flex;gap:12px;margin-bottom:8px;'>"
        "<div style='flex:1;min-width:0;font-weight:600;color:#cbd5e1;'>✏️ Your Changes"
        " <span style='font-weight:400;color:#64748b;font-size:0.88em;'>"
        "β€” your submitted code vs the buggy code you received</span></div>"
        "<div style='flex:1;min-width:0;font-weight:600;color:#cbd5e1;'>🎯 Expected Fix"
        " <span style='font-weight:400;color:#64748b;font-size:0.88em;'>"
        "β€” the minimal correct fix</span></div>"
        "</div>"
    )

    if not all_files:
        return col_headers + "<div class='diff-block' style='color:#22c55e;'>No changes detected in workspace.</div>"

    _no_change_left  = "<div class='diff-block' style='color:#22c55e;'>No changes</div>"
    _no_change_right = "<div class='diff-block' style='color:#64748b;'>No change expected</div>"

    # ── Per-file side-by-side rows ────────────────────────────────────────────
    rows: list[str] = []
    for rel in all_files:
        file_header = (
            f"<h4 style='color:#94a3b8;margin:6px 0 4px;font-family:monospace;'>πŸ“„ {rel}</h4>"
        )

        # Left: student's changes
        if rel in student_changes:
            recv, curr = student_changes[rel]
            left_body = _diff_html(recv, curr, rel, rel)
        else:
            left_body = _no_change_left

        # Right: expected fix (only for the sabotaged target file)
        if rel == target_rel and expected_fixed is not None:
            right_body = _diff_html(received_code, expected_fixed, rel, rel)
        else:
            right_body = _no_change_right

        rows.append(
            "<div style='display:flex;gap:12px;margin-bottom:20px;'>"
            f"<div style='flex:1;min-width:0;'>{file_header}{left_body}</div>"
            f"<div style='flex:1;min-width:0;'>{file_header}{right_body}</div>"
            "</div>"
        )

    # ── Verdict banner (full-width) ───────────────────────────────────────────
    verdict = ""
    if submitted_code:
        def _ast_eq(a: str, b: str) -> bool:
            try:
                import ast as _ast
                return _ast.dump(_ast.parse(a)) == _ast.dump(_ast.parse(b))
            except SyntaxError:
                return _normalize(a) == _normalize(b)

        target_ok    = expected_fixed is not None and _ast_eq(expected_fixed, submitted_code)
        extra_files  = [f for f in student_changes if f != target_rel]
        is_perfect   = target_ok and not extra_files

        if is_perfect:
            verdict = (
                "<div style='margin-top:12px;padding:10px 14px;background:#052e16;"
                "border:1px solid #22c55e;border-radius:6px;color:#22c55e;font-weight:600;'>"
                "βœ… Perfect fix β€” you changed exactly the right lines and nothing more."
                "</div>"
            )
        else:
            verdict = (
                "<div style='margin-top:12px;padding:10px 14px;background:#2d1a00;"
                "border:1px solid #f59e0b;border-radius:6px;color:#f59e0b;font-weight:600;'>"
                "⚠️ Your fix differs from the expected solution."
                "</div>"
            )

    return col_headers + "".join(rows) + verdict


def _hints_html(hint_log: list) -> str:
    """Render hint log with the student's actual question and the assistant response."""

    def _esc(s: str) -> str:
        return (s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"))

    entries = [e for e in (hint_log or []) if isinstance(e, dict)]

    if not entries:
        return "<p style='color:#888;font-style:italic;'>No hints were used.</p>"

    parts: list[str] = []
    for n, entry in enumerate(entries, 1):
        question = entry.get("question", "").strip() or entry.get("summary", "").strip()
        response = entry.get("response", "").strip()
        hint_summary = entry.get("hint_summary", "").strip()
        if not question:
            first_line = response.split("\n")[0].strip()
            dot = first_line.find(". ")
            question = first_line[: dot + 1] if dot != -1 else first_line
        parts.append(
            f'<div style="margin:6px 0;padding:8px 14px;border:1px solid #374151;'
            f'border-radius:8px;background:#1a2e1a;">'
            f'<span style="color:#93c5fd;font-weight:bold;margin-right:10px;">Hint #{n}</span>'
            f'<div style="color:#86efac;margin-top:6px;"><strong>Question:</strong> {_esc(question)}</div>'
            f'<div style="color:#d1d5db;margin-top:6px;white-space:pre-wrap;"><strong>Answer:</strong> {_esc(response)}</div>'
            + (f'<div style="color:#94a3b8;margin-top:6px;font-size:0.9em;"><strong>Internal hint summary:</strong> {_esc(hint_summary)}</div>' if hint_summary else '') +
            f'</div>'
        )

    header = (f'<p style="color:#888;font-size:0.85em;margin:0 0 8px 0;">'
              f'{len(entries)} hint(s) used</p>')
    return (
        header
        + '<div style="max-height:50vh;overflow-y:auto;padding:4px;">'
        + "".join(parts)
        + "</div>"
    )


def _score_summary_html(result: dict) -> str:
    """Build a prominent score summary block."""
    total       = result["total_score"]
    llm_score   = result.get("llm_score", total)
    explanation = result.get("llm_explanation", "")
    penalty     = result["hint_penalty"]
    passed      = result["passed"]
    ttl         = result["total_tests"]
    all_ok      = result["all_passed"]

    color = "#22c55e" if all_ok else ("#f59e0b" if total >= 50 else "#ef4444")
    badge = "πŸŽ‰ ALL TESTS PASS!" if all_ok else ("⚠️ Partial" if total > 0 else "❌ Failed")

    explanation_html = ""
    if explanation:
        import html as _html
        escaped = _html.escape(explanation)
        explanation_html = (
            f'<div style="margin-top:14px;padding:10px 14px;background:#0f172a;'
            f'border-left:3px solid #60a5fa;border-radius:4px;color:#cbd5e1;'
            f'font-size:0.9em;line-height:1.5;">'
            f'<strong style="color:#60a5fa;">πŸ€– AI Evaluation:</strong><br>{escaped}</div>'
        )

    return f"""
<div style="padding:20px;border-radius:12px;background:#1e1e1e;border:2px solid {color};">
  <div style="font-size:2.5em;font-weight:bold;color:{color};text-align:center;">{total}/100</div>
  <div style="text-align:center;color:{color};font-size:1.1em;margin-bottom:16px;">{badge}</div>
  <table style="width:100%;border-collapse:collapse;font-family:monospace;">
    <tr>
      <td style="padding:6px 12px;color:#d4d4d4;">πŸ€– AI Score</td>
      <td style="padding:6px 12px;color:#60a5fa;text-align:right;font-weight:bold;">{llm_score}/100</td>
      <td style="padding:6px 12px;color:#888;">({passed}/{ttl} tests passed)</td>
    </tr>
    <tr>
      <td style="padding:6px 12px;color:#d4d4d4;">πŸ’‘ Hint Penalty</td>
      <td style="padding:6px 12px;color:#f87171;text-align:right;font-weight:bold;">βˆ’{penalty}</td>
      <td style="padding:6px 12px;color:#888;"></td>
    </tr>
  </table>
  {explanation_html}
</div>
"""


def _submission_outcome(result: dict) -> str:
    if not result.get("touched_bug_function", True):
        return "wrong_location" if result.get("changed_function_names") else "no_attempt"
    if result.get("all_passed"):
        return "full_fix"
    before_passed = result.get("before_passed", 0)
    after_passed = result.get("passed", 0)
    if after_passed > before_passed:
        return "partial_fix"
    if after_passed < before_passed:
        return "regression"
    return "attempted_no_improvement"


def _build_submission_record(
    cs: "ChallengeState",
    student_name: str,
    submitted_code: str,
    result: dict,
    hints_used: int,
    chat_log: list,
    hint_log: list,
    attempt_number: int,
    debug_logs: str,
    enable_cloud_uploads: bool,
    identity: dict | None = None,
) -> dict:
    timestamp = datetime.now()
    submission_id = timestamp.strftime("%Y%m%d_%H%M%S_%f")
    expected_fixed_code = _compute_expected_fixed_code(cs) or cs.original_code
    challenge_id = f"{cs.workspace.name}:{cs.target_file}:{cs.function_name or 'unknown'}"
    student_name = (student_name or "Anonymous").strip() or "Anonymous"
    outcome = _submission_outcome(result)

    cloud_caps = _cloud_upload_capabilities()
    google_status = "pending" if enable_cloud_uploads and cloud_caps["google_sheets"]["available"] and cloud_caps["google_sheets"]["configured"] else "disabled"
    supabase_status = "pending" if enable_cloud_uploads and cloud_caps["supabase"]["available"] and cloud_caps["supabase"]["configured"] else "disabled"
    google_error = "" if google_status == "pending" else str(cloud_caps["google_sheets"]["reason"])
    supabase_error = "" if supabase_status == "pending" else str(cloud_caps["supabase"]["reason"])

    return {
        "submission_id": submission_id,
        "timestamp": timestamp.isoformat(),
        "student": {
            "name": student_name,
            "email": "",
            "auth_provider": (identity or {}).get("provider", ""),
            "provider_user_id": (identity or {}).get("provider_user_id", ""),
            "profile_url": (identity or {}).get("profile_url", ""),
        },
        "challenge": {
            "challenge_id": challenge_id,
            "created_at": cs.challenge_created_at,
            "challenge_summary": cs.challenge_summary,
            "workspace_name": cs.workspace.name,
            "workspace_path": str(cs.workspace),
            "repo_url": cs.github_url,
            "target_file": cs.target_file,
            "function_name": cs.function_name,
            "bug_func_name": cs.bug_func_name,
            "bug_func_names": cs.bug_func_names,
            "bug_description": cs.bug_description,
            "difficulty_level": cs.nesting_level,
            "refactoring_enabled": cs.refactoring_enabled,
            "debug_mode": cs.debug_mode,
            "challenge_prompt": cs.readme(),
            "original_code": cs.original_code,
            "buggy_code": cs.sabotaged_code,
            "expected_fixed_code": expected_fixed_code,
            "public_tests": cs.public_tests,
            "secret_tests": cs.secret_tests,
        },
        "submission": {
            "attempt_number": attempt_number,
            "hints_used": hints_used,
            "chat_history": chat_log or [],
            "hint_history": hint_log or [],
            "student_code": submitted_code,
            "student_diff": _plain_diff_text(
                cs.sabotaged_code,
                submitted_code,
                f"received/{cs.target_file}",
                f"student/{cs.target_file}",
            ),
            "changed_function_names": result.get("changed_function_names", []),
            "changed_functions": result.get("changed_functions", []),
            "bug_function_names": result.get("bug_function_names", []),
            "touched_bug_function": result.get("touched_bug_function", False),
        },
        "tests": {
            "before_passed": result.get("before_passed", 0),
            "before_total": result.get("before_total", 0),
            "public_passed": result.get("public_passed", 0),
            "public_total": result.get("public_total", 0),
            "secret_passed": result.get("secret_passed", 0),
            "secret_total": result.get("secret_total", 0),
            "passed_tests": result.get("passed", 0),
            "total_tests": result.get("total_tests", 0),
            "all_passed": result.get("all_passed", False),
            "per_test_before": result.get("per_test_before", []),
            "per_test_after": result.get("per_test_after", []),
            "public_output": result.get("public_output", ""),
            "secret_output": result.get("secret_output", ""),
            "test_output": result.get("test_output", ""),
        },
        "scoring": {
            "llm_score": result.get("llm_score", result.get("total_score", 0)),
            "llm_explanation": result.get("llm_explanation", ""),
            "hint_penalty": result.get("hint_penalty", 0),
            "total_score": result.get("total_score", 0),
            "test_score": result.get("test_score", 0),
            "correct_location": result.get("correct_location", False),
            "submission_outcome": outcome,
        },
        "system": {
            "llm_provider": os.getenv("LLM_PROVIDER", ""),
            "llm_model": os.getenv("LLM_MODEL", ""),
            "agent_model": os.getenv("AGENT_MODEL", ""),
        },
        "cloud": {
            "google_sheets": {"status": google_status, "error": google_error},
            "supabase": {"status": supabase_status, "error": supabase_error},
        },
        "debug": {
            "captured_logs": debug_logs,
        },
    }


# ── Full two-page interface ───────────────────────────────────────────────────

def create_full_interface() -> gr.Blocks:
    """
    Returns a Gradio app with login page (if needed) + challenge interface:
      Page 0: Login (visible only if OPENAI_API_KEY not in .env)
      Page 1: Setup form (name / URL / level / bugs)
      Page 2: Challenge interface (shown after pipeline finishes)
      Page 3: Results (shown after Submit)
    """
    
    # Spaces require an identity even when a server-side model key is configured.
    has_env_key = bool(_configured_llm_api_key())

    css = """
    #code-editor {
        font-size: 14px !important;
        font-family: 'Consolas', 'Monaco', 'Courier New', monospace !important;
        background-color: #1e1e1e !important;
        border-radius: 8px !important;
    }
    #code-editor .codemirror-wrapper {
        background-color: #1e1e1e !important;
    }
    #code-editor .cm-editor {
        background-color: #1e1e1e !important;
    }
    
    .setup-card {
        max-width: 800px;
        margin: 40px auto;
        padding: 30px;
    }
    """

    # Note: CSS parameter moved to launch() in Gradio 6.0, removed for compatibility
    with gr.Blocks(title="Legacy Code Challenge") as demo:

        # Shared state
        user_api_key_state        = gr.State("")
        user_name_state           = gr.State("")
        workspace_state           = gr.State("")
        hints_used_state          = gr.State(0)
        submission_count_state    = gr.State(0)
        chat_log_state            = gr.State([])
        hint_log_state            = gr.State([])
        confirmation_pending_state = gr.State(False)
        timer_trigger             = gr.Number(value=0, visible=False)
        
        # Account action, shown only after login.
        with gr.Row(visible=False, elem_id="logout-row") as logout_row:
            logout_btn = gr.Button("Log out", variant="secondary", elem_id="logout-btn", size="sm")

        # ════════════════════════════════════════════════════════════════════
        # PAGE 0 β€” Login (visible only if no .env key)
        # ════════════════════════════════════════════════════════════════════
        with gr.Column(visible=not has_env_key or HF_OAUTH_REQUIRED, elem_classes=["setup-card"]) as login_page:
            gr.Markdown(
                "# πŸ” Welcome to Legacy Code Challenge\n"
                "### Please enter your details to continue"
            )

            if HF_OAUTH_REQUIRED:
                gr.LoginButton(elem_id="huggingface-login")
            
            login_name = gr.Textbox(
                label="Your Name",
                placeholder="e.g. Alice Smith",
                elem_id="login-name",
                interactive=not HF_OAUTH_REQUIRED,
            )
            
            login_api_key = gr.Textbox(
                label="OpenAI API Key",
                placeholder="sk-proj-...",
                type="password",
                info="Get one at platform.openai.com/api-keys",
                elem_id="login-api-key",
                visible=not has_env_key,
            )

            if has_env_key:
                gr.Markdown("The app's configured model key will be used.")
            
            gr.Markdown(
                "⚠️ **Note:** Your API key is only used for this session and consumes credits from your OpenAI account."
            )
            
            login_btn = gr.Button("πŸš€ Continue", variant="primary", size="lg")
            login_status = gr.Markdown("")

        # ════════════════════════════════════════════════════════════════════
        # PAGE 1 β€” Setup (visible if .env exists, else hidden)
        # ════════════════════════════════════════════════════════════════════
        with gr.Column(visible=has_env_key and not HF_OAUTH_REQUIRED, elem_classes=["setup-card"]) as setup_page:
            gr.Markdown(
                "# πŸ› Legacy Code Challenge\n"
                "Fill in the details below, then click **Start Challenge**."
            )

            name_box = gr.Textbox(
                label="Your Name",
                placeholder="e.g. Alice Smith",
            )
            url_box = gr.Textbox(
                label="GitHub Repository URL",
                placeholder="https://github.com/mahmoud/boltons",
            )
            with gr.Row():
                nesting_slider = gr.Slider(
                    minimum=1, maximum=6, value=3, step=1,
                    label="πŸ”— Nesting Level (call-chain depth)",
                    info="Higher = deeper call chains (1=simple, 6=very deep)",
                )
                bugs_slider = gr.Slider(
                    minimum=1, maximum=5, value=1, step=1,
                    label="πŸ› Number of Bugs to Inject",
                )
            with gr.Row():
                refactoring_check = gr.Checkbox(
                    label="πŸ”€ Enable Refactoring (obfuscation/spaghettification)",
                    value=False,
                )
                debug_check = gr.Checkbox(
                    label="🐞 Debug Mode (verbose output, show bug locations)",
                    value=False,
                )
            timer_slider = gr.Slider(
                minimum=0, maximum=120, value=0, step=5,
                label="⏱️ Challenge Timer (minutes β€” 0 = no timer)",
            )

            start_btn  = gr.Button("πŸš€ Start Challenge", variant="primary", size="lg")
            status_box = gr.Textbox(
                label="Status",
                interactive=False,
                visible=False,
                lines=3,
            )

        # ════════════════════════════════════════════════════════════════════
        # PAGE 2 β€” Challenge (hidden until pipeline finishes)
        # ════════════════════════════════════════════════════════════════════
        with gr.Column(visible=False) as challenge_page:

            with gr.Row(elem_classes=["header-row"]):
                header_md  = gr.Markdown("### πŸ› Legacy Code Challenge")
                timer_html = gr.HTML('<span id="timer-inner" style="font-family:monospace"></span>', elem_id="challenge-timer")

            with gr.Row(elem_classes=["main-row"]):

                # ── Left column: tabs ─────────────────────────────────────
                with gr.Column(scale=3, elem_classes=["left-col"]):
                    with gr.Tabs(selected=0, elem_classes=["left-tabs"]) as left_tabs:

                        with gr.Tab("πŸ“‹ Challenge", id=0):
                            challenge_readme = gr.Markdown("")

                        with gr.Tab("πŸ’» Code Editor", id=1):
                            file_dropdown = gr.Dropdown(
                                choices=[],
                                label="File",
                                info="Select a file to view. Submit saves to the target file.",
                            )
                            with gr.Row():
                                btn_tests   = gr.Button("β–Ά Run Tests",        variant="secondary")
                                btn_changes = gr.Button("πŸ‘οΈ View My Changes", variant="secondary")
                                save_btn    = gr.Button("πŸ’Ύ Save",             variant="secondary", elem_id="save-btn")
                            save_status = gr.Markdown("")
                            code_editor = gr.Code(
                                value="",
                                language="python",
                                label="",
                                interactive=True,
                                lines=30,
                                elem_id="code-editor",
                                show_label=False,
                            )

                        with gr.Tab("πŸ§ͺ Test Results", id=2):
                            run_tests_tab_btn = gr.Button("β–Ά Run Tests", variant="secondary")
                            test_output = gr.HTML(
                                "<p style='color:#888;font-family:monospace;'>Click 'β–Ά Run Tests' to run…</p>"
                            )

                        with gr.Tab("πŸ‘οΈ My Changes", id=3):
                            gr.Markdown("_Diff: your saved file vs the original buggy code you received_")
                            with gr.Row():
                                refresh_btn = gr.Button("πŸ”„ Refresh", variant="secondary")
                                revert_btn  = gr.Button("↩️ Revert to Original", variant="secondary")
                            changes_diff_html = gr.HTML("")

                # ── Right column: AI assistant + submit ───────────────────
                with gr.Column(scale=2, elem_classes=["right-col"]):
                    hint_counter = gr.Markdown(_hint_md(0, 0))
                    chatbot = gr.Chatbot(
                        label="AI Assistant",
                        elem_id="ai-chatbot",
                    )
                    with gr.Row():
                        chat_input = gr.Textbox(
                            placeholder="Ask the AI assistant for a hint…",
                            show_label=False,
                            scale=5,
                        )
                        send_btn = gr.Button("Send", variant="secondary", scale=1)

                    gr.Markdown("---")
                    submit_btn = gr.Button("πŸš€ Submit Fix", variant="primary")
            
            # Live Debug Console (always visible at bottom)
            gr.Markdown("---")
            with gr.Accordion("πŸ› Live Debug Console", open=False):
                live_debug_console = gr.Textbox(
                    label="Real-time Execution Logs",
                    lines=10,
                    max_lines=20,
                    interactive=False,
                    placeholder="Debug logs will appear here during submission...",
                    elem_id="live-debug-console"
                )
            
            # Hidden trigger for submit (ensures at least 1 UI input)
            submit_trigger = gr.Number(value=0, visible=False)

        # ════════════════════════════════════════════════════════════════════
        # PAGE 3 β€” Results (hidden until Submit clicked)
        # ════════════════════════════════════════════════════════════════════
        with gr.Column(visible=False) as results_page:
            gr.Markdown("## πŸ“Š Submission Results")

            score_summary_html = gr.HTML("")

            # Use Accordions instead of nested Tabs (more stable for dynamic updates)
            with gr.Accordion("πŸ§ͺ Test Results", open=True):
                results_test_html = gr.HTML("")

            with gr.Accordion("πŸ” Changes & Expected", open=False):
                results_changes_html = gr.HTML("")

            with gr.Accordion("οΏ½ Hints Used", open=False):
                results_hints_html = gr.HTML("")
            
            # Debug console (collapsible)
            with gr.Accordion("πŸ› Debug Console", open=False):
                debug_console = gr.Textbox(
                    label="Execution Logs",
                    lines=15,
                    max_lines=30,
                    interactive=False,
                    placeholder="Debug logs will appear here...",
                )

        # ── Login callback ────────────────────────────────────────────────
        
        def on_oauth_profile(profile: gr.OAuthProfile | None):
            identity = _hf_oauth_identity(profile)
            if identity is None:
                return gr.update(), gr.update()
            return (
                gr.update(value=identity["display_name"]),
                f"Signed in to Hugging Face as **@{identity['provider_user_id']}**.",
            )

        def on_login(name, api_key, profile: gr.OAuthProfile | None = None):
            identity = _hf_oauth_identity(profile)
            if _hf_auth_required(profile):
                return (
                    gr.update(), gr.update(), gr.update(), gr.update(),
                    "❌ Sign in with Hugging Face before continuing.", "", "",
                )

            name = identity["display_name"] if identity else (name or "").strip()
            if not name:
                return (
                    gr.update(),  # login page stays
                    gr.update(),  # setup page hidden
                    gr.update(),  # logout row remains hidden
                    gr.update(),  # keep setup name as-is
                    "❌ Please enter your name",
                    "", ""  # states empty
                )
            
            submitted_api_key = (api_key or "").strip()
            api_key_for_validation = submitted_api_key or _configured_llm_api_key()
            if not api_key_for_validation:
                return (
                    gr.update(), gr.update(), gr.update(), gr.update(),
                    "❌ Enter an API key to continue.", "", "",
                )

            valid, msg = validate_openai_key(api_key_for_validation)
            if not valid:
                return (
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    msg,
                    "", ""
                )
            
            # Success!
            return (
                gr.update(visible=False),  # hide login
                gr.update(visible=True),   # show setup
                gr.update(visible=True),   # show logout row
                gr.update(value=name),  # prefill setup page name
                "βœ… Logged in!",
                submitted_api_key,
                name,
            )
        
        def on_logout():
            """Clear session values and return to the login page."""
            return (
                gr.update(visible=not has_env_key or HF_OAUTH_REQUIRED),  # show login
                gr.update(visible=has_env_key and not HF_OAUTH_REQUIRED),  # hide setup
                gr.update(visible=False),  # hide challenge
                gr.update(visible=False),  # hide results
                gr.update(visible=False),  # hide logout row
                "", "", "", "",  # clear textboxes
                "", ""  # clear states
            )

        # ── Setup callback ─────────────────────────────────────────────────

        def on_start(name, url, nesting_lvl, num_bugs, refactoring, debug, timer_mins, user_name_from_login, user_api_key, profile: gr.OAuthProfile | None = None):
            if _hf_auth_required(profile):
                yield (
                    gr.update(visible=True, value="❌ Sign in with Hugging Face before starting a challenge."),
                    gr.update(interactive=True),
                    gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
                )
                return

            logger.info(f"=== START CHALLENGE ===")
            logger.info(f"User: {user_name_from_login or name}")
            logger.info(f"URL: {url}")
            logger.info(f"Nesting: {nesting_lvl}, Bugs: {num_bugs}, Refactoring: {refactoring}, Debug: {debug}")
            
            nesting = int(nesting_lvl)
            
            # Use login name if available, otherwise name from setup form
            name_str = user_name_from_login.strip() if user_name_from_login else name.strip()
            
            if not user_api_key and not _configured_llm_api_key():
                logger.warning("No user_api_key provided!")

            logger.info("Yielding loading message...")
            yield (
                gr.update(visible=True,
                          value="⏳ Cloning repository and generating challenge…"
                                " this may take 1–2 minutes."),
                gr.update(interactive=False),
                gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
            )

            try:
                logger.info(f"Starting pipeline for {url.strip()}")
                with llm_api_key_context(user_api_key or None):
                    workspace_path = _run_pipeline(url.strip(), nesting, int(num_bugs), refactoring, debug)
                logger.info(f"Pipeline completed. Workspace: {workspace_path}")
                
                cs       = ChallengeState(workspace_path)
                py_files = cs.list_py_files()
                default  = cs.target_file if cs.target_file in py_files else (py_files[0] if py_files else "")
                suffix   = f" &nbsp;|&nbsp; {name_str}" if name_str else ""

                logger.info(f"Challenge ready! Target file: {cs.target_file}, {len(py_files)} Python files")
                
                yield (
                    gr.update(visible=False),
                    gr.update(interactive=True),
                    gr.update(visible=False),
                    gr.update(visible=True),
                    gr.update(value=f"### πŸ› Legacy Code Challenge{suffix}"),
                    gr.update(value=cs.readme()),
                    gr.update(choices=py_files, value=default),
                    gr.update(value=cs.read_target(), label=cs.target_file, interactive=True),
                    workspace_path,
                    int(timer_mins),
                )

            except Exception as exc:
                logger.error(f"Pipeline failed: {exc}", exc_info=True)
                error_msg = str(exc)
                
                # Provide user-friendly error messages
                if "verify_sabotage" in error_msg and "crashed" in error_msg:
                    user_message = (
                        "❌ Challenge generation failed: The bugs introduced caused all tests to crash.\n\n"
                        "πŸ’‘ **Suggestions:**\n"
                        "β€’ Try reducing the number of bugs (use 1-2 instead of 3)\n"
                        "β€’ Try a different repository with simpler code\n"
                        "β€’ Enable 'Debug Mode' to see detailed logs\n\n"
                        f"Technical details: {error_msg}"
                    )
                elif "clone" in error_msg.lower():
                    user_message = (
                        "❌ Failed to clone repository.\n\n"
                        "πŸ’‘ **Check:**\n"
                        "β€’ Is the URL correct?\n"
                        "β€’ Is the repository public?\n\n"
                        f"Details: {error_msg}"
                    )
                else:
                    user_message = f"❌ Error: {error_msg}\n\nπŸ’‘ Try enabling 'Debug Mode' for more details."
                
                yield (
                    gr.update(visible=True, value=user_message),
                    gr.update(interactive=True),
                    gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
                )

        # ── Wiring for login ──────────────────────────────────────────────

        demo.load(
            on_oauth_profile,
            inputs=None,
            outputs=[login_name, login_status],
        )
        
        login_btn.click(
            on_login,
            inputs=[login_name, login_api_key],
            outputs=[
                login_page, setup_page, logout_row,
                name_box,
                login_status,
                user_api_key_state, user_name_state
            ]
        )
        
        logout_btn.click(
            on_logout,
            outputs=[
                login_page, setup_page, challenge_page, results_page, logout_row,
                login_name, login_api_key, name_box, url_box,
                user_api_key_state, user_name_state
            ]
        )
        
        start_btn.click(
            on_start,
            inputs=[name_box, url_box, nesting_slider, bugs_slider, refactoring_check, debug_check, timer_slider, user_name_state, user_api_key_state],
            outputs=[
                status_box, start_btn,
                setup_page, challenge_page,
                header_md, challenge_readme,
                file_dropdown, code_editor,
                workspace_state, timer_trigger,
            ],
        )

        timer_trigger.change(
            fn=None, inputs=[timer_trigger],
            js="(n) => { window.startTimer && window.startTimer(n); return n; }",
            outputs=[timer_trigger],
        )

        # ── Challenge callbacks ────────────────────────────────────────────

        def on_file_select(rel_path, workspace_path):
            if not workspace_path:
                return gr.update()
            cs = ChallengeState(workspace_path)
            content = cs.read_py_file(rel_path)
            return gr.update(value=content, interactive=True, label=rel_path)

        def on_save(code, rel_path, workspace_path):
            if not workspace_path:
                return "⚠️ No challenge loaded."
            cs = ChallengeState(workspace_path)
            if rel_path:
                cs.write_py_file(rel_path, code)
            else:
                cs.write_target(code)
            return "βœ… Saved"

        def on_run_tests(code, rel_path, workspace_path):
            loading = '<p style="text-align:center;padding:20px;color:#888;">⏳ Running tests…</p>'
            yield (gr.update(selected=2), loading)
            if not workspace_path:
                yield (gr.update(selected=2), "<p style='color:#888'>No challenge loaded.</p>")
                return
            # Auto-save before running tests
            cs_temp = ChallengeState(workspace_path)
            if rel_path:
                cs_temp.write_py_file(rel_path, code)
            else:
                cs_temp.write_target(code)
            try:
                from orchestrator.scoring import run_tests
                r   = run_tests(workspace_path)
                raw = r["output"] if r["output"] else "No output."
                yield (gr.update(selected=2), _colorise_test_output(raw))
            except Exception as exc:
                yield (gr.update(selected=2), f"<p style='color:#ef4444;font-family:monospace;'>❌ Error: {exc}</p>")

        def on_show_changes(code, rel_path, workspace_path):
            if not workspace_path:
                diff = "<p style='color:#888'>No challenge loaded.</p>"
            else:
                try:
                    # Save code from editor, then read from disk for comparison
                    # (Gradio code_editor doesn't always pass updated content reliably)
                    cs = ChallengeState(workspace_path)
                    if rel_path:
                        cs.write_py_file(rel_path, code)
                    else:
                        cs.write_target(code)
                    diff = _workspace_diff_html(cs)
                except Exception as e:
                    diff = f"<p style='color:#ef4444;'>Error generating diff: {str(e)[:200]}</p>"
            return (gr.update(selected=3), diff)

        def on_revert(workspace_path):
            if not workspace_path:
                return gr.update(), gr.update(selected=1)
            cs = ChallengeState(workspace_path)
            cs.reset_target()
            return cs.sabotaged_code, gr.update(selected=1)

        def on_submit(trigger, hints_used, submit_count, workspace_path, chat_log, hint_log, user_name, code, rel_path, user_api_key, profile: gr.OAuthProfile | None = None):
            if _hf_auth_required(profile):
                message = "❌ Sign in with Hugging Face before submitting."
                yield (
                    gr.update(visible=True), gr.update(visible=False), message,
                    "", "", "", submit_count, "", message,
                )
                return

            logger.info(f"=== SUBMIT CHALLENGE ===")
            logger.info(f"Trigger: {trigger}, User: {user_name}, Hints: {hints_used}, Submit#: {submit_count}")
            logger.info(f"Workspace: {workspace_path}")
            
            # First yield IMMEDIATELY: Hide challenge, show results with loading
            _loading = '<p style="text-align:center;padding:40px;color:#888;font-size:1.2em;">⏳ Running tests…</p>'
            yield (
                gr.update(visible=False),  # Hide challenge page
                gr.update(visible=True),   # Show results page
                _loading, "", "", "",  # Show loading message in results area
                submit_count,
                "",  # debug console
                "Starting submission evaluation...",  # live debug
            )
            
            # Capture all print statements for debug console
            log_capture = StringIO()
            original_stdout = sys.stdout
            
            try:
                sys.stdout = log_capture
                
                if not workspace_path:
                    sys.stdout = original_stdout
                    yield (gr.update(visible=False), gr.update(visible=True), "No challenge loaded.", "", "", "", submit_count, log_capture.getvalue(), "❌ No workspace loaded")
                    return
                
                print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸš€ Starting submission evaluation...")
                cs  = ChallengeState(workspace_path)
                log = SubmissionLog(cs.workspace)
                if rel_path:
                    cs.write_py_file(rel_path, code)
                
                print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸ“– Reading submitted code...")
                submitted_code = cs.read_target()
                
                print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸ§ͺ Running tests...")
                with llm_api_key_context(user_api_key or None):
                    result = evaluate_submission(
                        workspace_path=workspace_path,
                        student_code=submitted_code,
                        original_code=cs.original_code,
                        bug_func_name=cs.bug_func_name,
                        hints_used=hints_used,
                        sabotaged_code=cs.sabotaged_code,
                        target_file=str(cs.target_path),
                        bug_func_names=cs.bug_func_names,
                    )
                
                new_count = submit_count + 1

                print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸ“Š Generating results...")
                score_html     = _score_summary_html(result)
                combined_diff  = _combined_changes_html(cs, submitted_code)
                test_html      = _colorise_test_output(result["test_output"] or "No test output.")
                hints_html     = _hints_html(hint_log or [])

                print(f"[{datetime.now().strftime('%H:%M:%S')}] βœ… Results ready, returning to user...")
                
                # Get all captured logs
                debug_logs = log_capture.getvalue()
                print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸ’Ύ Saving submission...")
                submission_record = _build_submission_record(
                    cs=cs,
                    student_name=user_name,
                    submitted_code=submitted_code,
                    result=result,
                    hints_used=hints_used,
                    chat_log=chat_log or [],
                    hint_log=hint_log or [],
                    attempt_number=new_count,
                    debug_logs=debug_logs,
                    enable_cloud_uploads=True,
                    identity=_hf_oauth_identity(profile),
                )
                log_path = log.save(submission_record)
                supabase_result = _save_submission_to_supabase(log, log_path, submission_record)
                if supabase_result["status"] != "success":
                    debug_logs += f"\n\nSupabase storage {supabase_result['status']}: {supabase_result['error']}"
                    log.update(log_path, {"debug": {"captured_logs": debug_logs}})
                sys.stdout = original_stdout  # Restore stdout
                
                # Return results to user IMMEDIATELY
                yield (
                    gr.update(visible=False),  # Hide challenge page
                    gr.update(visible=True),   # Show results page
                    score_html, combined_diff, test_html, hints_html,
                    new_count,
                    debug_logs,
                    debug_logs,  # live debug (same)
                )
                
                # Google Sheets remains an optional summary destination.
                def _background_upload():
                    student_name = user_name.strip() if user_name else "Anonymous"
                    cloud_updates = {}
                    cloud_caps = _cloud_upload_capabilities()
                    logger.info(
                        "Cloud upload capabilities: google available=%s configured=%s, Supabase status=%s",
                        cloud_caps["google_sheets"]["available"],
                        cloud_caps["google_sheets"]["configured"],
                        supabase_result["status"],
                    )
                    
                    # Google Sheets (fast summary)
                    if cloud_caps["google_sheets"]["available"] and cloud_caps["google_sheets"]["configured"]:
                        try:
                            print("πŸ“Š Uploading to Google Sheets...")
                            sheets_ok = log_to_google_sheets(
                                student_name=student_name,
                                repo_url=cs.github_url,
                                hints_used=hints_used,
                                score=result["total_score"],
                                total_tests=result["total_tests"],
                                passed_tests=result["passed"],
                                all_passed=result["all_passed"],
                                chat_history=chat_log or [],
                                submission_record=submission_record,
                            )
                            if sheets_ok:
                                print(f"βœ… Logged to Google Sheets: {student_name}")
                                cloud_updates["google_sheets"] = {"status": "success", "error": ""}
                            else:
                                diag = diagnose_google_sheets()
                                reason = diag.get("reason", "Logger returned False")
                                print(f"⚠️ Google Sheets logging returned False: {reason}")
                                cloud_updates["google_sheets"] = {"status": "failed", "error": reason}
                        except Exception as e:
                            print(f"⚠️ Google Sheets logging failed: {e}")
                            cloud_updates["google_sheets"] = {"status": "failed", "error": str(e)}
                    else:
                        reason = str(cloud_caps["google_sheets"]["reason"])
                        logger.warning("Google Sheets upload disabled: %s", reason)
                        cloud_updates["google_sheets"] = {"status": "disabled", "error": reason}
                    
                    log.update(log_path, {"cloud": cloud_updates})
                
                # Start background upload (won't block UI)
                upload_thread = threading.Thread(target=_background_upload, daemon=True)
                upload_thread.start()
                
            except Exception as exc:
                import traceback
                error_details = traceback.format_exc()
                debug_logs = log_capture.getvalue() + f"\n\n❌ ERROR:\n{error_details}"
                sys.stdout = original_stdout  # Restore stdout
                err = f"<p style='color:#ef4444;padding:20px;font-family:monospace;'>❌ Error during evaluation:<br>{exc}</p>"
                yield (gr.update(visible=False), gr.update(visible=True), err, "", "", "", submit_count, debug_logs, debug_logs)
            finally:
                sys.stdout = original_stdout  # Always restore stdout

        def on_send(message, history, hints_used, submit_count, workspace_path, chat_log, hint_log, confirmation_pending, user_api_key, profile: gr.OAuthProfile | None = None):
            if _hf_auth_required(profile):
                response = "Please sign in with Hugging Face before using the assistant."
                history = list(history or []) + [
                    {"role": "user", "content": message},
                    {"role": "assistant", "content": response},
                ]
                return history, "", hints_used, _hint_md(hints_used, 0), chat_log, hint_log, confirmation_pending

            if not message.strip():
                penalty = PENALTY_TABLE[min(hints_used, len(PENALTY_TABLE) - 1)]
                return history, "", hints_used, _hint_md(hints_used, penalty), chat_log, hint_log, confirmation_pending
            if not workspace_path:
                history = list(history or []) + [
                    {"role": "user",      "content": message},
                    {"role": "assistant", "content": "No challenge loaded yet."},
                ]
                new_chat_log = list(chat_log or [])
                new_chat_log.append({
                    "question": message,
                    "response": "No challenge loaded yet.",
                    "gave_hint": False,
                    "hint_summary": "",
                })
                return history, "", hints_used, _hint_md(hints_used, 0), new_chat_log, hint_log, False
            cs = ChallengeState(workspace_path)
            with llm_api_key_context(user_api_key or None):
                result = get_hint(
                    user_message=message,
                    history=history,
                    hints_used=hints_used,
                    submission_attempts=submit_count,
                    challenge_info=cs.challenge_info(),
                )
            # Python-level guarantee: if a confirmation was pending and the student
            # didn't explicitly decline, the hint counts β€” regardless of LLM marker.
            accepted_pending = confirmation_pending and _is_affirmation(message)
            gave_hint = result["gave_hint"] or accepted_pending
            new_confirmation_pending = not gave_hint and _is_confirmation_question(result["response"])

            history = list(history or []) + [
                {"role": "user",      "content": message},
                {"role": "assistant", "content": result["response"]},
            ]
            new_chat_log = list(chat_log or [])
            new_chat_log.append({
                "question": message,
                "response": result["response"],
                "gave_hint": gave_hint,
                "hint_summary": result.get("hint_summary", ""),
            })
            new_hints = hints_used + (1 if gave_hint else 0)
            penalty   = PENALTY_TABLE[min(new_hints, len(PENALTY_TABLE) - 1)]
            new_log   = list(hint_log or [])
            if gave_hint:
                new_log.append({
                    "question": message,
                    "response": result["response"],
                    "hint_summary": result.get("hint_summary", ""),
                    "summary": result.get("hint_summary", ""),
                })
            return history, "", new_hints, _hint_md(new_hints, penalty), new_chat_log, new_log, new_confirmation_pending

        # ── Wiring ────────────────────────────────────────────────────────


        file_dropdown.change(
            on_file_select,
            inputs=[file_dropdown, workspace_state],
            outputs=[code_editor],
        )
        save_btn.click(on_save, inputs=[code_editor, file_dropdown, workspace_state], outputs=[save_status])

        btn_tests.click(on_run_tests, inputs=[code_editor, file_dropdown, workspace_state], outputs=[left_tabs, test_output])
        run_tests_tab_btn.click(on_run_tests, inputs=[code_editor, file_dropdown, workspace_state], outputs=[left_tabs, test_output])

        btn_changes.click(on_show_changes, inputs=[code_editor, file_dropdown, workspace_state], outputs=[left_tabs, changes_diff_html])
        refresh_btn.click(on_show_changes, inputs=[code_editor, file_dropdown, workspace_state], outputs=[left_tabs, changes_diff_html])

        revert_btn.click(on_revert, inputs=[workspace_state], outputs=[code_editor, left_tabs])

        submit_btn.click(
            on_submit,
            inputs=[submit_trigger, hints_used_state, submission_count_state,
                    workspace_state, chat_log_state, hint_log_state, user_name_state, code_editor, file_dropdown,
                    user_api_key_state],
            outputs=[
                challenge_page,  # Hide challenge page
                results_page,    # Show results page
                score_summary_html,
                results_changes_html,
                results_test_html,
                results_hints_html,
                submission_count_state,
                debug_console,
                live_debug_console,
            ],
        )
        
        send_btn.click(
            on_send,
            inputs=[chat_input, chatbot, hints_used_state, submission_count_state, workspace_state, chat_log_state,
                    hint_log_state, confirmation_pending_state, user_api_key_state],
            outputs=[chatbot, chat_input, hints_used_state, hint_counter, chat_log_state, hint_log_state, confirmation_pending_state],
        )
        chat_input.submit(
            on_send,
            inputs=[chat_input, chatbot, hints_used_state, submission_count_state, workspace_state, chat_log_state,
                    hint_log_state, confirmation_pending_state, user_api_key_state],
            outputs=[chatbot, chat_input, hints_used_state, hint_counter, chat_log_state, hint_log_state, confirmation_pending_state],
        )

    # CRITICAL: Enable queue for generator functions to work on production servers
    # max_size: Maximum queue size to prevent overflow
    # default_concurrency_limit: Number of requests processed in parallel
    demo.queue(max_size=20, default_concurrency_limit=10)
    
    return demo


# ── Legacy entry point (used by challenge.py CLI path) ───────────────────────

def create_interface(workspace_path: str, student_name: str = "", timer_minutes: int = 0) -> gr.Blocks:
    """Build the challenge-only interface for a pre-existing workspace."""

    cs  = ChallengeState(workspace_path)
    log = SubmissionLog(cs.workspace)

    py_files     = cs.list_py_files()
    default_file = cs.target_file if cs.target_file in py_files else (py_files[0] if py_files else None)

    name_suffix = f" &nbsp;|&nbsp; {student_name.strip()}" if student_name.strip() else ""

    css = """
    #code-editor {
        font-size: 14px !important;
        font-family: 'Consolas', 'Monaco', 'Courier New', monospace !important;
        background-color: #1e1e1e !important;
        border-radius: 8px !important;
    }
    #code-editor .codemirror-wrapper {
        background-color: #1e1e1e !important;
    }
    #code-editor .cm-editor {
        background-color: #1e1e1e !important;
    }
    """

    # Note: CSS parameter moved to launch() in Gradio 6.0, removed for compatibility
    with gr.Blocks(title="Legacy Code Challenge", js=_make_js(timer_minutes)) as demo:

        hints_used_state          = gr.State(0)
        submission_count_state    = gr.State(0)
        chat_log_state            = gr.State([])
        hint_log_state            = gr.State([])
        confirmation_pending_state = gr.State(False)

        with gr.Row(elem_classes=["header-row"]):
            gr.Markdown(
                f"### πŸ› Legacy Code Challenge{name_suffix}",
                elem_classes=["app-header"],
            )
            gr.HTML('<span id="timer-inner"></span>', elem_id="challenge-timer")

        # ── Challenge page ────────────────────────────────────────────────
        with gr.Column(visible=True) as challenge_col:
            with gr.Row(elem_classes=["main-row"]):
                with gr.Column(scale=3, elem_classes=["left-col"]):
                    with gr.Tabs(selected=0, elem_classes=["left-tabs"]) as left_tabs:

                        with gr.Tab("πŸ“‹ Challenge", id=0):
                            gr.Markdown(cs.readme())

                        with gr.Tab("πŸ’» Code Editor", id=1):
                            file_dropdown = gr.Dropdown(
                                choices=py_files, value=default_file, label="File",
                                info="Select a file to view. Submit saves to the target file.",
                            )
                            with gr.Row():
                                btn_tests   = gr.Button("β–Ά Run Tests",        variant="secondary")
                                btn_changes = gr.Button("πŸ‘οΈ View My Changes", variant="secondary")
                                save_btn    = gr.Button("πŸ’Ύ Save",             variant="secondary", elem_id="save-btn")
                            save_status = gr.Markdown("")
                            code_editor = gr.Code(
                                value=cs.read_target(), language="python", label=cs.target_file,
                                interactive=True, lines=30, elem_id="code-editor",
                                show_label=False,
                            )

                        with gr.Tab("πŸ§ͺ Test Results", id=2):
                            run_tests_tab_btn = gr.Button("β–Ά Run Tests", variant="secondary")
                            test_output = gr.HTML(
                                "<p style='color:#888;font-family:monospace;'>Click 'β–Ά Run Tests' to run…</p>"
                            )

                        with gr.Tab("πŸ‘οΈ My Changes", id=3):
                            gr.Markdown("_Diff: your saved file vs the original buggy code you received_")
                            with gr.Row():
                                refresh_btn = gr.Button("πŸ”„ Refresh", variant="secondary")
                                revert_btn  = gr.Button("↩️ Revert to Original", variant="secondary")
                            changes_diff_html = gr.HTML("")

                with gr.Column(scale=2, elem_classes=["right-col"]):
                    hint_counter = gr.Markdown(_hint_md(0, 0))
                    chatbot = gr.Chatbot(
                        label="AI Assistant",
                        elem_id="ai-chatbot",
                    )
                    with gr.Row():
                        chat_input = gr.Textbox(
                            placeholder="Ask the AI assistant for a hint…",
                            show_label=False, scale=5,
                        )
                        send_btn   = gr.Button("Send", variant="secondary", scale=1)
                    gr.Markdown("---")
                    submit_btn = gr.Button("πŸš€ Submit Fix", variant="primary")

        # ── Results page ──────────────────────────────────────────────────
        with gr.Column(visible=False) as results_col:
            gr.Markdown("## πŸ“Š Submission Results")

            score_summary_html = gr.HTML("")

            with gr.Tabs():
                with gr.Tab("πŸ§ͺ Test Results"):
                    results_test_html = gr.HTML("")

                with gr.Tab("πŸ” Changes & Expected"):
                    results_changes_html = gr.HTML("")

                with gr.Tab("πŸ’‘ Hints Used"):
                    results_hints_html = gr.HTML("")
            
            # Debug console (collapsible)
            with gr.Accordion("πŸ› Debug Console", open=False):
                debug_console_standalone = gr.Textbox(
                    label="Execution Logs",
                    lines=15,
                    max_lines=30,
                    interactive=False,
                    placeholder="Debug logs will appear here...",
                )

        # ── Callbacks ─────────────────────────────────────────────────────

        def on_file_select(rel_path):
            content = cs.read_py_file(rel_path)
            return gr.update(value=content, interactive=True, label=rel_path)

        def on_save(code, rel_path):
            if rel_path:
                cs.write_py_file(rel_path, code)
            else:
                cs.write_target(code)
            return "βœ… Saved"

        def on_run_tests(code, rel_path):
            loading = '<p style="text-align:center;padding:20px;color:#888;">⏳ Running tests…</p>'
            yield (gr.update(selected=2), loading)
            # Auto-save before running tests
            if rel_path:
                cs.write_py_file(rel_path, code)
            else:
                cs.write_target(code)
            try:
                from orchestrator.scoring import run_tests
                r   = run_tests(workspace_path)
                raw = r["output"] if r["output"] else "No output."
                yield (gr.update(selected=2), _colorise_test_output(raw))
            except Exception as exc:
                yield (gr.update(selected=2), f"<p style='color:#ef4444;font-family:monospace;'>❌ Error: {exc}</p>")

        def on_show_changes():
            # Read directly from disk (Gradio code_editor doesn't update its value reliably)
            diff = _workspace_diff_html(cs)
            return (gr.update(selected=3), diff)

        def on_revert():
            cs.reset_target()
            return cs.sabotaged_code, gr.update(selected=1)

        def on_submit(hints_used, submit_count, chat_log, hint_log, code, rel_path):
            # Capture all print statements for debug console
            log_capture = StringIO()
            original_stdout = sys.stdout
            sys.stdout = log_capture
            
            try:
                _loading = '<p style="text-align:center;padding:40px;color:#888;font-size:1.2em;">⏳ Running tests…</p>'
                sys.stdout = original_stdout  # Restore for yield
                yield (
                    gr.update(visible=False),
                    gr.update(visible=True),
                    _loading, "", "", "",
                    submit_count,
                    "",  # debug console
                )
                sys.stdout = log_capture  # Capture again
                
                print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸš€ Starting submission evaluation (standalone mode)...")
                if rel_path:
                    cs.write_py_file(rel_path, code)
                print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸ“– Reading submitted code...")
                submitted_code = cs.read_target()
                
                print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸ§ͺ Running tests...")
                result = evaluate_submission(
                    workspace_path=workspace_path,
                    student_code=submitted_code,
                    original_code=cs.original_code,
                    bug_func_name=cs.bug_func_name,
                    hints_used=hints_used,
                    sabotaged_code=cs.sabotaged_code,
                    target_file=str(cs.target_path),
                    bug_func_names=cs.bug_func_names,
                )
                
                new_count = submit_count + 1

                print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸ“Š Generating results...")
                score_html    = _score_summary_html(result)
                combined_diff = _combined_changes_html(cs, submitted_code)
                test_html     = _colorise_test_output(result["test_output"] or "No test output.")
                hints_html    = _hints_html(hint_log or [])

                print(f"[{datetime.now().strftime('%H:%M:%S')}] βœ… Results ready, returning to user...")
                
                # Get all captured logs
                debug_logs = log_capture.getvalue()
                print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸ’Ύ Saving submission...")
                submission_record = _build_submission_record(
                    cs=cs,
                    student_name="Anonymous (standalone mode)",
                    submitted_code=submitted_code,
                    result=result,
                    hints_used=hints_used,
                    chat_log=chat_log or [],
                    hint_log=hint_log or [],
                    attempt_number=new_count,
                    debug_logs=debug_logs,
                    enable_cloud_uploads=False,
                )
                log_path = log.save(submission_record)
                supabase_result = _save_submission_to_supabase(log, log_path, submission_record)
                if supabase_result["status"] != "success":
                    debug_logs += f"\n\nSupabase storage {supabase_result['status']}: {supabase_result['error']}"
                    log.update(log_path, {"debug": {"captured_logs": debug_logs}})
                sys.stdout = original_stdout  # Restore stdout
                
                # Return results to user IMMEDIATELY
                yield (
                    gr.update(visible=False), gr.update(visible=True),
                    score_html, combined_diff, test_html, hints_html,
                    new_count,
                    debug_logs,
                )
                
            except Exception as exc:
                import traceback
                error_details = traceback.format_exc()
                debug_logs = log_capture.getvalue() + f"\n\n❌ ERROR:\n{error_details}"
                sys.stdout = original_stdout  # Restore stdout
                err = f"<p style='color:#ef4444;padding:20px;font-family:monospace;'>❌ Error during evaluation:<br>{exc}</p>"
                yield (gr.update(visible=False), gr.update(visible=True), err, "", "", "", submit_count, debug_logs)
            finally:
                sys.stdout = original_stdout  # Always restore stdout

        def on_send(message, history, hints_used, submit_count, chat_log, hint_log, confirmation_pending):
            if not message.strip():
                penalty = PENALTY_TABLE[min(hints_used, len(PENALTY_TABLE) - 1)]
                return history, "", hints_used, _hint_md(hints_used, penalty), chat_log, hint_log, confirmation_pending
            result = get_hint(
                user_message=message, history=history,
                hints_used=hints_used, submission_attempts=submit_count,
                challenge_info=cs.challenge_info(),
            )
            # Python-level guarantee: if a confirmation was pending and the student
            # didn't explicitly decline, the hint counts β€” regardless of LLM marker.
            accepted_pending = confirmation_pending and _is_affirmation(message)
            gave_hint = result["gave_hint"] or accepted_pending
            new_confirmation_pending = not gave_hint and _is_confirmation_question(result["response"])

            history = list(history or []) + [
                {"role": "user",      "content": message},
                {"role": "assistant", "content": result["response"]},
            ]
            new_chat_log = list(chat_log or [])
            new_chat_log.append({
                "question": message,
                "response": result["response"],
                "gave_hint": gave_hint,
                "hint_summary": result.get("hint_summary", ""),
            })
            new_hints = hints_used + (1 if gave_hint else 0)
            penalty   = PENALTY_TABLE[min(new_hints, len(PENALTY_TABLE) - 1)]
            new_log   = list(hint_log or [])
            if gave_hint:
                new_log.append({
                    "question": message,
                    "response": result["response"],
                    "hint_summary": result.get("hint_summary", ""),
                    "summary": result.get("hint_summary", ""),
                })
            return history, "", new_hints, _hint_md(new_hints, penalty), new_chat_log, new_log, new_confirmation_pending

        # ── Wiring ────────────────────────────────────────────────────────


        file_dropdown.change(on_file_select, inputs=[file_dropdown], outputs=[code_editor])
        save_btn.click(on_save, inputs=[code_editor, file_dropdown], outputs=[save_status])

        btn_tests.click(on_run_tests, inputs=[code_editor, file_dropdown], outputs=[left_tabs, test_output])
        run_tests_tab_btn.click(on_run_tests, inputs=[code_editor, file_dropdown], outputs=[left_tabs, test_output])

        btn_changes.click(on_show_changes, outputs=[left_tabs, changes_diff_html])
        refresh_btn.click(on_show_changes, outputs=[left_tabs, changes_diff_html])

        revert_btn.click(on_revert, outputs=[code_editor, left_tabs])

        submit_btn.click(
            on_submit,
            inputs=[hints_used_state, submission_count_state, chat_log_state, hint_log_state, code_editor, file_dropdown],
            outputs=[
                challenge_col, results_col,
                score_summary_html,
                results_changes_html,
                results_test_html,
                results_hints_html,
                submission_count_state,
                debug_console_standalone,
            ],
        )
        send_btn.click(
            on_send,
            inputs=[chat_input, chatbot, hints_used_state, submission_count_state, chat_log_state, hint_log_state, confirmation_pending_state],
            outputs=[chatbot, chat_input, hints_used_state, hint_counter, chat_log_state, hint_log_state, confirmation_pending_state],
        )
        chat_input.submit(
            on_send,
            inputs=[chat_input, chatbot, hints_used_state, submission_count_state, chat_log_state, hint_log_state, confirmation_pending_state],
            outputs=[chatbot, chat_input, hints_used_state, hint_counter, chat_log_state, hint_log_state, confirmation_pending_state],
        )

    # CRITICAL: Enable queue for generator functions to work on production servers
    # max_size: Maximum queue size | default_concurrency_limit: Parallel requests
    demo.queue(max_size=20, default_concurrency_limit=10)
    
    return demo

# Create the demo instance for app.py to import
demo = create_full_interface()

if __name__ == "__main__":
    demo.launch()