File size: 114,548 Bytes
d81481c
dd2ffee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34df3ae
dd2ffee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
775bc78
 
dd2ffee
 
775bc78
dd2ffee
8a9cf86
89acb88
dd2ffee
 
 
 
92a55ee
599eea2
 
 
 
 
1697428
599eea2
 
 
 
 
dd2ffee
599eea2
 
 
 
 
 
 
 
 
 
 
 
 
775bc78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd2ffee
 
 
 
 
 
34df3ae
dd2ffee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c243f10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd2ffee
c243f10
 
 
dd2ffee
c243f10
dd2ffee
c243f10
dd2ffee
c243f10
dd2ffee
c243f10
dd2ffee
34df3ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd2ffee
 
 
c243f10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd2ffee
 
 
c243f10
 
 
 
 
 
 
dd2ffee
c243f10
dd2ffee
 
c243f10
 
 
 
 
dd2ffee
 
 
c243f10
 
 
 
 
dd2ffee
 
 
c243f10
 
 
 
 
dd2ffee
 
 
c243f10
 
 
 
 
dd2ffee
 
 
c243f10
 
 
 
 
dd2ffee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34df3ae
dd2ffee
34df3ae
dd2ffee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34df3ae
 
 
 
 
 
 
 
dd2ffee
34df3ae
dd2ffee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34df3ae
dd2ffee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e304a25
dd2ffee
34df3ae
 
dd2ffee
 
 
 
 
 
34df3ae
 
 
dd2ffee
 
 
 
34df3ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e304a25
 
34df3ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e304a25
34df3ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b204c0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34df3ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b204c0d
 
 
 
 
 
 
34df3ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b204c0d
 
 
34df3ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd2ffee
 
 
 
 
 
 
 
 
9aa0db6
a8d1c3a
 
dd2ffee
 
bef34b1
 
 
9aa0db6
a8d1c3a
4959a61
 
 
 
9aa0db6
a8d1c3a
4959a61
 
9aa0db6
 
4959a61
 
 
 
9aa0db6
 
 
 
dd2ffee
 
4959a61
dd2ffee
 
4959a61
dd2ffee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4959a61
dd2ffee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4959a61
dd2ffee
 
 
 
4959a61
 
 
 
 
 
 
 
 
 
 
dd2ffee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4959a61
 
 
 
 
 
 
 
 
 
 
dd2ffee
 
 
 
4959a61
dd2ffee
 
 
 
 
bef34b1
 
dd2ffee
 
 
 
4959a61
dd2ffee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4959a61
 
 
dd2ffee
 
 
e1d72a3
 
05ec958
e1d72a3
 
 
 
 
 
 
dd2ffee
e1d72a3
 
 
 
dd2ffee
 
 
 
 
 
e1d72a3
dd2ffee
 
e1d72a3
 
 
dd2ffee
e1d72a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd2ffee
e1d72a3
 
3a28f7c
e1d72a3
 
 
3a28f7c
 
 
 
e1d72a3
 
 
3a28f7c
 
 
 
 
 
f16292f
 
 
e1d72a3
3a28f7c
 
dd2ffee
e1d72a3
 
 
dd2ffee
 
e1d72a3
 
 
 
 
dd2ffee
 
 
 
e1d72a3
 
 
 
 
 
dd2ffee
 
 
e1d72a3
dd2ffee
 
 
e1d72a3
dd2ffee
 
 
e1d72a3
 
dd2ffee
e1d72a3
 
 
 
 
 
 
 
 
 
dd2ffee
 
e1d72a3
 
dd2ffee
e1d72a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd2ffee
e1d72a3
dd2ffee
 
 
0b74dd0
dd2ffee
 
e1d72a3
 
 
 
dd2ffee
e1d72a3
dd2ffee
 
e1d72a3
dd2ffee
e1d72a3
 
dd0de01
dd2ffee
 
8f841bf
 
 
 
 
 
dd2ffee
 
 
8f841bf
 
 
 
 
 
dd0de01
 
dd2ffee
 
 
 
 
e1d72a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd2ffee
 
 
34df3ae
dd2ffee
 
 
 
 
 
 
 
34df3ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd2ffee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3134223
7d75cd8
dd2ffee
 
7d75cd8
dd2ffee
7d75cd8
dd2ffee
7d75cd8
dd2ffee
7d75cd8
dd2ffee
4c316b6
7d75cd8
 
 
023e864
dd2ffee
 
 
7d75cd8
023e864
dd2ffee
7d75cd8
4959a61
7d75cd8
dd2ffee
7d75cd8
dd2ffee
 
 
 
7d75cd8
4959a61
7d75cd8
dd2ffee
7d75cd8
dd2ffee
4e706fc
dd2ffee
7d75cd8
dd2ffee
 
 
 
 
 
d81481c
 
 
 
 
 
 
 
 
dd2ffee
7d75cd8
dd2ffee
 
 
 
 
 
 
 
 
 
 
 
7d75cd8
 
 
dd2ffee
7d75cd8
ea87f78
dd2ffee
7d75cd8
 
 
 
 
 
dd2ffee
7d75cd8
 
dd2ffee
 
7d75cd8
dd2ffee
 
7d75cd8
a8d1c3a
 
7d75cd8
 
 
 
dd2ffee
7d75cd8
 
dd2ffee
7d75cd8
 
 
 
 
dd2ffee
 
 
 
7d75cd8
 
 
8a9cf86
7d75cd8
8a9cf86
 
 
 
7d75cd8
dd2ffee
7d75cd8
5175a91
 
 
 
 
 
 
 
 
dd2ffee
5175a91
dd2ffee
5175a91
 
c84e191
7d75cd8
dd2ffee
 
 
 
7d75cd8
dd2ffee
 
 
7d75cd8
4e706fc
c814274
0a552ea
 
 
 
 
 
 
 
dd2ffee
 
 
 
 
7d75cd8
 
dd2ffee
7d75cd8
61b370f
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
from flask import Flask, request, jsonify, render_template, send_from_directory, send_file
import cv2, json,base64,io,os,tempfile,logging, re
import numpy as np
from unstructured.partition.pdf import partition_pdf
from PIL import Image
# from imutils.perspective import four_point_transform
from dotenv import load_dotenv
import pytesseract
from werkzeug.utils import secure_filename
from langchain_groq import ChatGroq
from langgraph.prebuilt import create_react_agent
from pdf2image import convert_from_path
from concurrent.futures import ThreadPoolExecutor
from pdf2image.exceptions import PDFInfoNotInstalledError
from typing import Dict, TypedDict, Optional, Any
from langgraph.graph import StateGraph, END
import uuid
import shutil, time
from langchain_experimental.open_clip.open_clip import OpenCLIPEmbeddings
# from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from io import BytesIO
from pathlib import Path
import os
from utils.block_relation_builder import block_builder, variable_adder_main

# ============================== #
#     INITIALIZE CLIP EMBEDDER   #
# ============================== #
clip_embd = OpenCLIPEmbeddings()

# Configure logging
logging.basicConfig(
    level=logging.DEBUG,  # Use INFO or ERROR in production
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler("/app/logs/app.log"),
        logging.StreamHandler()
    ]
)

logger = logging.getLogger(__name__)

load_dotenv()
# os.environ["GROQ_API_KEY"] = os.getenv("GROQ_API_KEY")
groq_api_key = os.getenv("GROQ_API_KEY")

llm = ChatGroq(
    model="meta-llama/llama-4-scout-17b-16e-instruct",
    temperature=0,
    max_tokens=None,
)

app = Flask(__name__)

# ============================== #
#     TESSERACT CONFIGURATION    #
# ============================== #
# Set the Tesseract executable path
# pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
pytesseract.pytesseract.tesseract_cmd = (r'/usr/bin/tesseract')
# Set the TESSDATA_PREFIX environment variable to the directory containing the 'tessdata' folder
# This is crucial for Tesseract to find its language data files (e.g., eng.traineddata)
# os.environ['TESSDATA_PREFIX'] = r'C:\Program Files\Tesseract-OCR'

# poppler_path = r"C:\poppler\Library\bin"
backdrop_images_path = r"app\blocks\Backdrops"
sprite_images_path = r"blocks\sprites"

count = 0

BASE_DIR = Path("/app")
BLOCKS_DIR       = BASE_DIR / "blocks"
STATIC_DIR       = BASE_DIR / "static"
GEN_PROJECT_DIR  = BASE_DIR / "generated_projects"
BACKDROP_DIR     = BLOCKS_DIR / "Backdrops"
SPRITE_DIR       = BLOCKS_DIR / "sprites"

# === new: outputs rooted under BASE_DIR ===
OUTPUT_DIR       = BASE_DIR / "outputs"
DETECTED_IMAGE_DIR = OUTPUT_DIR / "DETECTED_IMAGE"
SCANNED_IMAGE_DIR  = OUTPUT_DIR / "SCANNED_IMAGE"
JSON_DIR           = OUTPUT_DIR / "EXTRACTED_JSON"

# make all of them in one go
for d in (
    BLOCKS_DIR,
    STATIC_DIR,
    GEN_PROJECT_DIR,
    BACKDROP_DIR,
    SPRITE_DIR,
    OUTPUT_DIR,
    DETECTED_IMAGE_DIR,
    SCANNED_IMAGE_DIR,
    JSON_DIR,
):
    d.mkdir(parents=True, exist_ok=True)
# def classify_image_type(description_or_name: str) -> str:
#     desc = description_or_name.lower()

#     sprite_keywords = ["sprite", "character", "animal", "person", "creature", "robot", "figure"]
#     backdrop_keywords = ["background", "scene", "forest", "city", "room", "sky", "mountain", "village"]
#     code_block_keywords = [
#         "move", "turn", "wait", "repeat", "if", "else", "broadcast",
#         "glide", "change", "forever", "when", "switch", "costume",
#         "say", "think", "stop", "clone", "touching", "sensing",
#         "scratch", "block", "code", "set", "variable"
#     ]

#     if any(kw in desc for kw in code_block_keywords):
#         return "code-block"
#     elif any(kw in desc for kw in sprite_keywords):
#         return "sprite"
#     elif any(kw in desc for kw in backdrop_keywords):
#         return "backdrop"
#     else:
#         return "unknown"
      
class GameState(TypedDict):
    project_json: dict
    description: str
    project_id: str
    project_image: str
    pseudo_code: dict
    action_plan: Optional[Dict]
    temporary_node: Optional[Dict]
    
    
# Refined SYSTEM_PROMPT with more explicit Scratch JSON rules, especially for variables
SYSTEM_PROMPT = """
You are an expert AI assistant named GameScratchAgent, specialized in generating and modifying Scratch-VM 3.x game project JSON.
Your core task is to process game descriptions and existing Scratch JSON structures, then produce or update JSON segments accurately.
You possess deep knowledge of Scratch 3.0 project schema, informed by comprehensive reference materials. When generating or modifying the `blocks` section, pay extremely close attention to the following:

**Scratch Project JSON Schema Rules:**

1.  **Target Structure (`project.json`'s `targets` array):**
    * Each object in the `targets` array represents a Stage or a Sprite.
    * `isStage`: A boolean indicating if the target is the Stage (`true`) or a Sprite (`false`).
    * `name`: The name of the Stage (e.g., `"Stage"`) or the Sprite (e.g., `"Cat"`). This property replaces `objName` found in older Scratch versions.
    * `variables` dictionary: This dictionary maps unique variable IDs to arrays `[variable_name, initial_value, isCloudVariable?]`.
        * `variable_name`: The user-defined name of the variable.
        * `initial_value`: The variable's initial value, which can be a number or a string.
        * `isCloudVariable?`: (Optional) A boolean indicating if it's a cloud variable (`true`) or a local variable (`false` or absent for regular variables).
        * Example: `"myVarId123": ["score", 0]`, `"cloudVarId456": ["☁ High Score", "54", true]`
    * `lists` dictionary: This dictionary maps unique list IDs to arrays `[list_name, [item1, item2, ...]]`.
        * Example: `"myListId789": ["my list", ["apple", "banana"]]`
    * `broadcasts` dictionary: This dictionary maps unique broadcast IDs to their names.
        * Example: `"myBroadcastId": "Game Over"`
    * `blocks` dictionary: This dictionary contains all the blocks belonging to this target. Keys are block IDs, values are block objects.

2.  **Block Structure (within a `target`'s `blocks` dictionary):**
    * Every block object must have the following core properties:
        * [cite_start]`opcode`: A unique internal identifier for the block's specific functionality (e.g., `"motion_movesteps"`, `"event_whenflagclicked"`)[cite: 31, 18, 439, 452].
        * `parent`: The ID of the block directly above it in the script stack (or `null` for a top-level block).
        * `next`: The ID of the block directly below it in the script stack (or `null` for the end of a stack).
        * `inputs`: An object defining values or blocks plugged into the block's input slots. Values are **arrays**.
        * `fields`: An object defining dropdown menu selections or direct internal values within the block. Values are **arrays**.
        * `shadow`: `true` if it's a shadow block (e.g., a default number input that can be replaced by another block), `false` otherwise.
        * `topLevel`: `true` if it's a hat block or a standalone block (not connected to a parent), `false` otherwise.

3.  **`inputs` Property Details (for blocks plugged into input slots):**
    * **Direct Block Connection (Reporter/Boolean block plugged in):**
        * Format: `"<INPUT_NAME>": [1, "<blockId_of_plugged_block>"]`
        * Example: `"CONDITION": [1, "someBooleanBlockId"]` (e.g., for an `if` block).
    * **Literal Value Input (Shadow block with a literal):**
        * Format: `"<INPUT_NAME>": [1, [<type_code>, "<value_string>"]]`
        * `type_code`: A numeric code representing the data type. Common codes include: `4` for number, `7` for string/text, `10` for string/message.
        * `value_string`: The literal value as a string.
        * Examples:
            * Number: `"STEPS": [1, [4, "10"]]` (for `move 10 steps` block).
            * String/Text: `"MESSAGE": [1, [7, "Hello"]]` (for `say Hello` block).
            * String/Message (common for text inputs): `"MESSAGE": [1, [10, "Hello!"]]` (for `say Hello! for 2 secs`).
    * **C-Block Substack (blocks within a loop or conditional):**
        * Format: `"<SUBSTACK_NAME>": [2, "<blockId_of_first_block_in_substack>"]`
        * Common `SUBSTACK_NAME` values are `SUBSTACK` (for `if`, `forever`, `repeat`) and `SUBSTACK2` (for `else` in `if else`).
        * Example: `"SUBSTACK": [2, "firstBlockInLoopId"]`

4.  **`fields` Property Details (for dropdowns or direct internal values):**
    * Used for dropdown menus, variable names, list names, or other static selections directly within the block.
    * Format: `"<FIELD_NAME>": ["<selected_value>", null]`
    * Examples:
        * Dropdown: `"KEY_OPTION": ["space", null]` (for `when space key pressed`).
        * Variable Name: `"VARIABLE": ["score", null]` (for `set score to 0`).
        * Direction (specific motion block): `"FORWARD_BACKWARD": ["forward", null]` (for `go forward layers`).

5.  **Unique IDs:**
    * All block IDs, variable IDs, and list IDs must be unique strings (e.g., "myBlock123", "myVarId456", "myListId789"). Do NOT use placeholder strings like "block_id_here".

6.  **No Nested `blocks` Dictionary:**
    * The `blocks` dictionary should only appear once per `target` (sprite/stage). Do NOT nest a `blocks` dictionary inside an individual block definition. Blocks that are part of a substack are linked via the `SUBSTACK` input.

7.  **Asset Properties (for Costumes/Sounds):**
    * `assetId`, `md5ext`, `bitmapResolution`, `rotationCenterX`/`rotationCenterY` should be correctly associated with costume and sound objects within the `costumes` and `sounds` arrays.

**General Principles and Important Considerations:**
* **Backward Compatibility:** Adhere strictly to existing Scratch 3.0 opcodes and schema to ensure backward compatibility with older projects. [cite_start]Opcodes must remain consistent to prevent previously saved projects from failing to load or behaving unexpectedly[cite: 18, 19, 25, 65].
* **Forgiving Inputs:** Recognize that Scratch is designed to be "forgiving in its interpretation of inputs." [cite_start]The Scratch VM handles potentially "invalid" inputs gracefully (e.g., converting a number to a string if expected, returning default values like zero or empty strings, or performing no action) rather than crashing[cite: 20, 21, 22, 38, 39, 41]. This implies that precise type matching for inputs might be handled internally by Scratch, allowing for some flexibility in how values are provided, but the agent should aim for the most common and logical type.
"""

SYSTEM_PROMPT_JSON_CORRECTOR ="""
You are an assistant that outputs JSON responses strictly following the given schema.  
If the JSON you produce has any formatting errors, missing required fields, or invalid structure, you must identify the problems and correct them.  
Always return only valid JSON that fully conforms to the schema below, enclosed in triple backticks (```), without any extra text or explanation.  

If you receive an invalid or incomplete JSON response, fix it by:  
- Adding any missing required fields with appropriate values.  
- Correcting syntax errors such as missing commas, brackets, or quotes.  
- Ensuring the JSON structure matches the schema exactly.  

Remember: Your output must be valid JSON only, ready to be parsed without errors.
"""
# debugger and resolver agent for Scratch 3.0
# Main agent of the system agent for Scratch 3.0
agent = create_react_agent(
    model=llm,
    tools=[], # No specific tools are defined here, but could be added later
    prompt=SYSTEM_PROMPT
)

agent_json_resolver = create_react_agent(
    model=llm,
    tools=[], # No specific tools are defined here, but could be added later
    prompt=SYSTEM_PROMPT_JSON_CORRECTOR 
)

# Helper function to load the block catalog from a JSON file
# def _load_block_catalog(file_path: str) -> Dict:
#     """Loads the Scratch block catalog from a specified JSON file."""
#     try:
#         with open(file_path, 'r') as f:
#             catalog = json.load(f)
#         logger.info(f"Successfully loaded block catalog from {file_path}")
#         return catalog
#     except FileNotFoundError:
#         logger.error(f"Error: Block catalog file not found at {file_path}")
#         # Return an empty dict or raise an error, depending on desired behavior
#         return {}
#     except json.JSONDecodeError as e:
#         logger.error(f"Error decoding JSON from {file_path}: {e}")
#         return {}
#     except Exception as e:
#         logger.error(f"An unexpected error occurred while loading {file_path}: {e}")
#         return {}

# Helper function to load the block catalog from a JSON file
def _load_block_catalog(block_type: str) -> Dict:
    """
    Loads the Scratch block catalog named '{block_type}_blocks.json'
    from the <project_root>/blocks/ folder. Returns {} on any error.
    """
    catalog_path = BLOCKS_DIR / f"{block_type}.json"

    try:
        text = catalog_path.read_text()  # will raise FileNotFoundError if missing
        catalog = json.loads(text)       # will raise JSONDecodeError if malformed
        logger.info(f"Successfully loaded block catalog from {catalog_path}")
        return catalog

    except FileNotFoundError:
        logger.error(f"Error: Block catalog file not found at {catalog_path}")
    except json.JSONDecodeError as e:
        logger.error(f"Error decoding JSON from {catalog_path}: {e}")
    except Exception as e:
        logger.error(f"Unexpected error loading {catalog_path}: {e}")

def get_block_by_opcode(catalog_data: dict, opcode: str) -> dict | None:
    """
    Search a single catalog (with keys "description" and "blocks": List[dict])
    for a block whose 'op_code' matches the given opcode.
    Returns the block dict or None if not found.
    """
    for block in catalog_data["blocks"]:
        if block.get("op_code") == opcode:
            return block
    return None

# Helper function to find a block in all catalogs by opcode
def find_block_in_all(opcode: str, all_catalogs: list[dict]) -> dict | None:
    """
    Search across multiple catalogs for a given opcode.
    Returns the first matching block dict or None.
    """
    for catalog in all_catalogs:
        blk = get_block_by_opcode(catalog, opcode)
        if blk is not None:
            return blk
    return None



# --- Global variable for the block catalog ---
# --- Global variable for the block catalog ---
ALL_SCRATCH_BLOCKS_CATALOG = {}
# BLOCK_CATALOG_PATH = r"blocks\blocks.json" # Define the path to your JSON file
# HAT_BLOCKS_PATH = r"blocks\hat_blocks.json" # Path to the hat blocks JSON file
# STACK_BLOCKS_PATH = r"blocks\stack_blocks.json" # Path to the stack blocks JSON file
# REPORTER_BLOCKS_PATH = r"blocks\reporter_blocks.json" # Path to the reporter blocks JSON file
# BOOLEAN_BLOCKS_PATH = r"blocks\boolean_blocks.json" # Path to the boolean blocks JSON file
# C_BLOCKS_PATH = r"blocks\c_blocks.json" # Path to the C blocks JSON file
# CAP_BLOCKS_PATH = r"blocks\cap_blocks.json" # Path to the cap blocks JSON file

# BLOCK_CATALOG_PATH = r"blocks/blocks.json" 
# HAT_BLOCKS_PATH = r"blocks/hat_blocks.json" 
# STACK_BLOCKS_PATH = r"blocks/stack_blocks.json" 
# REPORTER_BLOCKS_PATH = r"blocks/reporter_blocks.json" 
# BOOLEAN_BLOCKS_PATH = r"blocks/boolean_blocks.json" 
# C_BLOCKS_PATH = r"blocks/c_blocks.json" 
# CAP_BLOCKS_PATH = r"blocks/cap_blocks.json" 

BLOCK_CATALOG_PATH = "blocks" # Define the path to your JSON file
HAT_BLOCKS_PATH = "hat_blocks" # Path to the hat blocks JSON file
STACK_BLOCKS_PATH = "stack_blocks" # Path to the stack blocks JSON file
REPORTER_BLOCKS_PATH = "reporter_blocks" # Path to the reporter blocks JSON file
BOOLEAN_BLOCKS_PATH = "boolean_blocks" # Path to the boolean blocks JSON file
C_BLOCKS_PATH = "c_blocks" # Path to the C blocks JSON file
CAP_BLOCKS_PATH = "cap_blocks" # Path to the cap blocks JSON file

# Load the block catalogs from their respective JSON files
hat_block_data = _load_block_catalog(HAT_BLOCKS_PATH)
# hat_description = hat_block_data["description"]
hat_description = hat_block_data.get("description", "No description available")
# hat_opcodes_functionalities = "\n".join([f"    - Opcode: {block['op_code']}, functionality: {block['functionality']} example: standalone use: {block['example_standalone']}" for block in hat_block_data["blocks"]])
hat_opcodes_functionalities = "\n".join([
    f"    - Opcode: {block.get('op_code', 'N/A')}, functionality: {block.get('functionality', 'N/A')}, example: standalone use {block.get('example_standalone', 'N/A')}"
    for block in hat_block_data.get("blocks", [])
]) if isinstance(hat_block_data.get("blocks"), list) else "    No blocks information available."
print("Hat blocks loaded successfully.", hat_description)

boolean_block_data = _load_block_catalog(BOOLEAN_BLOCKS_PATH)
boolean_description = boolean_block_data["description"]
# boolean_opcodes_functionalities = "\n".join([f"    - Opcode: {block['op_code']}, functionality: {block['functionality']} example: standalone use: {block['example_standalone']}" for block in boolean_block_data["blocks"]])
boolean_opcodes_functionalities = "\n".join([
    f"    - Opcode: {block.get('op_code', 'N/A')}, functionality: {block.get('functionality', 'N/A')}, example: standalone use {block.get('example_standalone', 'N/A')}"
    for block in boolean_block_data.get("blocks", [])
]) if isinstance(boolean_block_data.get("blocks"), list) else "    No blocks information available."

c_block_data = _load_block_catalog(C_BLOCKS_PATH)
c_description = c_block_data["description"]
# c_opcodes_functionalities = "\n".join([f"    - Opcode: {block['op_code']}, functionality: {block['functionality']} example: standalone use: {block['example_standalone']}" for block in c_block_data["blocks"]])
c_opcodes_functionalities = "\n".join([
    f"    - Opcode: {block.get('op_code', 'N/A')}, functionality: {block.get('functionality', 'N/A')}, example: standalone use {block.get('example_standalone', 'N/A')}"
    for block in c_block_data.get("blocks", [])
]) if isinstance(c_block_data.get("blocks"), list) else "    No blocks information available."

cap_block_data = _load_block_catalog(CAP_BLOCKS_PATH)
cap_description = cap_block_data["description"]                                                                                                                                                                                                                                                                                                                                                                                                                                                      
# cap_opcodes_functionalities = "\n".join([f"    - Opcode: {block['op_code']}, functionality: {block['functionality']} example: standalone use: {block['example_standalone']}" for block in cap_block_data["blocks"]])
cap_opcodes_functionalities = "\n".join([
    f"    - Opcode: {block.get('op_code', 'N/A')}, functionality: {block.get('functionality', 'N/A')}, example: standalone use {block.get('example_standalone', 'N/A')}"
    for block in cap_block_data.get("blocks", [])
]) if isinstance(cap_block_data.get("blocks"), list) else "    No blocks information available."

reporter_block_data = _load_block_catalog(REPORTER_BLOCKS_PATH)
reporter_description = reporter_block_data["description"]
# reporter_opcodes_functionalities = "\n".join([f"    - Opcode: {block['op_code']}, functionality: {block['functionality']} example: standalone use: {block['example_standalone']}" for block in reporter_block_data["blocks"]])
reporter_opcodes_functionalities = "\n".join([
    f"    - Opcode: {block.get('op_code', 'N/A')}, functionality: {block.get('functionality', 'N/A')}, example: standalone use {block.get('example_standalone', 'N/A')}"
    for block in reporter_block_data.get("blocks", [])
]) if isinstance(reporter_block_data.get("blocks"), list) else "    No blocks information available."

stack_block_data = _load_block_catalog(STACK_BLOCKS_PATH)
stack_description = stack_block_data["description"]
# stack_opcodes_functionalities = "\n".join([f"    - Opcode: {block['op_code']}, functionality: {block['functionality']} example: standalone use: {block['example_standalone']}" for block in stack_block_data["blocks"]])
stack_opcodes_functionalities = "\n".join([
    f"    - Opcode: {block.get('op_code', 'N/A')}, functionality: {block.get('functionality', 'N/A')}, example: standalone use {block.get('example_standalone', 'N/A')}"
    for block in stack_block_data.get("blocks", [])
]) if isinstance(stack_block_data.get("blocks"), list) else "    No blocks information available."

# This makes ALL_SCRATCH_BLOCKS_CATALOG available globally
ALL_SCRATCH_BLOCKS_CATALOG = _load_block_catalog(BLOCK_CATALOG_PATH)

# Helper function to extract JSON from LLM response
def extract_json_from_llm_response(raw_response: str) -> dict:
    # --- 1) Pull out the JSON code‑block if present ---
    md = re.search(r"```(?:json)?\s*([\s\S]*?)\s*```", raw_response)
    json_string = md.group(1).strip() if md else raw_response

    # --- 2) Trim to the outermost { … } so we drop any prefix/suffix junk ---
    first, last = json_string.find('{'), json_string.rfind('}')
    if 0 <= first < last:
        json_string = json_string[first:last+1]

    # --- 3) PRE‑CLEANUP: remove stray assistant{…}, rogue assistant keys, fix boolean quotes ---
    json_string = re.sub(r'\b\w+\s*{', '{', json_string)
    json_string = re.sub(r'"assistant"\s*:', '', json_string)
    json_string = re.sub(r'\b(false|true)"', r'\1', json_string)
    logger.debug("Ran pre‑cleanup for stray tokens and boolean quotes.")

    # --- 3.1) Fix stray inner quotes at start of name/list values ---
    # e.g., { "name": " \"recent_scoress\"", ... } → "recent_scoress"
    json_string = re.sub(
        r'("name"\s*:\s*")\s*"',
        r'\1',
        json_string
    )

    # --- 4) Escape all embedded quotes in any `logic` value up to the next key ---
    def _esc(m):
        prefix, body = m.group(1), m.group(2)
        return prefix + body.replace('"', r'\"')
    json_string = re.sub(
        r'("logic"\s*:\s*")([\s\S]+?)(?=",\s*"[A-Za-z_]\w*"\s*:\s*)',
        _esc,
        json_string
    )
    logger.debug("Escaped embedded quotes in logic fields.")

    logger.debug("Quoted unquoted keys.")

    # --- 6) Remove trailing commas before } or ] ---
    json_string = re.sub(r',\s*(?=[}\],])', '', json_string)
    json_string = re.sub(r',\s*,', ',', json_string)
    logger.debug("Removed trailing commas.")

    # --- 7) Balance braces: drop extra } at end if needed ---
    ob, cb = json_string.count('{'), json_string.count('}')
    if cb > ob:
        excess = cb - ob
        json_string = json_string.rstrip()[:-excess]
        logger.debug(f"Stripped {excess} extra closing brace(s).")

    # --- 8) Escape literal newlines in *all* string values ---
    json_string = re.sub(
        r'"((?:[^"\\]|\\.)*?)"',
        lambda m: '"' + m.group(1).replace('\n', '\\n').replace('\r', '\\r') + '"',
        json_string,
        flags=re.DOTALL
    )
    logger.debug("Escaped newlines in strings.")

    # --- 9) Final parse attempt ---
    try:
        return json.loads(json_string)
    except json.JSONDecodeError:
        logger.error("Sanitized JSON still invalid:\n%s", json_string)
        raise

# Node 1: Logic updating if any issue here
def pseudo_generator_node(state: GameState):
    logger.info("--- Running plan_logic_aligner_node ---")
    image = state.get("project_image", "")  
    project_json = state["project_json"]
    
    # MODIFICATION 1: Include 'Stage' in the list of names to plan for.
    # It's crucial to ensure 'Stage' is always present for its global role.
    target_names = [t["name"] for t in project_json["targets"]]
    
    refinement_prompt = f"""
You are an expert in Scratch 3.0 game development, specializing in understanding block relationships (stacked, nested).
"Analyze the Scratch code-block image and generate Pseudo-Code for what this logic appears to be doing."
From Image, you also have to detect a value of Key given in Text form "Script for: ". Below is the example
Example: "Script for: Bear", "Script for:" is a key and "Bear" is value and check if there is related target name available.

**Targets in Game (Sprites and Stage) available in project_json:** {', '.join(target_names)}

--- Scratch 3.0 Block Reference ---
    ### Hat Blocks
    Description: {hat_description}
    Blocks:
    {hat_opcodes_functionalities}

    ### Boolean Blocks
    Description: {boolean_description}
    Blocks:
    {boolean_opcodes_functionalities}

    ### C Blocks
    Description: {c_description}
    Blocks:
    {c_opcodes_functionalities}

    ### Cap Blocks
    Description: {cap_description}
    Blocks:
    {cap_opcodes_functionalities}

    ### Reporter Blocks
    Description: {reporter_description}
    Blocks:
    {reporter_opcodes_functionalities}

    ### Stack Blocks
    Description: {stack_description}
    Blocks:
    {stack_opcodes_functionalities}
-----------------------------------

Your task is to:
If you don't find any "Code-Blocks" then,
    **Don't generate Pseudo Code, and pass the message "No Code-blocks" 
If you find any "Code-Blocks" then, 
1. **Refine the 'logic'**: Make it precise, accurate, and fully aligned with the Game Description. Use Scratch‑consistent verbs and phrasing. **Do NOT** use raw double‑quotes inside the logic string.

2. **Structural requirements**:
   - **Numeric values** `(e.g., 0, 5, 0.2, -130)` **must** be in parentheses: `(0)`, `(5)`, `(0.2)`, `(-130)`.
   - **AlphaNumeric values** `(e.g., hello, say 5, 4, hi!)` **must** be in parentheses: `(hello)`, `(say 5)`, `(4)`, `(hi!)`.
   - **Variables** must be in the form `[variable v]` (e.g., `[score v]`), even when used inside expressions two example use `set [score v] to (1)` or `show variable ([speed v])`.
   - **Dropdown options** must be in the form `[option v]` (e.g., `[Game Start v]`, `[blue sky v]`). example use `when [space v] key pressed`.
   - **Reporter blocks** used as inputs must be double‑wrapped: `((x position))`, `((y position))`. example use `if <((y position)) = (-130)> then` or `(((x position)) * (1))`.
   - **Boolean blocks** in conditions must be inside `< >`, including nested ones: `<not <condition>>`, `<<cond1> and <cond2>>`,`<<cond1> or <cond2>>`.
   - **Other Boolean blocks** in conditions must be inside `< >`, including nested ones or values or variables: `<(block/value/variable) * (block/value/variable)>`,`<(block/value/variable) < (block/value/variable)>`, and example of another variable`<[apple v] contains [a v]?>`.
   - **Operator expressions** must use explicit Scratch operator blocks, e.g.:
     ```
     (([ballSpeed v]) * (1.1))
     ```
   - **Every hat block script must end** with a final `end` on its own line.
   
3. **Pseudo‑code formatting**:
   - Represent each block or nested block on its own line.
   - Indent nested blocks by 4 spaces under their parent (`forever`, `if`, etc.).
   - No comments or explanatory text—just the block sequence.
   - a natural language breakdown of each step taken after the event, formatted as a multi-line string representing pseudo-code. Ensure clarity and granularity—each described action should map closely to a Scratch block or tight sequence. 

4. **Logic content**:
   - Build clear flow for mechanics (movement, jumping, flying, scoring, collisions).
   - Match each action closely to a Scratch block or tight sequence.
   - Do **NOT** include any justification or comments—only the raw logic.

5. **Examples for reference**:  
**Correct** pattern for a simple start script:
   ```
   when green flag clicked
   switch backdrop to [blue sky v]
   set [score v] to (0)
   show variable [score v]
   broadcast [Game Start v]
   end
   ```
**Correct** pattern for updating the high score variable handling:
   ```
   when I receive [Game Over v]
   if <((score)) > (([High Score v]))> then
   set [High Score v] to ([score v])
   end
   switch backdrop to [Game Over v]
   end
   ```
**Correct** pattern for level up and increase difficulty use:
   ```
   when I receive [Level Up v]
   change [level v] by (1)
   set [ballSpeed v] to ((([ballSpeed v]) * (1.1)))
   end
   ```
**Correct** pattern for jumping mechanics use:
   ```
   when [space v] key pressed
   if <((y position)) = (-100)> then
   repeat (5)
   change y by (100)
   wait (0.1) seconds
   change y by (-100)
   wait (0.1) seconds
   end
   end
   end
   ```
**Correct** pattern for continuos moving objects use:
   ```
   when green flag clicked
   go to x: (240) y: (-100)
   set [speed v] to (-5)
   show variable [speed v]
   forever
   change x by ([speed v])
   if <((x position)) < (-240)> then
   go to x: (240) y: (-100) 
   end
   end
   end
   ```
**Correct** pattern for continuos moving objects use:
   ```
   when green flag clicked
   go to x: (240) y: (-100)
   set [speed v] to (-5)
   show variable [speed v]
   forever
   change x by ([speed v])
   if <((x position)) < (-240)> then
   go to x: (240) y: (-100) 
   end
   end
   end
   ```
6. **Donot** add any explaination of logic or comments to justify or explain just put the logic content in the json.
7. **Output**:  
    Return **only** a JSON object, using double quotes everywhere:
    ```json
    {{
    "refined_logic":{{
        "name_variable": 'Value of "Sript for: "',
        "pseudocode":"…your fully‑formatted pseudo‑code here…",
            }}
    }}
    ```
    """
    image_input = {
        "type": "image_url",
        "image_url": {
            "url": f"data:image/png;base64,{image}"
        }
    }

    content = [
        {"type": "text", "text": refinement_prompt},
        image_input
    ]

    try:
        # Invoke the main agent for logic refinement and relationship identification
        response = agent.invoke({"messages": [{"role": "user", "content": content}]})
        llm_output_raw = response["messages"][-1].content.strip()
        print(f"llm_output_raw: {response}")
        parsed_llm_output = extract_json_from_llm_response(llm_output_raw)        
        result = parsed_llm_output           
        print(f"result:\n\n {result}")
        
    except json.JSONDecodeError as error_json:
        # If JSON parsing fails, use the json resolver agent
        correction_prompt = (
            "Your task is to correct the provided JSON string to ensure it is **syntactically perfect and adheres strictly to JSON rules**.\n"
            "It must be a JSON object with `refined_logic` (string) and `block_relationships` (array of objects).\n"
            f"- **Error Details**: {error_json}\n\n"
            "**Strict Instructions for your response:**\n"
            "1. **ONLY** output the corrected JSON. Do not include any other text or explanations.\n"
            "2. Ensure all keys and string values are enclosed in **double quotes**. Escape internal quotes (`\\`).\n"
            "3. No trailing commas. Correct nesting.\n\n"
            "Here is the problematic JSON string to correct:\n"
            f"```json\n{llm_output_raw}\n```\n"
            "Corrected JSON:\n"
        )
        try:
            correction_response = agent_json_resolver.invoke({"messages": [{"role": "user", "content": correction_prompt}]})
            corrected_output = extract_json_from_llm_response(correction_response['messages'][-1].content)
            #block_relationships = corrected_output.get("block_relationships", [])
            result = corrected_output 
            print(f"result:\n\n {result}")                   
        except Exception as e_corr:
            logger.error(f"Failed to correct JSON output for even after retry: {e_corr}")
            
            
    # Update the original action_plan in the state with the refined version
    state["pseudo_code"] = result
    
    # with open("debug_state.json", "w", encoding="utf-8") as f:
    #     json.dump(state, f, indent=2, ensure_ascii=False)
    print(f"[OVREALL REFINED PSEUDO CODE LOGIC]: {result}")
    logger.info("Plan refinement and block relation analysis completed for all plans.")
    return state

def overall_planner_node(state: GameState):
    """
    Generates a comprehensive action plan for sprites, including detailed Scratch block information.
    This node acts as an overall planner, leveraging knowledge of all block shapes and categories.
    """
    logger.info("--- Running OverallPlannerNode ---")

    project_json = state["project_json"]
    raw = state.get("pseudo_code", {})
    refined_logic_data = raw.get("refined_logic", {})
    sprite_name = refined_logic_data.get("name_variable", "<unknown>")
    pseudo      = refined_logic_data.get("pseudocode", "")

    # MODIFICATION 1: Include 'Stage' in the list of names to plan for.
    # It's crucial to ensure 'Stage' is always present for its global role.
    target_names = [t["name"] for t in project_json["targets"]]

    # MODIFICATION 2: Get sprite positions, providing default for Stage as it doesn't have x,y
    sprite_positions = {}
    for target in project_json["targets"]:
        if not target["isStage"]:
            sprite_positions[target["name"]] = {"x": target.get("x", 0), "y": target.get("y", 0)}
        else:
            sprite_positions[target["name"]] = {"x": "N/A", "y": "N/A"} # Stage doesn't have positional coordinates

    # declaration_plan = state["declaration_plan"]

    planning_prompt = f"""
Generate a detailed action plan for the game's sprites and stage based on the given pseudo-code and sprite details for the given sprite name and .

Description: 
    **Sprite_name**: {sprite_name} 
    **and its corresponding Pseudo_code:** 
    '{pseudo}'

[Note: Make sure you just refine the pseudo code by correting mistake and adding the missing opcode if any and *Do not* generate any new logic]
----
**Targets in Game (Sprites and Stage) available in project_json:** {', '.join(target_names)}

--- Scratch 3.0 Block Reference ---
This section provides a comprehensive reference of Scratch 3.0 blocks, categorized by shape, including their opcodes and functional descriptions. Use this to accurately identify block types and behavior.

### Hat Blocks
Description: {hat_description}
Blocks:
{hat_opcodes_functionalities}

### Boolean Blocks
Description: {boolean_description}
Blocks:
{boolean_opcodes_functionalities}

### C Blocks
Description: {c_description}
Blocks:
{c_opcodes_functionalities}

### Cap Blocks
Description: {cap_description}
Blocks:
{cap_opcodes_functionalities}

### Reporter Blocks
Description: {reporter_description}
Blocks:
{reporter_opcodes_functionalities}

### Stack Blocks
Description: {stack_description}
Blocks:
{stack_opcodes_functionalities}

-----------------------------------

Your task is to  use the `Sprite_name` given and `Pseudo_code` and add it to the specific target name and define the primary actions and movements.
The output should be a JSON object with a single key 'action_overall_flow'. Each key inside this object should be a sprite or 'Stage' name (e.g., 'Player', 'Enemy', 'Stage'), and its value must include a 'description' and a list of 'plans'.
Each plan must include a **single Scratch Hat Block** (e.g., 'event_whenflagclicked') to start scratch project and should contain:
1. **'event'**: the exact `opcode` of the hat block that initiates the logic.
[NOTE: INSTRUCTIONN TO FOLLOW IF PSEUDO_CODE HAVING PROBLEM ]
2. **'logic'**: a natural language breakdown of each step taken after the event, formatted as a multi-line string representing pseudo-code. Ensure clarity and granularity—each described action should map closely to a Scratch block or tight sequence.
    - Use 'forever: ...' or 'repeat(10): ...' to prefix repeating logic suitable taking reference from the C blocks.
    - Use Scratch-consistent verbs: 'move', 'change', 'wait', 'hide', 'show', 'say', 'glide', etc.
    - **Numeric values** `(e.g., 0, 5, 0.2, -130)` **must** be in parentheses: `(0)`, `(5)`, `(0.2)`, `(-130)`.
   - **AlphaNumeric values** `(e.g., hello, say 5, 4, hi!)` **must** be in parentheses: `(hello)`, `(say 5)`, `(4)`, `(hi!)`.
   - **Variables** must be in the form `[variable v]` (e.g., `[score v]`), even when used inside expressions two example use `set [score v] to (1)` or `show variable ([speed v])`.
   - **Dropdown options** must be in the form `[option v]` (e.g., `[Game Start v]`, `[blue sky v]`). example use `when [space v] key pressed`.
   - **Reporter blocks** used as inputs must be double‑wrapped: `((x position))`, `((y position))`. example use `if <((y position)) = (-130)> then` or `(((x position)) * (1))`.
   - **Boolean blocks** in conditions must be inside `< >`, including nested ones: `<not <condition>>`, `<<cond1> and <cond2>>`,`<<cond1> or <cond2>>`.
   - **Other Boolean blocks** in conditions must be inside `< >`, including nested ones or values or variables: `<(block/value/variable) * (block/value/variable)>`,`<(block/value/variable) < (block/value/variable)>`, and example of another variable`<[apple v] contains [a v]?>`.
   - **Operator expressions** must use explicit Scratch operator blocks, e.g.:
     ```
     (([ballSpeed v]) * (1.1))
     ```
   - **Every hat block script must end** with a final `end` on its own line.
3. **Opcode Lists**: include relevant Scratch opcodes grouped under `motion`, `control`, `operator`, `sensing`, `looks`, `sounds`, `events`, and `data`. List only the non-empty categories. Use exact opcodes.
4. Few Example of content of logics inside for a specific plan as scratch pseudo-code:
    - example 1[continues moving objects]:
    ```
    when green flag clicked
    go to x: (240) y: (-100)
    set [speed v] to (-5)
    show variable [speed v]
    forever
    change x by ([speed v])
    if <((x position)) < (-240)> then 
    go to x: (240) y: (-100) 
    end
    end
    end
    ```
    - example 2[jumping script of an plan]: 
    ```    
    when [space v] key pressed
    if <((y position)) = (-100)> then 
    repeat (5)
    change y by (100) 
    wait (0.1) seconds
    change y by (-100) 
    wait (0.1) seconds
    end
    end
    end
    ```
   - example 3 [pattern for level up and increase difficulty]:
   ```
   when I receive [Level Up v]
   change [level v] by (1)
   set [ballSpeed v] to ((([ballSpeed v]) * (1.1)))
   end
   ```
5. Use target names exactly as listed in `Targets in Game`. Do NOT rename or invent new targets.
6. Ensure the plan reflects accurate opcode usage derived strictly from the block reference above.
7. Few shot Example structure for 'action_overall_flow':
```json
{{
    "action_overall_flow": {{
        "Stage": {{
            "description": "Background and global game state management, including broadcasts, rewards, and score.",
            "plans": [
                {{
                    "event": "event_whenflagclicked",
                    "logic": "when green flag clicked\n    switch backdrop to [backdrop1 v]\n    set [score v] to 0\n    show variable [score v]\n    broadcast [Game Start v]",
                    "motion": [],
                    "control": [],
                    "operator": [],
                    "sensing": [],
                    "looks": [
                        "looks_switchbackdropto"
                    ],
                    "sounds": [],
                    "events": [
                        "event_broadcast"
                    ],
                    "data": [
                        "data_setvariableto",
                        "data_showvariable"
                    ]
                }},
                {{
                    "event": "event_whenbroadcastreceived",
                    "logic": "when I receive [Game Over v]\n    if <(score) > (High Score)> then\n        set [High Score v] to (score)\n    end\n    switch backdrop to [HighScore v]",
                    "motion": [],
                    "control": [
                        "control_if"
                    ],
                    "operator": [
                        "operator_gt"
                    ],
                    "sensing": [],
                    "looks": [
                        "looks_switchbackdropto"
                    ],
                    "sounds": [],
                    "events": [],
                    "data": [
                        "data_setvariableto"
                    ]
                }}
            ]
        }},
        "Sprite1": {{
            "description": "Main character (cat) actions",
            "plans": [
                {{
                    "event": "event_whenflagclicked",
                    "logic": "when green flag clicked\n    go to x: 240 y: -100\n    end\n.",
                    "motion": [
                        "motion_gotoxy"
                    ],
                    "control": [],
                    "operator": [],
                    "sensing": [],
                    "looks": [],
                    "sounds": [],
                    "events": [],
                    "data": []
                }},
                {{
                    "event": "event_whenkeypressed",
                    "logic": "when [space v] key pressed\n    repeat (10)\n        change y by (20)\n        wait (0.1) seconds\n        change y by (-20)\n    end",
                    "motion": [
                        "motion_changeyby"
                    ],
                    "control": [
                        "control_repeat",
                        "control_wait"
                    ],
                    "operator": [],
                    "sensing": [],
                    "looks": [],
                    "sounds": [],
                    "events": [],
                    "data": []
                }}
            ]
        }},
        "soccer ball": {{
            "description": "Obstacle movement and interaction",
            "plans": [
                {{
                    "event": "event_whenflagclicked",
                    "logic": "when green flag clicked\n    go to x: 240 y: -135\n    forever\n        glide 2 seconds to x: -240 y: -135\n        if <(x position) < -235> then\n            set x to 240\n        end\n        if <touching [Sprite1 v]?> then\n            broadcast [Game Over v]\n            stop [all v]\n        end\n    end",
                    "motion": [
                        "motion_gotoxy",
                        "motion_glidesecstoxy",
                        "motion_xposition",
                        "motion_setx"
                    ],
                    "control": [
                        "control_forever",
                        "control_if",
                        "control_stop"
                    ],
                    "operator": [
                        "operator_lt"
                    ],
                    "sensing": [
                        "sensing_istouching",
                        "sensing_touchingobjectmenu"
                    ],
                    "looks": [],
                    "sounds": [],
                    "events": [
                        "event_broadcast"
                    ],
                    "data": []
                }}
            ]
        }}

    }}
}}
```
8.  Based on the provided context, generate the `action_overall_flow`.
    - Maintain the **exact JSON structure** shown above.
    - All `logic` fields must be **clear and granular**.
    - Only include opcode categories that contain relevant opcodes.
    - Ensure that each opcode matches its intended Scratch functionality.
    - If feedback suggests major change, **rethink the entire plan** for the affected sprite(s).
    - If feedback is minor, make precise, minimal improvements only.
"""

    try:
        response = agent.invoke({"messages": [{"role": "user", "content": planning_prompt}]})
        print("Raw response from LLM [OverallPlannerNode 1]:",response)
        raw_response = response["messages"][-1].content#strip_noise(response["messages"][-1].content)
        print("Raw response from LLM [OverallPlannerNode 2]:", raw_response) # Uncomment for debugging
        # json debugging and solving
        try:
            overall_plan = extract_json_from_llm_response(raw_response)
        except json.JSONDecodeError as error_json:
            logger.error("Failed to extract JSON from LLM response. Attempting to correct the response.")
            # Use the JSON resolver agent to fix the response
            correction_prompt = (
                "Your task is to correct the provided JSON string to ensure it is **syntactically perfect and adheres strictly to JSON rules**.\n"
                "Carefully review the JSON for any errors, especially focusing on the reported error at:\n"
                f"- **Error Details**: {error_json}\n\n"
                "**Strict Instructions for your response:**\n"
                "1. **ONLY** output the corrected JSON. Do not include any other text, comments, or explanations outside the JSON.\n"
                "2. Ensure all property names (keys) are enclosed in **double quotes**.\n"
                "3. Ensure string values are correctly enclosed in **double quotes** and any internal special characters (like newlines `\\n`, tabs `\\t`, backslashes `\\\\`, or double quotes `\\`) are properly **escaped**.\n"
                "4. Verify that there are **no extra commas**, especially between key-value pairs or after the last element in an object or array.\n"
                "5. Ensure proper nesting and matching of curly braces `{}` and square brackets `[]`.\n"
                "6. **Crucially, remove any extraneous characters or duplicate closing braces outside the main JSON object.**\n"
                "7. The corrected JSON must be a **complete and valid** JSON object.\n\n"
                "Here is the problematic JSON string to correct:\n"
                "```json\n"
                f"{raw_response}\n"
                "```\n"
                "Corrected JSON:\n"
            )
            correction_response = agent_json_resolver.invoke({"messages": [{"role": "user", "content": correction_prompt}]})
            print(f"[JSON CORRECTOR RESPONSE AT OVERALLPLANNERNODE ]: {correction_response['messages'][-1].content}")
            overall_plan= extract_json_from_llm_response(correction_response['messages'][-1].content)#strip_noise(correction_response["messages"][-1].content))
            
        state["action_plan"] = overall_plan
        logger.info("Overall plan generated by OverallPlannerNode.")
        
        # with open("debug_state.json", "w", encoding="utf-8") as f:
        #     json.dump(state, f, indent=2, ensure_ascii=False)
            
        return state
            
    except Exception as e:
        logger.error(f"Error in OverallPlannerNode: {e}")
        raise

def refined_planner_node(state: GameState):
    """
    Refines the action plan based on validation feedback and game description.
    """
    logger.info("--- Running RefinedPlannerNode ---")
    raw = state.get("pseudo_code", {})
    refined_logic_data = raw.get("refined_logic", {})
    sprite_name = refined_logic_data.get("name_variable", "<unknown>")
    pseudo      = refined_logic_data.get("pseudocode", "")
    #detailed_game_description = state.get("detailed_game_description", state.get("description", "A game."))
    current_action_plan = state.get("action_plan", {})
    print(f"[current_action_plan before refinement] on ({state.get('iteration_count', 0)}): {json.dumps(current_action_plan, indent=2)}")
    plan_validation_feedback = state.get("plan_validation_feedback", "No specific feedback provided. Assume general refinement is needed.")
    project_json = state["project_json"]
    target_names = [t["name"] for t in project_json["targets"]]

    # MODIFICATION 2: Get sprite positions, providing default for Stage as it doesn't have x,y
    sprite_positions = {}
    for target in project_json["targets"]:
        if not target["isStage"]:
            sprite_positions[target["name"]] = {"x": target.get("x", 0), "y": target.get("y", 0)}
        else:
            sprite_positions[target["name"]] = {"x": "N/A", "y": "N/A"} # Stage doesn't have positional coordinates

    #declaration_plan = state["declaration_plan"]

    refinement_prompt = f"""
Refine and correct the JSON object `action_overall_flow` so that it fully aligns with the detailed game description, sprite positions, variable/broadcast declarations, and Scratch 3.0 block reference—while also validating for common formatting or opcode errors.

Here is the overall script available:
**Sprite name**: {sprite_name} 
**and its corresponding Pseudo_code:** 
'{pseudo}'

[Note: Make sure you just refine the pseudo code by correting mistake and adding the missing opcode if any and *Do not* generate any new logic]
---
**Targets in Game (Sprites and Stage):** {', '.join(target_names)}  
**Current action plan:**  
{current_action_plan}

**Validation Feedback:**  
'{plan_validation_feedback}'

--- Scratch 3.0 Block Reference ---
### Hat Blocks
{hat_opcodes_functionalities}

### Boolean Blocks
{boolean_opcodes_functionalities}

### C Blocks
{c_opcodes_functionalities}

### Cap Blocks
{cap_opcodes_functionalities}

### Reporter Blocks
{reporter_opcodes_functionalities}

### Stack Blocks
{stack_opcodes_functionalities}

-----------------------------------

* **Your task is to align to description, refine and correct the JSON object 'action_overall_flow'.**
Use sprite names exactly as provided in `sprite_names` (e.g., 'Sprite1', 'soccer ball'); and also the stage, do **NOT** rename them.
1.  **'event'**: the exact `opcode` of the hat block that initiates the logic.
2. **'logic'**: a natural language breakdown of each step taken after the event, formatted as a multi-line string representing pseudo-code. Ensure clarity and granularity—each described action should map closely to a Scratch block or tight sequence.
    - Do **NOT** include any justification or comments—only the raw logic.
    - Use 'forever: ...' or 'repeat(10): ...' to prefix repeating logic suitable taking reference from the C blocks.
    - Use Scratch-consistent verbs: 'move', 'change', 'wait', 'hide', 'show', 'say', 'glide', etc.
    - **Numeric values** `(e.g., 0, 5, 0.2, -130)` **must** be in parentheses: `(0)`, `(5)`, `(0.2)`, `(-130)`.
   - **AlphaNumeric values** `(e.g., hello, say 5, 4, hi!)` **must** be in parentheses: `(hello)`, `(say 5)`, `(4)`, `(hi!)`.
   - **Variables** must be in the form `[variable v]` (e.g., `[score v]`), even when used inside expressions two example use `set [score v] to (1)` or `show variable ([speed v])`.
   - **Dropdown options** must be in the form `[option v]` (e.g., `[Game Start v]`, `[blue sky v]`). example use `when [space v] key pressed`.
   - **Reporter blocks** used as inputs must be double‑wrapped: `((x position))`, `((y position))`. example use `if <((y position)) = (-130)> then` or `(((x position)) * (1))`.
   - **Boolean blocks** in conditions must be inside `< >`, including nested ones: `<not <condition>>`, `<<cond1> and <cond2>>`,`<<cond1> or <cond2>>`.
   - **Other Boolean blocks** in conditions must be inside `< >`, including nested ones or values or variables: `<(block/value/variable) * (block/value/variable)>`,`<(block/value/variable) < (block/value/variable)>`, and example of another variable`<[apple v] contains [a v]?>`.
   - **Operator expressions** must use explicit Scratch operator blocks, e.g.:
     ```
     (([ballSpeed v]) * (1.1))
     ```
   - **Every hat block script must end** with a final `end` on its own line.
3. **Validation & Formatting Checks**  
   - **Opcode Coverage**: Ensure every action in `logic` has a matching opcode in the lists.  
   - **Bracket Nesting**: Confirm every `(` has a matching `)`, e.g., `(pick random (100) to (-100))`.  
   - **Operator Formatting**: Validate that operators use Scratch operator blocks, not inline math.  
   - **Common Errors**:  
     - `pick random (100,-100)` → `(pick random (100) to (-100))`  
     - Missing `end` at script conclusion  
     - Unwrapped reporter inputs or Boolean tests
4. **Opcode Lists**: include relevant Scratch opcodes grouped under `motion`, `control`, `operator`, `sensing`, `looks`, `sounds`, `events`, and `data`. List only the non-empty categories. Use exact opcodes .
5. Few Example of content of logics inside for a specific plan as scratch pseudo-code:
    - example 1[continues moving objects]:
    ```
    when green flag clicked
    go to x: (240) y: (-100)
    set [speed v] to (-5)
    show variable [speed v]
    forever
    change x by ([speed v])
    if <((x position)) < (-240)> then 
    go to x: (240) y: (-100) 
    end
    end
    end
    ```
    - example 2[jumping script of an plan]: 
    ```    
    when [space v] key pressed
    if <((y position)) = (-100)> then 
    repeat (5)
    change y by (100) 
    wait (0.1) seconds
    change y by (-100) 
    wait (0.1) seconds
    end
    end
    end
    ```
   - example 3 [pattern for level up and increase difficulty]:
   ```
   when I receive [Level Up v]
   change [level v] by (1)
   set [ballSpeed v] to ((([ballSpeed v]) * (1.1)))
   end
   ```
6. Use target names exactly as listed in `Targets in Game`. Do NOT rename or invent new targets.
7. Ensure the plan reflects accurate opcode usage derived strictly from the block reference above.
8. Few shot Example structure for 'action_overall_flow':
```json
    {{
    "action_overall_flow": {{
        "Stage": {{
            "description": "Background and global game state management, including broadcasts, rewards, and score.",
            "plans": [
                {{
                    "event": "event_whenflagclicked",
                    "logic": "when green flag clicked\n    switch backdrop to [backdrop1 v]\n    set [score v] to 0\n    show variable [score v]\n    broadcast [Game Start v]",
                    "motion": [],
                    "control": [],
                    "operator": [],
                    "sensing": [],
                    "looks": [
                        "looks_switchbackdropto"
                    ],
                    "sounds": [],
                    "events": [
                        "event_broadcast"
                    ],
                    "data": [
                        "data_setvariableto",
                        "data_showvariable"
                    ]
                }},
                {{
                    "event": "event_whenbroadcastreceived",
                    "logic": "when I receive [Game Over v]\n    if <(score) > (High Score)> then\n        set [High Score v] to (score)\n    end\n    switch backdrop to [HighScore v]",
                    "motion": [],
                    "control": [
                        "control_if"
                    ],
                    "operator": [
                        "operator_gt"
                    ],
                    "sensing": [],
                    "looks": [
                        "looks_switchbackdropto"
                    ],
                    "sounds": [],
                    "events": [],
                    "data": [
                        "data_setvariableto"
                    ]
                }}
            ]
        }},
        "Sprite1": {{
            "description": "Main character (cat) actions",
            "plans": [
                {{
                    "event": "event_whenflagclicked",
                    "logic": "when green flag clicked\n    go to x: 240 y: -100\n    end\n.",
                    "motion": [
                        "motion_gotoxy"
                    ],
                    "control": [],
                    "operator": [],
                    "sensing": [],
                    "looks": [],
                    "sounds": [],
                    "events": [],
                    "data": []
                }},
                {{
                    "event": "event_whenkeypressed",
                    "logic": "when [space v] key pressed\n    repeat (10)\n        change y by (20)\n        wait (0.1) seconds\n        change y by (-20)\n    end",
                    "motion": [
                        "motion_changeyby"
                    ],
                    "control": [
                        "control_repeat",
                        "control_wait"
                    ],
                    "operator": [],
                    "sensing": [],
                    "looks": [],
                    "sounds": [],
                    "events": [],
                    "data": []
                }}
            ]
        }},
        "soccer ball": {{
            "description": "Obstacle movement and interaction",
            "plans": [
                {{
                    "event": "event_whenflagclicked",
                    "logic": "when green flag clicked\n    go to x: 240 y: -135\n    forever\n        glide 2 seconds to x: -240 y: -135\n        if <(x position) < -235> then\n            set x to 240\n        end\n        if <touching [Sprite1 v]?> then\n            broadcast [Game Over v]\n            stop [all v]\n        end\n    end",
                    "motion": [
                        "motion_gotoxy",
                        "motion_glidesecstoxy",
                        "motion_xposition",
                        "motion_setx"
                    ],
                    "control": [
                        "control_forever",
                        "control_if",
                        "control_stop"
                    ],
                    "operator": [
                        "operator_lt"
                    ],
                    "sensing": [
                        "sensing_istouching",
                        "sensing_touchingobjectmenu"
                    ],
                    "looks": [],
                    "sounds": [],
                    "events": [
                        "event_broadcast"
                    ],
                    "data": []
                }}
            ]
        }}
    }}
}}
```
9. Use the validation feedback to address errors, fill in missing logic, or enhance clarity.
    example of few possible improvements: 1.event_whenflagclicked is used to control sprite but its used for actual start scratch project and reset scratch. 2. looping like forever used where we should use iterative. 3. missing of for variable we used in the block
    - Maintain the **exact JSON structure** shown above.
    - All `logic` fields must be **clear and granular**.
    - Only include opcode categories that contain relevant opcodes.
    - Ensure that each opcode matches its intended Scratch functionality.
    - If feedback suggests major change, **rethink the entire plan** for the affected sprite(s).
    - If feedback is minor, make precise, minimal improvements only.
"""
    try:
        response = agent.invoke({"messages": [{"role": "user", "content": refinement_prompt}]})
        raw_response = response["messages"][-1].content#strip_noise(response["messages"][-1].content)
        logger.info(f"Raw response from LLM [RefinedPlannerNode]: {raw_response[:500]}...")
        # json debugging and solving
        try:
            refined_plan = extract_json_from_llm_response(raw_response)
        except json.JSONDecodeError as error_json:
            logger.error("Failed to extract JSON from LLM response. Attempting to correct the response.")
            # Use the JSON resolver agent to fix the response
            correction_prompt = (
                "Your task is to correct the provided JSON string to ensure it is **syntactically perfect and adheres strictly to JSON rules**.\n"
                "Carefully review the JSON for any errors, especially focusing on the reported error at:\n"
                f"- **Error Details**: {error_json}\n\n"
                "**Strict Instructions for your response:**\n"
                "1. **ONLY** output the corrected JSON. Do not include any other text, comments, or explanations outside the JSON.\n"
                "2. Ensure all property names (keys) are enclosed in **double quotes**.\n"
                "3. Ensure string values are correctly enclosed in **double quotes** and any internal special characters (like newlines `\\n`, tabs `\\t`, backslashes `\\\\`, or double quotes `\\`) are properly **escaped**.\n"
                "4. IN `logic` field make sure content enclosed in **double quotes** should not have invalid **double quotes**, **eliminate** all quotes inside the content if any. "
                "4. Verify that there are **no extra commas**, especially between key-value pairs or after the last element in an object or array.\n"
                "5. Ensure proper nesting and matching of curly braces `{}` and square brackets `[]`.\n"
                "6. **Crucially, remove any extraneous characters or duplicate closing braces outside the main JSON object.**\n" # Added instruction
                "7. The corrected JSON must be a **complete and valid** JSON object.\n\n"
                "Here is the problematic JSON string to correct:\n"
                "```json\n"
                f"{raw_response}\n"
                "```\n"
                "Corrected JSON:\n"
            )
            correction_response = agent_json_resolver.invoke({"messages": [{"role": "user", "content": correction_prompt}]})
            print(f"[JSON CORRECTOR RESPONSE AT REFINEPLANNER ]: {correction_response['messages'][-1].content}")
            refined_plan = extract_json_from_llm_response(correction_response["messages"][-1].content)#strip_noise(correction_response["messages"][-1].content))
            logger.info("Refined plan corrected by JSON resolver agent.")
            
        if refined_plan:
            #state["action_plan"] = refined_plan.get("action_overall_flow", {}) # Update to the key 'action_overall_flow' [error]
            state["action_plan"] = refined_plan #.get("action_overall_flow", {})  # Update the main the prompt includes updated only
            logger.info("Action plan refined by RefinedPlannerNode.")
        else:
            logger.warning("RefinedPlannerNode did not return a valid 'action_overall_flow' structure. Keeping previous plan.")
        print("[Refined Action Plan]:", json.dumps(state["action_plan"], indent=2))
        #print("[current state after refinement]:", json.dumps(state, indent=2))
        
        # with open("debug_state.json", "w", encoding="utf-8") as f:
        #     json.dump(state, f, indent=2, ensure_ascii=False)
        
        return state
    except Exception as e:
        logger.error(f"Error in RefinedPlannerNode: {e}")
        raise

def plan_opcode_counter_node(state: Dict[str, Any]) -> Dict[str, Any]:
    """
    For each plan in state["action_plan"], calls the LLM agent
    to analyze the `logic` string and return a list of {opcode, count} for each category.
    """
    logger.info("=== Running OPCODE COUTER LOGIC with LLM counts ===")
    #game_description = state.get("description", "No game description provided.")
    sprite_name = {}
    project_json_targets = state.get("project_json", {}).get("targets", [])
    for target in project_json_targets:
        sprite_name[target["name"]] = target["name"]
    
    action_flow = state.get("action_plan", {}) 
    
    if action_flow.get("action_overall_flow", {}) == {}:
        plan_data = action_flow.items()
    else:
        plan_data = action_flow.get("action_overall_flow", {}).items()
    
    refined_flow: Dict[str, Any] = {}
    for sprite, sprite_data in plan_data:
        refined_plans = []
        for plan in sprite_data.get("plans", []):
            logic = plan.get("logic", "")
            event = plan.get("event", "")
            
            # These are for guiding the LLM, not for the final output format directly
            opcodes_from_plan = {
                "motion": plan.get("motion", []),
                "control": plan.get("control", []),
                "operator": plan.get("operator", []),
                "sensing": plan.get("sensing", []),
                "looks": plan.get("looks", []),
                "sounds": plan.get("sounds", []),
                "events": plan.get("events", []) + ([event] if isinstance(event, str) else []),
                "data": plan.get("data", []),
            }

            refinement_prompt = f"""
You are a Scratch 3.0 expert with deep knowledge of block types, nesting and stack relationships.
Your job: read the plan logic below and decide exactly which blocks (and how many of each) are required to implement it.
Review the following plan for '{sprite}' triggered by '{event}'.
--- Scratch 3.0 Block Reference ---
    ### Hat Blocks
    Description: {hat_description}
    Blocks:
    {hat_opcodes_functionalities}

    ### Boolean Blocks
    Description: {boolean_description}
    Blocks:
    {boolean_opcodes_functionalities}

    ### C Blocks
    Description: {c_description}
    Blocks:
    {c_opcodes_functionalities}

    ### Cap Blocks
    Description: {cap_description}
    Blocks:
    {cap_opcodes_functionalities}

    ### Reporter Blocks
    Description: {reporter_description}
    Blocks:
    {reporter_opcodes_functionalities}

    ### Stack Blocks
    Description: {stack_description}
    Blocks:
    {stack_opcodes_functionalities}
-----------------------------------
Current Plan Details:
- Event (Hat Block Opcode): {event}
- Associated Opcodes by Category: {json.dumps(opcodes_from_plan, indent=2)}

── Game Context ──
Sprite: "{sprite}"

── Current Plan ──
Event (hat block): {event}
Logic (pseudo-Scratch): {logic}
Plan : {plan}

── Opcode Candidates ──
Motion:   {opcodes_from_plan["motion"]}
Control:  {opcodes_from_plan["control"]}
Operator: {opcodes_from_plan["operator"]}
Sensing:  {opcodes_from_plan["sensing"]}
Looks:    {opcodes_from_plan["looks"]}
Sounds:   {opcodes_from_plan["sounds"]}
Events:   {opcodes_from_plan["events"]}
Data:     {opcodes_from_plan["data"]}

── Your Task ──
1. Analyze the “Logic” steps and choose exactly which opcodes are needed.
2. Return a top-level JSON object with a single key: "opcode_counts".
3. The value of "opcode_counts" should be a list of objects, where each object has "opcode": "<opcode_name>" and "count": <integer>.
4. Ensure the list includes the hat block for this plan (e.g., event_whenflagclicked, event_whenkeypressed, event_whenbroadcastreceived) with a count of 1.
5. The order of opcodes within the "opcode_counts" list does not matter.
6. If any plan logic is None do not generate the opcode_counts for it.
7. Use only double quotes and ensure valid JSON.

Example output:
**example 1**
```json    
{{
"opcode_counts":[
    {{"opcode":"motion_gotoxy","count":1}},
    {{"opcode":"control_forever","count":1}},
    {{"opcode":"control_if","count":1}},
    {{"opcode":"looks_switchbackdropto","count":1}},
    {{"opcode":"event_whenflagclicked","count":1}},
    {{"opcode":"event_broadcast","count":1}},
    {{"opcode":"data_setvariableto","count":2}},
    {{"opcode":"data_showvariable","count":2}}
    ]        
}}    
```
**example 2**
```json    
{{        
"opcode_counts":[
    {{"opcode":"motion_gotoxy","count":1}},
    {{"opcode":"motion_glidesecstoxy","count":1}},
    {{"opcode":"motion_xposition","count":1}},
    {{"opcode":"motion_setx","count":1}},
    {{"opcode":"control_forever","count":1}},
    {{"opcode":"control_if","count":2}},
    {{"opcode":"operator_lt","count":1}},
    {{"opcode":"sensing_istouching","count":1}},
    {{"opcode":"event_whenflagclicked","count":1}},
    {{"opcode":"event_broadcast","count":1}}
    ]
}}
```
"""                                    
            try:
                response = agent.invoke({"messages": [{"role": "user", "content": refinement_prompt}]})
                llm_output = response["messages"][-1].content
                llm_json = extract_json_from_llm_response(llm_output)                 
                logger.info(f"Successfully analyze the opcode requirement for {sprite} - {event}.")

            except json.JSONDecodeError as error_json:
                logger.error(f"JSON Decode Error for {sprite} - {event}: {error_json}. Attempting correction.")
                correction_prompt = (
                    "Your task is to correct the provided JSON string to ensure it is **syntactically perfect and adheres strictly to JSON rules**.\n"
                    "It must be a JSON object with a single key `opcode_counts` containing a list of objects like {{'opcode': '<opcode_name>', 'count': <integer>}}.\n"
                    f"- **Error Details**: {error_json}\n\n"
                    "**Strict Instructions for your response:**\n"
                    "1. **ONLY** output the corrected JSON. Do not include any other text or explanations.\n"
                    "2. Ensure all keys and string values are enclosed in **double quotes**. Escape internal quotes (`\\`).\n"
                    "3. No trailing commas. Correct nesting.\n\n"
                    "Here is the problematic JSON string to correct:\n"
                    f"```json\n{llm_output}\n```\n"
                    "Corrected JSON:\n"
                )
                try:
                    correction_response = agent_json_resolver.invoke({"messages": [{"role": "user", "content": correction_prompt}]})
                    llm_json = extract_json_from_llm_response(correction_response["messages"][-1].content)
                    logger.info(f"Successfully corrected JSON output for {sprite} - {event}.")
                except Exception as e_corr:
                    logger.error(f"Failed to correct JSON output for {sprite} - {event} even after retry: {e_corr}")
                    continue 

            # Directly use the 'opcode_counts' list from the LLM's output
            plan["opcode_counts"] = llm_json.get("opcode_counts", [])
            
            # Optionally, you can remove the individual category lists from the plan
            # if they are no longer needed after the LLM provides the consolidated list.
            # for key in ["motion", "control", "operator", "sensing", "looks", "sounds", "events", "data"]:
            #     if key in plan:
            #         del plan[key]

            refined_plans.append(plan)

        refined_flow[sprite] = {
            "description": sprite_data.get("description", ""),
            "plans": refined_plans
        }
    
    if refined_flow:
        state["action_plan"] = refined_flow
        logger.info("logic aligned by logic_aligner_Node.")
        
    state["temporary_node"] = refined_flow
    #state["temporary_node"] = refined_flow
    print(f"[OPCODE COUTER LOGIC]: {refined_flow}")
    logger.info("=== OPCODE COUTER LOGIC completed ===")
    return state

# Node 10:Function based block builder node
# def overall_block_builder_node_2(state: dict):
#     logger.info("--- Running OverallBlockBuilderNode ---")

#     project_json = state["project_json"]
#     targets = project_json["targets"]
#     # --- Sprite and Stage Target Mapping ---
#     sprite_map = {target["name"]: target for target in targets if not target["isStage"]}
#     stage_target = next((target for target in targets if target["isStage"]), None)
#     if stage_target:
#         sprite_map[stage_target["name"]] = stage_target

#     action_plan = state.get("action_plan", {})
#     print("[Overall Action Plan received at the block generator]:", json.dumps(action_plan, indent=2))
#     if not action_plan:
#         logger.warning("No action plan found in state. Skipping OverallBlockBuilderNode.")
#         return state

#     # Initialize offsets for script placement on the Scratch canvas
#     script_y_offset = {}
#     script_x_offset_per_sprite = {name: 0 for name in sprite_map.keys()}

#     # This handles potential variations in the action_plan structure.
#     if action_plan.get("action_overall_flow", {}) == {}:
#         plan_data = action_plan.items()
#     else:
#         plan_data = action_plan.get("action_overall_flow", {}).items()

#     # --- Extract global project context for LLM ---
#     all_sprite_names = list(sprite_map.keys())
#     all_variable_names = {}
#     all_list_names = {}
#     all_broadcast_messages = {}

#     for target in targets:
#         for var_id, var_info in target.get("variables", {}).items():
#             all_variable_names[var_info[0]] = var_id  # Store name -> ID mapping (e.g., "myVariable": "myVarId123")
#         for list_id, list_info in target.get("lists", {}).items():
#             all_list_names[list_info[0]] = list_id  # Store name -> ID mapping
#         for broadcast_id, broadcast_name in target.get("broadcasts", {}).items():
#             all_broadcast_messages[broadcast_name] = broadcast_id  # Store name -> ID mapping

#     # --- Process each sprite's action plan ---
#     for sprite_name, sprite_actions_data in plan_data:
#         if sprite_name in sprite_map:
#             current_sprite_target = sprite_map[sprite_name]
#             if "blocks" not in current_sprite_target:
#                 current_sprite_target["blocks"] = {}

#             if sprite_name not in script_y_offset:
#                 script_y_offset[sprite_name] = 0

#             for plan_entry in sprite_actions_data.get("plans", []):
#                 logic_sequence = str(plan_entry["logic"])
#                 opcode_counts = plan_entry.get("opcode_counts", {})

#                 try:
#                     generated_blocks=block_builder(opcode_counts,logic_sequence)                
#                     if "blocks" in generated_blocks and isinstance(generated_blocks["blocks"], dict):
#                         logger.warning(f"LLM returned nested 'blocks' key for {sprite_name}. Unwrapping.")
#                         generated_blocks = generated_blocks["blocks"]

#                     # Update block positions for top-level script
#                     for block_id, block_data in generated_blocks.items():
#                         if block_data.get("topLevel"):
#                             block_data["x"] = script_x_offset_per_sprite.get(sprite_name, 0)
#                             block_data["y"] = script_y_offset[sprite_name]
#                             script_y_offset[sprite_name] += 150 # Increment for next script

#                     current_sprite_target["blocks"].update(generated_blocks)
#                     print(f"[current_sprite_target block updated]: {current_sprite_target['blocks']}")
#                     state["iteration_count"] = 0
#                     logger.info(f"Action blocks added for sprite '{sprite_name}' by OverallBlockBuilderNode.")
#                 except Exception as e:
#                     logger.error(f"Error generating blocks for sprite '{sprite_name}': {e}")
                    
#     state["project_json"] = project_json
#     # with open("debug_state.json", "w", encoding="utf-8") as f:
#     #     json.dump(state, f, indent=2, ensure_ascii=False)
    
#     return state
# Node 10:Function based block builder node
def overall_block_builder_node_2(state: dict):
    logger.info("--- Running OverallBlockBuilderNode ---")

    project_json = state["project_json"]
    targets = project_json["targets"]
    # --- Sprite and Stage Target Mapping ---
    sprite_map = {target["name"]: target for target in targets if not target["isStage"]}
    stage_target = next((target for target in targets if target["isStage"]), None)
    if stage_target:
        sprite_map[stage_target["name"]] = stage_target

    action_plan = state.get("action_plan", {})
    print("[Overall Action Plan received at the block generator]:", json.dumps(action_plan, indent=2))
    if not action_plan:
        logger.warning("No action plan found in state. Skipping OverallBlockBuilderNode.")
        return state

    # Initialize offsets for script placement on the Scratch canvas
    script_y_offset = {}
    script_x_offset_per_sprite = {name: 0 for name in sprite_map.keys()}

    # This handles potential variations in the action_plan structure.
    if action_plan.get("action_overall_flow", {}) == {}:
        plan_data = action_plan.items()
    else:
        plan_data = action_plan.get("action_overall_flow", {}).items()

    # --- Extract global project context for LLM ---
    all_sprite_names = list(sprite_map.keys())
    all_variable_names = {}
    all_list_names = {}
    all_broadcast_messages = {}

    for target in targets:
        for var_id, var_info in target.get("variables", {}).items():
            all_variable_names[var_info[0]] = var_id  # Store name -> ID mapping (e.g., "myVariable": "myVarId123")
        for list_id, list_info in target.get("lists", {}).items():
            all_list_names[list_info[0]] = list_id  # Store name -> ID mapping
        for broadcast_id, broadcast_name in target.get("broadcasts", {}).items():
            all_broadcast_messages[broadcast_name] = broadcast_id  # Store name -> ID mapping

    # --- Process each sprite's action plan ---
    for sprite_name, sprite_actions_data in plan_data:
        if sprite_name in sprite_map:
            current_sprite_target = sprite_map[sprite_name]
            if "blocks" not in current_sprite_target:
                current_sprite_target["blocks"] = {}

            if sprite_name not in script_y_offset:
                script_y_offset[sprite_name] = 0

            for plan_entry in sprite_actions_data.get("plans", []):
                logic_sequence = str(plan_entry["logic"])
                opcode_counts = plan_entry.get("opcode_counts", {})

                try:
                    generated_blocks = block_builder(opcode_counts, logic_sequence)
                    
                    # Ensure generated_blocks is a dictionary
                    if not isinstance(generated_blocks, dict):
                        logger.error(f"block_builder for sprite '{sprite_name}' returned non-dict type: {type(generated_blocks)}. Skipping block update.")
                        continue # Skip to next plan_entry if output is not a dictionary

                    if "blocks" in generated_blocks and isinstance(generated_blocks["blocks"], dict):
                        logger.warning(f"LLM returned nested 'blocks' key for {sprite_name}. Unwrapping.")
                        generated_blocks = generated_blocks["blocks"]

                    # Update block positions for top-level script
                    for block_id, block_data in generated_blocks.items():
                        if block_data.get("topLevel"):
                            block_data["x"] = script_x_offset_per_sprite.get(sprite_name, 0)
                            block_data["y"] = script_y_offset[sprite_name]
                            script_y_offset[sprite_name] += 150 # Increment for next script

                    current_sprite_target["blocks"].update(generated_blocks)
                    print(f"[current_sprite_target block updated]: {current_sprite_target['blocks']}")
                    state["iteration_count"] = 0
                    logger.info(f"Action blocks added for sprite '{sprite_name}' by OverallBlockBuilderNode.")
                except Exception as e:
                    logger.error(f"Error generating blocks for sprite '{sprite_name}': {e}")
                    # Consider adding more specific error handling here if a malformed output
                    # from block_builder should cause a specific state change, but generally
                    # avoid nulling the entire project_json.
                    
    state["project_json"] = project_json
    # with open("debug_state.json", "w", encoding="utf-8") as f:
    #     json.dump(state, f, indent=2, ensure_ascii=False)
    
    return state

# # Node 11: Variable adder node
def variable_adder_node(state: GameState):
    project_json = state["project_json"]
    try:
        updated_project_json = variable_adder_main(project_json)
        state["project_json"]=updated_project_json
        return state
    except Exception as e:
        logger.error(f"Error in variable adder node while updating project_json': {e}")
        raise


scratch_keywords = [
                    "move", "turn", "wait", "repeat", "if", "else", "broadcast",
                    "glide", "change", "forever", "when", "switch",
                    "next costume", "set", "show", "hide", "play sound",
                    "go to", "x position", "y position", "think", "say",
                    "variable", "stop", "clone",
                    "touching", "sensing", "pen", "clear","Scratch","Code","scratch blocks"
                ]

#def extract_images_from_pdf(pdf_path: Path, json_base_dir: Path, image_base_dir: Path):
#def extract_images_from_pdf(pdf_path: Path, json_base_dir: Path):
def extract_images_from_pdf(pdf_path: Path):
    ''' Extract images from PDF and generate structured sprite JSON '''
    try:
        pdf_path = Path(pdf_path)
        pdf_filename = pdf_path.stem               # e.g., "scratch_crab"
        pdf_dir_path = str(pdf_path.parent).replace("/", "\\")
        print("-------------------------------pdf_filename-------------------------------",pdf_filename)
        print("-------------------------------pdf_dir_path-------------------------------",pdf_dir_path)
        # Create subfolders under the provided base directories
        # This will create paths like:
        # /app/detected_images/pdf_filename/
        # /app/json_data/pdf_filename/
        extracted_image_subdir = DETECTED_IMAGE_DIR / pdf_filename
        json_subdir = JSON_DIR / pdf_filename
        extracted_image_subdir.mkdir(parents=True, exist_ok=True)
        json_subdir.mkdir(parents=True, exist_ok=True)
        print("-------------------------------extracted_image_subdir-------------------------------",extracted_image_subdir)
        print("-------------------------------json_subdir-------------------------------",json_subdir)
        # Output paths (now using Path objects directly)
        output_json_path = json_subdir / "extracted.json"
        final_json_path = json_subdir / "extracted_sprites.json" # Path to extracted_sprites.json
        final_json_path_2 = json_subdir / "extracted_sprites_2.json"
        print("-------------------------------output_json_path-------------------------------",output_json_path)
        print("-------------------------------final_json_path-------------------------------",final_json_path)
        print("-------------------------------final_json_path_2-------------------------------",final_json_path_2)
        
        try:
            elements = partition_pdf(
                filename=str(pdf_path), # partition_pdf might expect a string
                strategy="hi_res",
                extract_image_block_types=["Image"],
                extract_image_block_to_payload=True,
            )
        except Exception as e:
            raise RuntimeError(
                f"❌ Failed to extract images from PDF: {str(e)}")

        try:
            with open(output_json_path, "w") as f:
                json.dump([element.to_dict()
                          for element in elements], f, indent=4)
        except Exception as e:
            raise RuntimeError(f"❌ Failed to write extracted.json: {str(e)}")

        try:
            # Display extracted images
            with open(output_json_path, 'r') as file:
                file_elements = json.load(file)
        except Exception as e:
            raise RuntimeError(f"❌ Failed to read extracted.json: {str(e)}")

        # Prepare manipulated sprite JSON structure
        manipulated_json = {}

        # SET A SYSTEM PROMPT
        system_prompt = """
            You are an expert in visual scene understanding.
            Your Job is to analyze an image and respond acoording if asked for name give simple name by analyzing it and if ask for descrption generate a short description covering its elements.
            
            Guidelines:
            - Focus only the images given in Square Shape.
            - Don't Consider Blank areas in Image as.
            - Don't include generic summary or explanation outside the fields.
            Return only string.
            """
        agent = create_react_agent(
            model=llm,
            tools=[],
            prompt=system_prompt
        )

        # If JSON already exists, load it and find the next available Sprite number
        if final_json_path.exists(): # Use Path.exists()
            with open(final_json_path, "r") as existing_file:
                manipulated = json.load(existing_file)
            # Determine the next available index (e.g., Sprite 4 if 1–3 already exist)
            existing_keys = [int(k.replace("Sprite ", ""))
                             for k in manipulated.keys()]
            start_count = max(existing_keys, default=0) + 1
        else:
            start_count = 1

        sprite_count = start_count
        for i, element in enumerate(file_elements):
            if "image_base64" in element["metadata"]:
                try:
                    image_data = base64.b64decode(
                        element["metadata"]["image_base64"])
                    image = Image.open(BytesIO(image_data)).convert("RGB") # Use BytesIO here
                    
                    image = upscale_image(image, scale=2)
                    # image.show(title=f"Extracted Image {i+1}")
                    
                    # MODIFIED: Store image directly to BytesIO to avoid saving to disk if not needed
                    # and then converting back to base64.
                    img_buffer = BytesIO()
                    image.save(img_buffer, format="PNG")
                    img_bytes = img_buffer.getvalue()
                    img_base64 = base64.b64encode(img_bytes).decode("utf-8")

                    # Optionally save image to disk if desired for debugging/permanent storage
                    image_path = extracted_image_subdir / f"Sprite_{i+1}.png"
                    image.save(image_path)
                    
                    prompt_combined = """
                    Analyze this image and return JSON with keys:# modify prompt for "name", if it detects "code-blocks only then give name as 'scratch-block'"
                    {
                    "name": "<short name or 'scratch blocks'>" ,
                    "description": "<short description>"
                    }
                    Guidelines:
                    - If image contains logical/code blocks from Scratch (e.g., move, turn, repeat, when clicked, etc.), use 'scratch-block' as the name.
                    - If image is a character, object, or backdrop, give an appropriate descriptive name instead.
                    - Avoid generic names like 'image1' or 'picture'.
                    - Keep the response strictly in JSON format.
                    """
                    
                    content = [
                        {"type": "text", "text": prompt_combined},
                        {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img_base64}"}}
                    ]
                    
                    response = agent.invoke({"messages": [{"role": "user", "content": content}]})
                    
                    # Ensure response is handled correctly, it might be a string that needs json.loads
                    try:
                        # Assuming the agent returns a dictionary with 'messages' key,
                        # and the last message's content is the JSON string.
                        response_content_str = response.get("messages", [])[-1].content
                        result_json = json.loads(response_content_str)
                    except (json.JSONDecodeError, IndexError, AttributeError) as e:
                        logger.error(f"⚠️ Failed to parse agent response as JSON: {e}. Response was: {response}", exc_info=True)
                        result_json = {} # Default to empty dict if parsing fails

                    try:
                        name = result_json.get("name", "").strip()
                        description = result_json.get("description", "").strip()
                    except Exception as e:
                        logger.error(f"⚠️ Failed to extract name/description from result_json: {str(e)}", exc_info=True)
                        name = "unknown"
                        description = "unknown"                    

                    manipulated_json[f"Sprite {sprite_count}"] = {
                        "name": name,
                        "base64": element["metadata"]["image_base64"],
                        "file-path": pdf_dir_path,
                        "description": description
                    }
                    sprite_count += 1
                except Exception as e:
                    logger.error(f"⚠️ Error processing Sprite {i+1}: {str(e)}", exc_info=True)
                    
        # Save manipulated JSON
        with open(final_json_path, "w") as sprite_file:
            json.dump(manipulated_json, sprite_file, indent=4)
        
        def is_code_block(name: str) -> bool:
            for kw in scratch_keywords:
                if kw.lower() in name.lower():
                    return True
            return False

        # Filter out code block images
        filtered_sprites = {}
        for key, value in manipulated_json.items():
            sprite_name = value.get("name", "")
            if not is_code_block(sprite_name):
                filtered_sprites[key] = value
            else:
                logger.info(f"🛑 Excluded code block-like image: {key}")

        # Overwrite with filtered content
        with open(final_json_path_2, "w") as sprite_file:
            json.dump(filtered_sprites, sprite_file, indent=4)
        
        # MODIFIED RETURN VALUE: Return the Path to the primary extracted_sprites.json file
        # and the directory where it's located.
        return final_json_path, json_subdir # Return the file path and its parent directory
    except Exception as e:
        raise RuntimeError(f"❌ Error in extract_images_from_pdf: {str(e)}")

def similarity_matching(input_json_path: str, project_folder: str) -> str:
    logger.info("🔍 Running similarity matching…")
    os.makedirs(project_folder, exist_ok=True)

    # ----------------------------------------
    # CHANGED: define normalized base-paths so startswith() checks work
    backdrop_base_path = os.path.normpath(str(BACKDROP_DIR))
    sprite_base_path   = os.path.normpath(str(SPRITE_DIR))
    # ----------------------------------------

    project_json_path = os.path.join(project_folder, "project.json")

    # ==============================
    #    READ SPRITE METADATA
    # ==============================
    with open(input_json_path, 'r') as f:
        sprites_data = json.load(f)

    sprite_ids, texts, sprite_base64 = [], [], []
    for sid, sprite in sprites_data.items():
        sprite_ids.append(sid)
        texts.append("This is " + sprite.get("description", sprite.get("name", "")))
        sprite_base64.append(sprite["base64"])

    # =========================================
    #  Build the list of all candidate images
    # =========================================
    folder_image_paths = [
        # backdrops
        BACKDROP_DIR / "badroom3.sb3"   / "8cc0b88d53345b3e337e8f028a32a4e7.png",
        BACKDROP_DIR / "baseball2.sb3"  / "7be1f5b3e682813dac1f297e52ff7dca.png",
        BACKDROP_DIR / "beach_malibu.sb3" / "050615fe992a00d6af0e664e497ebf53.png",
        BACKDROP_DIR / "castle2.sb3"    / "951765ee7f7370f120c9df20b577c22f.png",
        BACKDROP_DIR / "hall.sb3"       / "ea86ca30b346f27ca5faf1254f6a31e3.png",
        BACKDROP_DIR / "jungle.sb3"     / "f4f908da19e2753f3ed679d7b37650ca.png",
        # sprites
        SPRITE_DIR   / "Batter.sprite3" / "baseball_sprite_motion_1.png",
        SPRITE_DIR   / "Bear.sprite3"   / "bear_motion_2.png",
        SPRITE_DIR   / "Beetle.sprite3" / "46d0dfd4ae7e9bfe3a6a2e35a4905eae.png",
        SPRITE_DIR   / "cat"            / "cat_motion_1.png",
        SPRITE_DIR   / "Centaur.sprite3" / "2373556e776cad3ba4d6ee04fc34550b.png",
        SPRITE_DIR   / "Crab.sprite3"   / "bear_element.png",
        SPRITE_DIR   / "Soccer Ball.sprite3" / "cat_football.png",
    ]
    folder_image_paths = [os.path.normpath(str(p)) for p in folder_image_paths]
    # =========================================

    # -----------------------------------------
    #  Load reference embeddings from JSON
    # -----------------------------------------
    with open(f"{BLOCKS_DIR}/embeddings.json", "r") as f:
        embedding_json = json.load(f)
    img_matrix = np.array([img["embeddings"] for img in embedding_json])

    # =========================================
    #  Decode & embed each sprite image
    # =========================================
    sprite_features = []
    for b64 in sprite_base64:
        if "," in b64:
            b64 = b64.split(",", 1)[1]
        img_bytes = base64.b64decode(b64)
        pil_img = Image.open(BytesIO(img_bytes)).convert("RGB")
        buf = BytesIO()
        pil_img.save(buf, format="PNG")
        buf.seek(0)
        feats = clip_embd.embed_image([buf])[0]
        sprite_features.append(feats)
    sprite_matrix = np.vstack(sprite_features)

    # =========================================
    #  Compute similarities & pick best match
    # =========================================
    similarity = np.matmul(sprite_matrix, img_matrix.T)
    most_similar_indices = np.argmax(similarity, axis=1)

    # =========================================
    #  Copy matched sprite assets + collect data
    # =========================================
    project_data   = []
    copied_folders = set()

    for sprite_idx, matched_idx in enumerate(most_similar_indices):
        matched_image_path = folder_image_paths[matched_idx]
        matched_folder     = os.path.dirname(matched_image_path)

        # CHANGED: use our new normalized sprite_base_path
        if not matched_folder.startswith(sprite_base_path):
            continue

        if matched_folder in copied_folders:
            continue
        copied_folders.add(matched_folder)
        logger.info(f"Matched sprite: {matched_image_path}")

        sprite_json_path = os.path.join(matched_folder, 'sprite.json')
        if not os.path.exists(sprite_json_path):
            logger.warning(f"No sprite.json in {matched_folder}")
            continue

        with open(sprite_json_path, 'r') as f:
            sprite_info = json.load(f)
        # copy all non‐matched files
        for fname in os.listdir(matched_folder):
            if fname in (os.path.basename(matched_image_path), 'sprite.json'):
                continue
            shutil.copy2(os.path.join(matched_folder, fname),
                         os.path.join(project_folder, fname))
        project_data.append(sprite_info)

    # =========================================
    #  Copy matched backdrop assets + collect
    # =========================================
    backdrop_data = []

    for backdrop_idx, matched_idx in enumerate(most_similar_indices):
        matched_image_path = folder_image_paths[matched_idx]
        matched_folder     = os.path.dirname(matched_image_path)

        # CHANGED: use our new normalized backdrop_base_path
        if not matched_folder.startswith(backdrop_base_path):
            continue

        logger.info(f"Matched backdrop: {matched_image_path}")
        # copy non‐matched files
        for fname in os.listdir(matched_folder):
            if fname in (os.path.basename(matched_image_path), 'project.json'):
                continue
            shutil.copy2(os.path.join(matched_folder, fname),
                         os.path.join(project_folder, fname))

        # append the stage‐target from its project.json
        pj = os.path.join(matched_folder, 'project.json')
        if os.path.exists(pj):
            with open(pj, 'r') as f:
                bd_json = json.load(f)
            for tgt in bd_json.get("targets", []):
                if tgt.get("isStage"):
                    backdrop_data.append(tgt)
        else:
            logger.warning(f"No project.json in {matched_folder}")

    # =========================================
    #  Merge into final Scratch project.json
    # =========================================
    final_project = {
        "targets": [], "monitors": [], "extensions": [],
        "meta": {
            "semver": "3.0.0",
            "vm": "11.3.0",
            "agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
        }
    }
    # sprites first
    for spr in project_data:
        if not spr.get("isStage", False):
            final_project["targets"].append(spr)

    # then backdrop as the Stage
    if backdrop_data:
        all_costumes, sounds = [], []
        for i, bd in enumerate(backdrop_data):
            all_costumes.extend(bd.get("costumes", []))
            if i == 0:
                sounds = bd.get("sounds", [])
        stage_obj={
            "isStage": True,
            "name": "Stage",
            "objName": "Stage",
            "variables": {}, 
            "lists": {}, 
            "broadcasts": {},
            "blocks": {}, 
            "comments": {},
            "currentCostume": 1 if len(all_costumes) > 1 else 0,
            "costumes": all_costumes,
            "sounds": sounds,
            "volume": 100, 
            "layerOrder": 0,
            "tempo": 60, 
            "videoTransparency": 50,
            "videoState": "on",
            "textToSpeechLanguage": None
        }
        final_project["targets"].insert(0, stage_obj)

    with open(project_json_path, 'w') as f:
        json.dump(final_project, f, indent=2)

    return project_json_path
    # for sprite_idx, matched_idx in enumerate(most_similar_indices):
    #     matched_image_path = folder_image_paths[matched_idx]
    #     matched_image_path = os.path.normpath(matched_image_path)
    #     print(" --------------------------------------1- matched_image_path ---------------------------------------",matched_image_path)
    #     matched_folder = os.path.dirname(matched_image_path)
    #     #folder_name = os.path.basename(matched_folder)
    #     print(" --------------------------------------1- matched_folder ---------------------------------------",matched_folder)
    #     if matched_folder in copied_folders:
    #         continue
    #     copied_folders.add(matched_folder)
    #     logger.info(f"Matched image path: {matched_image_path}")

    #     sprite_json_path = os.path.join(matched_folder, 'sprite.json')
    #     print(" --------------------------------------- sprite_json_path ---------------------------------------",sprite_json_path)
    #     if not os.path.exists(sprite_json_path):
    #         logger.warning(f"sprite.json not found in: {matched_folder}")
    #         continue

    #     with open(sprite_json_path, 'r') as f:
    #         sprite_data = json.load(f)
    #         # print(f"SPRITE DATA: \n{sprite_data}")
    #     # # Copy only non-matched files
    #     # for fname in os.listdir(matched_folder):
    #     #     fpath = os.path.join(matched_folder, fname)
    #     #     if os.path.isfile(fpath) and fname not in {os.path.basename(matched_image_path), 'sprite.json'}:
    #     #         shutil.copy2(fpath, os.path.join(project_folder, fname))
    #     #         # logger.info(f"Copied Sprite asset: {fname}")
    #     project_data.append(sprite_data)
    #     print(" --------------------------------------1- project_data ---------------------------------------",project_data)
    #     for fname in os.listdir(matched_folder):
    #         fpath = os.path.join(matched_folder, fname)
    #         dest_path = os.path.join(project_folder, fname)
    #         if os.path.isfile(fpath) and fname not in {os.path.basename(matched_image_path), 'sprite.json'}:
    #             shutil.copy2(fpath, dest_path)
    #             logger.info(f"🟢 Copied Sprite Asset: {fpath} → {dest_path}")
        
    # # ================================================================== #
    # #   Loop through most similar images from Backdrops folder           #
    # #   → Copy Backdrop assets (excluding matched image + project.json)  #
    # #   → Load project.json and append its data to project_data          #
    # # ================================================================== #
    # backdrop_data = []  # for backdrop-related entries

    # for backdrop_idx, matched_idx in enumerate(most_similar_indices):
    #     matched_image_path = os.path.normpath(folder_image_paths[matched_idx])
    #     print(" --------------------------------------2- matched_image_path ---------------------------------------",matched_image_path)
    #     # Check if the match is from the Backdrops folder
    #     if matched_image_path.startswith(os.path.normpath(backdrop_images_path)):
    #         matched_folder = os.path.dirname(matched_image_path)
    #         print(" --------------------------------------2- matched_folder ---------------------------------------",matched_folder)
    #         folder_name = os.path.basename(matched_folder)

    #         logger.info(f"Backdrop matched image: {matched_image_path}")

    #         # Copy only non-matched files
    #         # for fname in os.listdir(matched_folder):
    #         #     fpath = os.path.join(matched_folder, fname)
    #         #     if os.path.isfile(fpath) and fname not in {os.path.basename(matched_image_path), 'project.json'}:
    #         #         shutil.copy2(fpath, os.path.join(project_folder, fname))
    #         #         # logger.info(f"Copied Backdrop asset: {fname}")
    #         for fname in os.listdir(matched_folder):
    #             fpath = os.path.join(matched_folder, fname)
    #             dest_path = os.path.join(project_folder, fname)
    #             if os.path.isfile(fpath) and fname not in {os.path.basename(matched_image_path), 'project.json'}:
    #                 shutil.copy2(fpath, dest_path)
    #                 logger.info(f"🟡 Copied Backdrop Asset: {fpath} → {dest_path}")


    #         # Append backdrop's project.json
    #         backdrop_json_path = os.path.join(matched_folder, 'project.json')
    #         print(" --------------------------------------2- backdrop_json_path ---------------------------------------",backdrop_json_path)
    #         if os.path.exists(backdrop_json_path):
    #             with open(backdrop_json_path, 'r') as f:
    #                 backdrop_json_data = json.load(f)
    #                 # print(f"SPRITE DATA: \n{backdrop_json_data}")
    #             if "targets" in backdrop_json_data:
    #                 for target in backdrop_json_data["targets"]:
    #                     if target.get("isStage") == True:
    #                         backdrop_data.append(target)
    #         else:
    #             logger.warning(f"project.json not found in: {matched_folder}")

    # # Merge JSON structure
    # final_project = {
    #     "targets": [],
    #     "monitors": [],
    #     "extensions": [],
    #     "meta": {
    #         "semver": "3.0.0",
    #         "vm": "11.3.0",
    #         "agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
    #     }
    # }

    # for sprite in project_data:
    #     if not sprite.get("isStage", False):
    #         final_project["targets"].append(sprite)

    # if backdrop_data:
    #     all_costumes, sounds = [], []
    #     for idx, bd in enumerate(backdrop_data):
    #         all_costumes.extend(bd.get("costumes", []))
    #         if idx == 0 and "sounds" in bd:
    #             sounds = bd["sounds"]
    #     final_project["targets"].append({
    #         "isStage": True,
    #         "name": "Stage",
    #         "variables": {},
    #         "lists": {},
    #         "broadcasts": {},
    #         "blocks": {},
    #         "comments": {},
    #         "currentCostume": 1 if len(all_costumes) > 1 else 0,
    #         "costumes": all_costumes,
    #         "sounds": sounds,
    #         "volume": 100,
    #         "layerOrder": 0,
    #         "tempo": 60,
    #         "videoTransparency": 50,
    #         "videoState": "on",
    #         "textToSpeechLanguage": None
    #     })

    # with open(project_json_path, 'w') as f:
    #     json.dump(final_project, f, indent=2)

    # # logger.info(f"🎉 Final project saved: {project_json_path}")
    # return project_json_path

def delay_for_tpm_node(state: GameState):
    logger.info("--- Running DelayForTPMNode ---")
    time.sleep(60)  # Adjust the delay as needed
    logger.info("Delay completed.")
    return state

# Build the LangGraph workflow
workflow = StateGraph(GameState)

# Add all nodes to the workflow
workflow.add_node("time_delay_1", delay_for_tpm_node)
workflow.add_node("time_delay_2", delay_for_tpm_node)
workflow.add_node("time_delay_3", delay_for_tpm_node)
# workflow.add_node("time_delay_4", delay_for_tpm_node)
workflow.add_node("pseudo_generator", pseudo_generator_node)
workflow.add_node("plan_generator", overall_planner_node)
#workflow.add_node("logic_alignment", plan_logic_aligner_node)
#workflow.add_node("plan_verifier", plan_verification_node)
workflow.add_node("refined_planner", refined_planner_node) # Refines the action plan
workflow.add_node("opcode_counter", plan_opcode_counter_node)
workflow.add_node("block_builder", overall_block_builder_node_2)
# #workflow.add_node("variable_initializer", variable_adder_node)

workflow.set_entry_point("pseudo_generator")
workflow.add_edge("pseudo_generator","time_delay_1")
workflow.add_edge("time_delay_1","plan_generator")
workflow.add_edge("plan_generator","time_delay_2")
workflow.add_edge("time_delay_2",END)
workflow.add_edge("time_delay_2","refined_planner")
workflow.add_edge("refined_planner","time_delay_3")
workflow.add_edge("time_delay_3","opcode_counter")
workflow.add_edge("opcode_counter","block_builder")
workflow.add_edge("block_builder",END)
#workflow.add_edge("variable_initializer", END)
app_graph = workflow.compile()

# ============== Helper function to Upscale an Image ============== #
def upscale_image(image: Image.Image, scale: int = 2) -> Image.Image:
    """
    Upscales a PIL image by a given scale factor.
    """
    try:
        width, height = image.size
        new_size = (width * scale, height * scale)
        upscaled_image = image.resize(new_size, Image.LANCZOS)
        logger.info(f"✅ Upscaled image to {new_size}")
        return upscaled_image
    except Exception as e:
        logger.error(f"❌ Error during image upscaling: {str(e)}")
        return image 
        
def create_sb3_archive(project_folder, project_id):
    """
    Zips the project folder and renames it to an .sb3 file.
    
    Args:
        project_folder (str): The path to the directory containing the project.json and assets.
        project_id (str): The unique ID for the project, used for naming the .sb3 file.
        
    Returns:
        str: The path to the created .sb3 file, or None if an error occurred.
    """
    print(" --------------------------------------- create_sb3_archive INITIALIZE ---------------------------------------")
    # output_filename = os.path.join("outputs", project_id)
    #output_filename = OUTPUT_DIR / project_id
    output_filename = GEN_PROJECT_DIR / project_id
    print(" --------------------------------------- output_filename ---------------------------------------",output_filename)
    zip_path = None
    sb3_path = None
    try:
        zip_path = shutil.make_archive(output_filename, 'zip', root_dir=project_folder)
        print(" --------------------------------------- zip_path_str ---------------------------------------", output_filename, project_folder)
        logger.info(f"Project folder zipped to: {zip_path}")
        
        # 2. Rename the .zip file to .sb3
        sb3_path = f"{output_filename}.sb3"
        os.rename(zip_path, sb3_path)
        print(" --------------------------------------- rename paths ---------------------------------------", zip_path, sb3_path)
        logger.info(f"Renamed {zip_path} to {sb3_path}")

        return sb3_path
    except Exception as e:
        logger.error(f"Error creating SB3 archive for {project_id}: {e}")
        # Clean up any partial files if an error occurs
        if zip_path and os.path.exists(zip_path):
            os.remove(zip_path)
        if sb3_path and os.path.exists(sb3_path):
            os.remove(sb3_path)
        return sb3_path


@app.route('/')
def index():
    return render_template('app_index.html')

@app.route("/download_sb3/<project_id>", methods=["GET"])
def download_sb3(project_id):
    sb3_path = GEN_PROJECT_DIR / f"{project_id}.sb3"
    if not sb3_path.exists():
        return jsonify({"error": "Scratch project file not found"}), 404

    return send_file(
        sb3_path,
        as_attachment=True,
        download_name=sb3_path.name
    )

# API endpoint
@app.route('/process_pdf', methods=['POST'])
def process_pdf():
    try:
        logger.info("Received request to process PDF.")
        if 'pdf_file' not in request.files:
            logger.warning("No PDF file found in request.")
            return jsonify({"error": "Missing PDF file in form-data with key 'pdf_file'"}), 400

        pdf_file = request.files['pdf_file']
        if pdf_file.filename == '':
            return jsonify({"error": "Empty filename"}), 400

        # ================================================= #
        #   Generate Random UUID for project folder name    #
        # ================================================= #
        project_id = str(uuid.uuid4()).replace('-', '')
        # project_folder = os.path.join("outputs", f"{project_id}")    
        project_folder = OUTPUT_DIR / project_id

        # =========================================================================== #
        #           Create empty json in project_{random_id} folder                   #
        # =========================================================================== #
        #os.makedirs(project_folder, exist_ok=True)
        
        # Save the uploaded PDF temporarily
        filename = secure_filename(pdf_file.filename)
        temp_dir = tempfile.mkdtemp()
        saved_pdf_path = os.path.join(temp_dir, filename)
        pdf_file.save(saved_pdf_path)

        # logger.info(f"Created project folder: {project_folder}")
        logger.info(f"Saved uploaded PDF to: {saved_pdf_path}")
        
        # Extract & process
        # output_path, result = extract_images_from_pdf(saved_pdf_path, json_path)
        output_path, result = extract_images_from_pdf(saved_pdf_path)
        print(" --------------------------------------- zip_path_str ---------------------------------------", output_path, result)
        # Check extracted_sprites.json for "scratch block" in any 'name'
        # extracted_dir = os.path.join(JSON_DIR, os.path.splitext(filename)[0])
        # extracted_sprites_json = os.path.join(extracted_dir, "extracted_sprites.json")

        # if not os.path.exists(extracted_sprites_json):
        #     return jsonify({"error": "No extracted_sprites.json found"}), 500

        # with open(extracted_sprites_json, 'r') as f:
        #     sprite_data = json.load(f)

        project_output = similarity_matching(output_path, project_folder)
        logger.info("Received request to process PDF.")
        
        with open(project_output, 'r') as f:
            project_skeleton = json.load(f)
            
            
        images = convert_from_path(saved_pdf_path, dpi=300)  
        print(type)
        page = images[0]
        # img_base64 = base64.b64encode(images).decode("utf-8") 
        buf = BytesIO()
        page.save(buf, format="PNG")
        img_bytes = buf.getvalue()
        img_b64 = base64.b64encode(img_bytes).decode("utf-8")
        #image_paths = await convert_pdf_to_images_async(saved_pdf_path)
        
        #updating logic here [Dev Patel]
        initial_state_dict = {
            "project_json": project_skeleton,
            "description": "The pseudo code for the script",
            "project_id": project_id,
            "project_image": img_b64,
            "action_plan": {},
            "pseudo_code": {},
            "temporary_node": {},
        }
        
        final_state_dict = app_graph.invoke(initial_state_dict) # Pass dictionary

        final_project_json = final_state_dict['project_json'] # Access as dict
        #final_project_json = project_skeleton
        
        # Save the *final* filled project JSON, overwriting the skeleton
        with open(project_output, "w") as f:
            json.dump(final_project_json, f, indent=2)
        logger.info(f"Final project JSON saved to {project_output}")

        # --- Call the new function to create the .sb3 file ---
        sb3_file_path = create_sb3_archive(project_folder, project_id)
        if sb3_file_path:
            logger.info(f"Successfully created SB3 file: {sb3_file_path}")
            # Instead of returning the local path, return a URL to the download endpoint
            download_url = f"https:/webashalarforml-scratch-vlm-v1-2.hf.space/download_sb3/{project_id}" 
            print(f"DOWNLOAD_URL: {download_url}")
            # return jsonify({"message": "Procesed PDF and Game sb3 generated successfully", "project_id": project_id, "download_url": download_url})
            return jsonify({
                "message": "✅ PDF processed successfully",
                "output_json": "output_path",
                "sprites": "result",
                "project_output_json": "project_output",
                "test_url": download_url
            })
        else:
            return jsonify(error="Failed to create SB3 archive"), 500

    except Exception as e:
        logger.error(f"Error during processing the pdf workflow for project ID {project_id}: {e}", exc_info=True)
        return jsonify({"error": f"❌ Failed to process PDF: {str(e)}"}), 500   
    
if __name__ == '__main__':
    # os.makedirs("outputs", exist_ok=True) #== commented by P
    app.run(host='0.0.0.0', port=7860, debug=True)