File size: 59,897 Bytes
1c58aa5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from flask import Flask, render_template, request, jsonify
import json,base64,io,os,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 transformers import AutoProcessor, AutoModelForImageTextToText, AutoModelForVision2Seq
from langchain_community.document_loaders.image_captions import ImageCaptionLoader
from werkzeug.utils import secure_filename
from langchain_groq import ChatGroq
from langgraph.prebuilt import create_react_agent
from pdf2image import convert_from_bytes #convert_from_path, 
import asyncio 
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, functools
from langchain_experimental.open_clip.open_clip import OpenCLIPEmbeddings
# from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from io import BytesIO

# https://prthm11-Scratch_vlm_v1.hf.space/
# https://huggingface.co/spaces/prthm11/Scratch_vlm_v1
# https://prthm11-scratch-vlm-v1.hf.space/process_pdf

# def log_execution_time(func):
#     @functools.wraps(func)
#     def wrapper(*args, **kwargs):
#         start_time = time.time()
#         result = func(*args, **kwargs)
#         end_time = time.time()
#         logger.info(f"⏱ {func.__name__} executed in {end_time - start_time:.2f} seconds")
#         return result
#     return wrapper

# ============================== #
#     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.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",
    model = "meta-llama/llama-4-maverick-17b-128e-instruct",
    temperature=0,
    max_tokens=None,
)

app = Flask(__name__)

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
poppler_path = r"C:\poppler-23.11.0\Library\bin"

count = 0

OUTPUT_FOLDER = "OUTPUTS"
DETECTED_IMAGE_FOLDER_PATH = os.path.join(OUTPUT_FOLDER, "DETECTED_IMAGE")
IMAGE_FOLDER_PATH = os.path.join(OUTPUT_FOLDER, "SCANNED_IMAGE")
JSON_FOLDER_PATH = os.path.join(OUTPUT_FOLDER, "EXTRACTED_JSON")

for path in [OUTPUT_FOLDER, IMAGE_FOLDER_PATH, DETECTED_IMAGE_FOLDER_PATH, JSON_FOLDER_PATH]:
    os.makedirs(path, exist_ok=True)
      
# class GameState(TypedDict):
#     image: str
#     pseudo_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
# 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 {}

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

# # 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_opcodes_functionalities = os.path.join(HAT_BLOCKS_PATH, "hat_blocks.txt")

# boolean_block_data = _load_block_catalog(BOOLEAN_BLOCKS_PATH)
# boolean_description = boolean_block_data["description"]
# boolean_opcodes_functionalities = os.path.join(BOOLEAN_BLOCKS_PATH, "boolean_blocks.txt")

# c_block_data = _load_block_catalog(C_BLOCKS_PATH)
# c_description = c_block_data["description"]
# c_opcodes_functionalities = os.path.join(C_BLOCKS_PATH, "c_blocks.txt")


# cap_block_data = _load_block_catalog(CAP_BLOCKS_PATH)
# cap_description = cap_block_data["description"]
# cap_opcodes_functionalities = os.path.join(CAP_BLOCKS_PATH, "cap_blocks.txt")

# reporter_block_data = _load_block_catalog(REPORTER_BLOCKS_PATH)
# reporter_description = reporter_block_data["description"]
# reporter_opcodes_functionalities = os.path.join(REPORTER_BLOCKS_PATH, "reporter_blocks.txt")

# stack_block_data = _load_block_catalog(STACK_BLOCKS_PATH)
# stack_description = stack_block_data["description"]
# stack_opcodes_functionalities = os.path.join(STACK_BLOCKS_PATH, "stack_blocks.txt")


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

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

# # Node 6: Logic updating if any issue here
# def plan_logic_aligner_node(state: GameState):
#     logger.info("--- Running plan_logic_aligner_node ---")

#     image = state.get("image", "")
    
#     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.
#         --- 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" find...
#         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()

#         parsed_llm_output = extract_json_from_llm_response(llm_output_raw)
        
#         # result = parsed_llm_output
#         # Extract needed values directly
#         logic_data = parsed_llm_output.get("refined_logic", {})
#         name_variable = logic_data.get("name_variable", "Unknown")
#         pseudocode = logic_data.get("pseudocode", "No logic extracted")
        
#         result = {"pseudo_node": {
#             "name_variable": name_variable,
#             "pseudocode": pseudocode
#         }}
        
#         print(f"result:\n\n {result}")
#         return result
#     except Exception as e:
#         logger.error(f"❌ plan_logic_aligner_node failed: {str(e)}")
#         return {"error": str(e)}
#     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 = {
#                 #"image_path": image_path,
#                 "pseudo_code": corrected_output
#             }
            
#             return result
        
#         except Exception as e_corr:
#             logger.error(f"Failed to correct JSON output for even after retry: {e_corr}")

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

# filtered_sprites = {}
# Prepare manipulated sprite JSON structure
manipulated_json = {}
img_elements = []

# @log_execution_time
# --- FUNCTION: Extract images from saved PDF ---
def extract_images_from_pdf(pdf_stream: io.BytesIO):
    ''' Extract images from PDF and generate structured sprite JSON '''
    try:
        # pdf_filename = os.path.splitext(os.path.basename(pdf_stream))[0]  # e.g., "scratch_crab"
        if isinstance(pdf_stream, io.BytesIO):
            # use a random ID since there's no filename
            pdf_id = uuid.uuid4().hex    
        else:
            pdf_id = os.path.splitext(os.path.basename(pdf_stream))[0]
        # pdf_dir_path = os.path.dirname(pdf_stream).replace("/", "\\")

        # Create subfolders
        # extracted_image_subdir = os.path.join(DETECTED_IMAGE_FOLDER_PATH, pdf_filename)
        # json_subdir = os.path.join(JSON_FOLDER_PATH, pdf_filename)
        # os.makedirs(extracted_image_subdir, exist_ok=True)
        # os.makedirs(json_subdir, exist_ok=True)
        # pdf_bytes = pdf_stream.getvalue()
        try:
            elements = partition_pdf(
                file=pdf_stream,
                strategy="hi_res",
                extract_image_block_types=["Image"],
                hi_res_model_name="yolox",
                extract_image_block_to_payload=True,  # Set to True to get base64 in output
            )
        except Exception as e:
            raise RuntimeError(
                f"❌ Failed to extract images from PDF: {str(e)}")

        file_elements = [element.to_dict() for element in elements]
        
        sprite_count = 1
        for el in file_elements:
            img_b64 = el["metadata"].get("image_base64")
            # with open(os.path.join(DETECTED_IMAGE_FOLDER_PATH, f"img_{sprite_count}.png")) as d_img:
            #     d_img = img_b64
            if not img_b64:
                continue 
            
            # raw = base64.b64decode(img_b64)
            # im = Image.open(io.BytesIO(raw)).convert("RGB")
            # up = upscale_image(im, scale=2)
            # buf = io.BytesIO()
            # up.save(buf, format="PNG")
            # buf.seek(0)
            # img_elements.append(base64.b64encode(buf.getvalue()).decode())
            # print(f"------------------------IMAGE ELEMENTS: \n{img_elements}")
           
            # auto_id = f"sprite_{sprite_count}"
            
            manipulated_json[f"Sprite {sprite_count}"] = {
                # "id":auto_id,
                # "name": name,
                "base64": el["metadata"]["image_base64"],
                "file-path": pdf_id,
                # "description": description
            }
            sprite_count += 1
            # print(f"************MANIPULATED JSON: {manipulated_json}")
            
            # manipulated_json_path = os.path.join(JSON_FOLDER_PATH, "manipulated.json")
            # with open(manipulated_json_path, 'w') as f:
            #     json.dump(manipulated_json, f, indent=2)
        # 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
        # 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}")

        return manipulated_json
    except Exception as e:
        raise RuntimeError(f"❌ Error in extract_images_from_pdf: {str(e)}")

# @log_execution_time
def similarity_matching(sprites_data: str, project_folder:str) -> str:
    logger.info("πŸ” Running similarity matching...")

    # ============================== #
    #         DEFINE PATHS           #
    # ============================== #
    # backdrop_images_path = r"E:\Pratham\2025\Harsh Sir\Scratch Vision\images\Backdrops"
    # sprite_images_path = r"E:\Pratham\2025\Harsh Sir\Scratch Vision\images\sprites"
    # image_dirs = [backdrop_images_path, sprite_images_path]

    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"])
    # print(f"\nSPRITE_BASE64: \n{sprite_base64}\n\n")

    sprite_images_bytes = []
    for b64 in sprite_base64:
        img = Image.open(BytesIO(base64.b64decode(b64.split(",")[-1]))).convert("RGB")
        buffer = BytesIO()
        img.save(buffer, format="PNG")
        buffer.seek(0)
        sprite_images_bytes.append(buffer)
    
    # ========================================= #
    #  Walk folders to collect all image paths  #
    # ========================================= #
    folder_image_paths = ['E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\Backdrops\\bedroom\\8cc0b88d53345b3e337e8f028a32a4e7.png', 
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\Backdrops\\baseball\\7be1f5b3e682813dac1f297e52ff7dca.png', 
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\Backdrops\\beach_malibu\\050615fe992a00d6af0e664e497ebf53.png', 
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\Backdrops\\castle\\951765ee7f7370f120c9df20b577c22f.png', 
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\Backdrops\\hall\\ea86ca30b346f27ca5faf1254f6a31e3.png', 
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\Backdrops\\jungle\\f4f908da19e2753f3ed679d7b37650ca.png', 
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\sprites\\Batter\\baseball_sprite_motion_1.png', 
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\sprites\\Bear\\bear_motion_2.png', 
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\sprites\\Beetle\\46d0dfd4ae7e9bfe3a6a2e35a4905eae.png', 
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\sprites\\cat\\cat_motion_1.png', 
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\sprites\\Centaur\\2373556e776cad3ba4d6ee04fc34550b.png', 
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\sprites\\Crab\\bear_element.png', 
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\sprites\\Soccer Ball\\cat_football.png',
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\code_blocks\\script1.jpg',
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\code_blocks\\script2.jpg',
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\code_blocks\\script3.jpg',
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\code_blocks\\script4.jpg',
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\code_blocks\\script5.jpg',
        'E:\\Pratham\\2025\\Harsh Sir\\Scratch Vision\\images\\code_blocks\\script6.jpg' ]
    
    # ============================== #
    #      EMBED SPRITE IMAGES       #
    # ============================== #
    sprite_features = clip_embd.embed_image(sprite_images_bytes)

    # # ============================== #
    # #   EMBED FOLDER IMAGES (REF)    #
    # # ============================== #
    # img_features = clip_embd.embed_image(folder_image_paths)

    # # ============================== #
    # #     Store image embeddings     #
    # # ============================== #
    # embedding_json = []
    # for i, path in enumerate(folder_image_paths):
    #     embedding_json.append({
    #         "name":os.path.basename(path),
    #         "file-path": path,
    #         "embeddings": list(img_features[i])
    #     })
    
    # # # Save to embeddings.json
    # with open(f"{OUTPUT_FOLDER}/embeddings.json", "w") as f:
    #     json.dump(embedding_json, f, indent=2)
        
    # ============================== #
    #     COMPUTE SIMILARITIES       #
    # ============================== #
    ref_embedding_path = f"{OUTPUT_FOLDER}/embeddings.json"
    with open(ref_embedding_path, "r") as f:
        embedding_json = json.load(f)
        # print(f"\n\n EMBEDDING JSON: {embedding_json}")
        
    img_matrix = np.array([img["embeddings"] for img in embedding_json])
    sprite_matrix = np.array(sprite_features)
    
    # if sprite_matrix.size == 0 or img_matrix.size == 0:
    #     raise RuntimeError("❌ No valid embeddings found for sprites or reference images.")
    similarity = np.matmul(sprite_matrix, img_matrix.T)
    # try:
    #     similarity = np.matmul(sprite_matrix, img_matrix.T)
    # except ValueError as ve:
    #     if "matmul" in str(ve) and "size" in str(ve):
    #         logger.error("❌ Matrix multiplication failed due to shape mismatch. Likely due to empty or invalid embeddings.")
    #         raise RuntimeError("Matrix shape mismatch: CLIP embedding input is invalid or empty.")
    #     else:
    #         raise
    most_similar_indices = np.argmax(similarity, axis=1)
    sprite_base_path = r'E:\Pratham\2025\Harsh Sir\Scratch Vision\images\sprites'
    # ============= Match and copy ===============
    project_data = [] #will hold loaded "sprite.json" contents for building the final "project.json"
    copied_folders = set() # prevents copying the same sprite folder more than once.

    # =============================================================== #
    #   Loop through most similar images from Sprites folder          #
    #   β†’ Copy sprite assets (excluding matched image + sprite.json)  #
    #   β†’ Load sprite.json and append its data to project_data        #
    # =============================================================== #
    #sprite_idx: index of sprite we are processing 
    #match_idx: index of the reference image with the highest similarity
    for sprite_idx, matched_idx in enumerate(most_similar_indices): 
        matched_image_path = folder_image_paths[matched_idx]
        print(f"------------ folder image paths: \n {folder_image_paths[matched_idx]}\n")
        matched_image_path = os.path.normpath(matched_image_path)

        matched_folder = os.path.dirname(matched_image_path)
        print(f"\nMATCHED_FOLDER: {matched_folder}\n")
        if not matched_folder.startswith(os.path.normpath(sprite_base_path)):
            continue
        
        folder_name = os.path.basename(matched_folder)
        print(f"FOLDER NAME: {folder_name}")
        print(f"================COPIED FOLDER: \n {copied_folders}\n")
        if matched_folder in copied_folders:
            continue
        copied_folders.add(matched_folder)
        logger.info(f"Matched sprites: {matched_image_path}")
        
        sprite_json_path = os.path.join(matched_folder, 'sprite.json')
        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)
        
    # ================================================================== #
    #   Loop through most similar images from Backdrops folder           #
    #   β†’ Copy matched image + other backdrop assets into project_folder #
    #   β†’ Load project.json and append its stage target to backdrop_data#
    # ================================================================== #
    backdrop_data = []  # for backdrop-related entries
    copied_backdrop_folders = set()  # prevent duplicate backdrops

    # make sure backdrop_base_path is normalized
    backdrop_base_path = os.path.normpath(r'E:\Pratham\2025\Harsh Sir\Scratch Vision\images\Backdrops')

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

        # only handle backdrops
        if not matched_image_path.startswith(backdrop_base_path):
            continue

        matched_folder = os.path.dirname(matched_image_path)
        # skip if backdrop folder already processed
        if matched_folder in copied_backdrop_folders:
            continue
        copied_backdrop_folders.add(matched_folder)
        
        matched_filename = os.path.basename(matched_image_path)
        logger.info(f"Backdrop matched image: {matched_image_path}")

        # 1) Copy the matched backdrop image itself
        try:
            shutil.copy2(
                matched_image_path,
                os.path.join(project_folder, matched_filename)
            )
            logger.info(f"βœ… Copied matched backdrop image {matched_filename} to {project_folder}")
        except Exception as e:
            logger.error(f"❌ Failed to copy matched backdrop {matched_image_path}: {e}")

        # 2) Copy other non‐matched files (e.g. extra costumes) into project_folder
        for fname in os.listdir(matched_folder):
            if fname in {matched_filename, 'project.json'}:
                continue
            src = os.path.join(matched_folder, fname)
            dst = os.path.join(project_folder, fname)
            if os.path.isfile(src):
                try:
                    shutil.copy2(src, dst)
                    logger.info(f"Copied additional backdrop asset {fname} to project folder")
                except Exception as e:
                    logger.error(f"Failed to copy {src}: {e}")

        # 3) Load and append the Stage target from this backdrop's project.json
        backdrop_json_path = os.path.join(matched_folder, 'project.json')
        if os.path.exists(backdrop_json_path):
            with open(backdrop_json_path, 'r') as f:
                backdrop_json_data = json.load(f)
            for target in backdrop_json_data.get("targets", []):
                if target.get("isStage"):
                    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 Edg/138.0.0.0"
        }
    }

    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",
            "objName": "Stage",
            "variables": { "`jEk@4|i[#Fk?(8x)AV.-my variable": ["my variable", 0] },
            "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
        })
    else:
        logger.warning("⚠️ No backdrop matched. Using default static backdrop.")
        default_backdrop_path = os.path.normpath(r"E:\Pratham\2025\Harsh Sir\Scratch Vision\images\plain_white.svg")
        default_backdrop_name = os.path.basename(default_backdrop_path)
        
        default_backdrop_sound = os.path.normpath(r"E:\Pratham\2025\Harsh Sir\Scratch Vision\images\83a9787d4cb6f3b7632b4ddfebf74367.wav")
        default_backdrop_sound_name = os.path.basename(default_backdrop_sound)
        
        try:
            shutil.copy2(default_backdrop_path, os.path.join(project_folder, default_backdrop_name))
            logger.info(f"βœ… Default backdrop copied to project: {default_backdrop_name}")
            
            shutil.copy2(default_backdrop_sound, os.path.join(project_folder, default_backdrop_sound_name))
            logger.info(f"βœ… Default backdrop sound copied to project: {default_backdrop_sound_name}")
            
        except Exception as e:
            logger.error(f"❌ Failed to copy default backdrop assets: {e}")
            
        final_project["targets"].append({
        "isStage": True,
        "name": "Stage",
        "objName": "Stage",
        "variables": {},
        "lists": {},
        "broadcasts": {},
        "blocks": {},
        "comments": {},
        "currentCostume": 0,
        "costumes": [
            {
                "assetId": default_backdrop_name.split(".")[0],
                "name": "defaultBackdrop",
                "md5ext": default_backdrop_name,
                "dataFormat": "png",
                "rotationCenterX": 240,
                "rotationCenterY": 180
            }
        ],
        "sounds": [
            {
            "name": "pop",
            "assetId": "83a9787d4cb6f3b7632b4ddfebf74367",
            "dataFormat": "wav",
            "format": "",
            "rate": 48000,
            "sampleCount": 1123,
            "md5ext": "83a9787d4cb6f3b7632b4ddfebf74367.wav"
            }
        ],
        "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)

    validate_and_copy_assets(
        action_planner_path=r"E:\Pratham\2025\Harsh Sir\Scratch Vision\action_plan.json",
        project_json_path=project_json_path,
        project_folder=project_folder,
        sprite_base_path=sprite_base_path,
        backdrop_base_path=backdrop_base_path,
        final_project = final_project
    )
    # project_data.extend(extra_sprites)
    # backdrop_data.extend(extra_backdrops)
    # logger.info(f"πŸŽ‰ Final project saved: {project_json_path}")
    return project_json_path

def validate_and_copy_assets(action_planner_path, project_json_path, project_folder,sprite_base_path, backdrop_base_path, final_project):
    # step 1: Load action_plan.json and get the first sprite name after "Stage":{...}
    with open(action_planner_path, 'r', encoding='utf-8') as f:
        planner_data = json.load(f)
    
    script_for = None
    keys = list(planner_data.keys())
    if len(keys) > 1:
        script_for = keys[1]
    else: 
        print("No sprite name found after 'Stage'")
        return
    
    print(f"\n\n=================script_for = '{script_for}'\n\n")
    
    # step 2: check in project.json if sprite exists
    sprite_found = False
    with open(project_json_path, 'r', encoding='utf-8') as f:
        project_data = json.load(f)
    
    for target in project_data.get("targets", []):
        if target.get("name", "").lower() == script_for.lower():
            sprite_found = True 
            break 
        
    if sprite_found:
        print(f"'{script_for}' found in project.json – no asset copy needed.")
        return

    # Step 3: Search in backdrops and sprites folders
    base_dirs = [sprite_base_path, backdrop_base_path]
    # project_data = []
    found_sprites = []
    # backdrop_data = []
    found_backdrops = []
    
    # search in sprites 
    if os.path.exists(sprite_base_path):
        for sub_dir in os.listdir(sprite_base_path):
            folder_path = os.path.join(sprite_base_path, sub_dir)
            sprite_json_path = os.path.join(folder_path, "sprite.json")
            if os.path.isdir(folder_path) and os.path.exists(sprite_json_path):
                with open(sprite_json_path, 'r', encoding='utf-8') as f:
                    sprite_info = json.load(f)
                
                if sprite_info.get("name", "").lower() == script_for.lower():
                    print(f"Found matching sprite in {sprite_json_path}")
                    # Copy all assets except json
                    for fname in os.listdir(folder_path):
                        if fname=='sprite.json':
                            continue
                        shutil.copy2(os.path.join(folder_path, fname), os.path.join(project_folder, fname))
                    found_sprites.append(sprite_info)
                    break
    
    # search in backdrops
    if os.path.exists(backdrop_base_path):
        for sub_dir in os.listdir(backdrop_base_path):
            folder_path = os.path.join(backdrop_base_path, sub_dir)
            proj_json_path = os.path.join(folder_path, "project.json")
            if os.path.isdir(folder_path) and os.path.exists(proj_json_path):
                with open(proj_json_path, 'r', encoding='utf-8') as f:
                    bd_json = json.load(f)
                for tgt in bd_json.get("targets", []):
                    if tgt.get("name", "").lower() == script_for.lower():
                        print(f"Found matching backdrop in {proj_json_path}")
                        # Copy all assets except JSON
                        for fname in os.listdir(folder_path):
                            if fname == "project.json":
                                continue
                            shutil.copy2(os.path.join(folder_path, fname),
                                         os.path.join(project_folder, fname))
                        found_backdrops.append(tgt)
                        break
    # return found_sprites, found_backdrops
    # Merge into final project.json
    for spr in found_sprites:
        if not spr.get("isStage", False):
            final_project["targets"].append(spr)
    for bd in found_backdrops:
        if bd.get("isStage", False):
            final_project["targets"].insert(0, bd)

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

    if found_sprites or found_backdrops:
        print(f"βœ… Updated {project_json_path} with missing '{script_for}' assets.")
    else:
        print(f"⚠️ No matching '{script_for}' assets found in sprites/backdrops.")
    
# --- ASYNC PDF to Image Conversion ---
async def convert_pdf_to_images_async(pdf_stream: io.BytesIO, dpi=150):
    loop = asyncio.get_event_loop()
    return await loop.run_in_executor(None, lambda: convert_bytes_to_image(pdf_stream.getvalue(), dpi))
    
    # pdf_name = os.path.splitext(os.path.basename(pdf_path))[0]
    # output_image_folder = os.path.join(IMAGE_FOLDER_PATH, pdf_name)
    # loop = asyncio.get_event_loop()
    # with ThreadPoolExecutor() as pool:
    #     # Pass poppler_path explicitly
    #     result = await loop.run_in_executor(
    #         pool, convert_pdf_to_images_sync, pdf_path, output_image_folder, dpi, poppler_path
    #     )
    # return result

def convert_bytes_to_image(pdf_bytes: bytes, dpi: int):
    images = convert_from_bytes(pdf_bytes, dpi=dpi, poppler_path=poppler_path)
    # Save each page to an in-memory BytesIO and return a list of BytesIOs
    buffers = []
    for img in images:
        buf = BytesIO()
        img.save(buf, format="PNG")
        buf.seek(0)
        buffers.append(buf)
    return buffers

# # Blocking version used internally
# def convert_pdf_to_images_sync(pdf_path, output_image_folder, dpi, poppler_path):
#     pdf_name = os.path.splitext(os.path.basename(pdf_path))[0]
#     output_image_folder = os.path.join("outputs", "SCANNED_IMAGE", pdf_name)
#     os.makedirs(output_image_folder, exist_ok=True)

#     print(f"[INFO] Converting PDF: {pdf_path}")
#     print(f"[INFO] Output folder: {output_image_folder}")
#     # print(f"[INFO] Using Poppler path: {poppler_path}")
#     try:
#         images = convert_from_path(pdf_path, dpi=dpi, poppler_path=poppler_path)
#         image_paths = []
#         for i, img in enumerate(images):
#             output_path = os.path.join(output_image_folder, f"page_{i+1}.png")
#             img.save(output_path, "PNG")
#             print(f"[DEBUG] Saved: {output_path}")
#             image_paths.append(output_path)
#         return image_paths
#     except PDFInfoNotInstalledError as e:
#         raise RuntimeError(f"Poppler not installed or path incorrect: {str(e)}")
#     except Exception as e:
#         print(f"[ERROR] Failed to convert PDF: {e}")
#       raise

# def delay_for_tpm_node(state: GameState):
#     logger.info("--- Running DelayForTPMNode ---")
#     time.sleep(10)  # 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("timer_delay",delay_for_tpm_node)
# workflow.add_node("opcode_counter", plan_logic_aligner_node)
# workflow.set_entry_point("timer_delay")
# workflow.add_edge("timer_delay","opcode_counter")
# workflow.add_edge("opcode_counter", END)
# app_graph = workflow.compile()

# def get_desc_pseudo(image_buf: BytesIO, pseudo_store: dict, project_folder: str):
#     """
#     Takes a path to a code-block image and returns a dict with:
#     - 'pseudo_code': pseudo-code representing logic in Scratch block format
#     Stores the output into outputs/pseudo_output.json
#     """
#     try:
#         # Load image and encode to base64
#         # with open(image_buf, "rb") as image_file:
#         #     image_bytes = image_file.read()
#         img_base64 = base64.b64encode(image_buf.getvalue()).decode()
#         # pseudo_store[image_key] = pseudo
        
#         # === Call LangGraph workflow (auto triggers plan_logic_aligner_node) ===
#         state = app_graph.invoke({"image": img_base64})
#         # { comment: to solve pseudo_output issue
#         # logic_refined = state.get("pseudo_node", {}).get("refined_logic", {}) 
#         pseudo_node = state.get("pseudo_node", {})
        
#         name_variable = pseudo_node.get("name_variable", "Unknown")
#         pseudocode = pseudo_node.get("pseudocode", "No logic extracted")
        
#         pseudo_store.setdefault(name_variable, []).append({"pseudo_code": pseudocode})
        
#         # --- Extract fields ---
#         # refined = logic_refined.get("refined_logic", {})
#         # {comment: to solve pseudo_output.json issue}
#         # name_variable = logic_refined.get("name_variable", "Unknown")
#         # pseudo_code_raw = logic_refined.get("pseudocode", "No logic extracted")
#         # if pseudo_store is not None:
#         #     pseudo_store.setdefault(name_variable, []).append({"pseudo_code": pseudo_code_raw}) 
#         #}
#         with open(os.path.join(project_folder, "pseudo_output.json"), "w") as f:
#             json.dump(pseudo_store, f, indent=2)
        
#         result = {
#             "name_variable": name_variable,
#             "pseudo_code": pseudocode
#         }
#         return result
#     except Exception as e:
#         logger.error(f"❌ get_desc_pseudo failed for {image_buf}: {e}")
#         return {
#             "error": str(e)
#         }

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

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

# API endpoint
@app.route('/process_pdf', methods=['POST'])
async def process_pdf():
    start_time = time.time()
    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    #
        # ================================================= #
        random_id = str(uuid.uuid4()).replace('-', '')
        project_folder = os.path.join("outputs", f"project_{random_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)
        # saved_pdf_path = os.path.join(DETECTED_IMAGE_FOLDER_PATH, filename)
        # pdf_file.save(saved_pdf_path)

        pdf_bytes = pdf_file.read()
        pdf_stream = io.BytesIO(pdf_bytes)
        # logger.info(f"Created project folder: {project_folder}")
        logger.info(f"Saved uploaded PDF to: {pdf_stream}")
        
        # Extract & process
        json_path = None
        # output_path, result = extract_images_from_pdf(saved_pdf_path, json_path)
        # print(f"\n\n OUTPUT_PATH: \n{output_path}\n")
        manipulated_sprites = extract_images_from_pdf(pdf_stream)
        # print(f"\nRESULT: {result}\n")
        # project_output = similarity_matching(output_path, project_folder)
        project_output = similarity_matching(manipulated_sprites, project_folder)

        # Call the async function from sync code
        try:
            image_paths = await convert_pdf_to_images_async(pdf_stream)
            print("PDF converted to images:", image_paths)
            
            # # Create an in-memory store for pseudo-codes
            # pseudo_store = {}   
            # [get_desc_pseudo(img_buf, pseudo_store, project_folder) for img_buf in image_paths]
        except Exception as e:
            print(f"Error processing PDF: {e}")
        
        # Convert in-memory images to base64 strings
        scanned_images_b64 = [
            base64.b64encode(buf.getvalue()).decode("utf-8")
            for buf in image_paths
        ]
        total_time = time.time() - start_time   # ⏳ End timer
        logger.info(f"⏱ Total processing time for PDF: {total_time:.2f} seconds")
        return jsonify({
            "message": "βœ… PDF processed successfully",
            # "output_json": output_path,
            # "sprites": filtered_sprites,
            "project_output_json": project_output,
            "scanned_images": scanned_images_b64,
            # "scanned_image_pseudo": pseudo_results
        })
    except Exception as e:
        logger.exception("❌ Failed to process PDF")
        return jsonify({"error": f"❌ Failed to process PDF: {str(e)}"}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7860, debug=True)