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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from code import interact
import yaml
import argparse
from dataclasses import dataclass, field
from typing import Dict, Any, Optional, List
from pathlib import Path
import os
import numpy as np
import json
import sys

# from core import outcome_based_task_generation
import glog


current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)
sys.path.append(os.path.abspath(os.path.join(current_dir, "..")))
sys.path.append(os.path.abspath(os.path.join(current_dir, "../..")))
from src.utils.run_context import PathResolver


@dataclass
class RawSceneConfig:

    desired_objects: List[str] = field(default_factory=lambda: None)
    not_desired_objects: List[str] = field(
        default_factory=lambda: [
            "frl_apartment_handbag",
            "frl_apartment_cushion_01",
            "frl_apartment_monitor",
            "frl_apartment_cloth_01",
            "frl_apartment_cloth_02",
            "frl_apartment_cloth_03",
            "frl_apartment_cloth",
            "frl_apartment_umbrella",
            "frl_apartment_tv_screen",
            "frl_apartment_indoor_plant_01",
            "frl_apartment_monitor_stand",
            "frl_apartment_setupbox",
            "frl_apartment_beanbag",
            "frl_apartment_bike_01",
            "frl_apartment_bike_02",
            "frl_apartment_indoor_plant_02",
            "frl_apartment_picture_01",
            "frl_apartment_towel",
            "frl_apartment_rug_01",
            "frl_apartment_rug_02",
            "frl_apartment_rug_03",
            "frl_apartment_mat",
            "frl_apartment_tv_object",
        ]
    )
    desired_articulations: List[str] = field(default_factory=lambda: None)
    not_desired_articulations: List[str] = field(default_factory=lambda: None)


@dataclass
class SapienConfig:

    camera_shader: str = "default"
    ray_tracing_denoiser: str = "none"
    time_step: float = 1 / 100.0  # Simulation time step
    ground_altitude: float = 0.0
    ambient_light: List[float] = field(
        default_factory=lambda: [0.5, 0.5, 0.5]
    )  # Ambient light color
    directional_light: List[Dict[str, List[float]]] = field(
        default_factory=lambda: [{"direction": [0, 1, -1], "color": [0.5, 0.5, 0.5]}]
    )
    point_lights: List[Dict[str, List[float]]] = field(
        default_factory=lambda: [
            {"position": [1.989, -5.822, 1], "color": [0.5, 0.5, 0.5]},
            {"position": [2 + 0.15, -5.75 - 0.15, 1.0], "color": [0.4, 0.4, 0.4]},
        ]
    )

    # camera_position: Dict[str, float] = field(
    #     default_factory=lambda: {"x": -5, "y": 0, "z": 6}
    # )
    # camera_rotation: Dict[str, float] = field(
    #     default_factory=lambda: {"r": 0, "p": -np.arctan2(2, 4), "y": 0}
    # )
    # camera_parameters: Dict[str, float] = field(
    #     default_factory=lambda: {"near": 0.05, "far": 100, "fovy": 1}
    # )

    default_material: Dict[str, Any] = field(
        default_factory=lambda: {
            "base_color": [1, 1, 1],
            "metallic": 0.0,
            "roughness": 0.5,
            "specular": 0.5,
            "transmission": 9.0,
        }
    )

    cushion_z_offset: float = 0.1  # Z offset for cushions
    urdf_z_adjustment_offset: float = 0.005  # Z adjustment offset for URDF files

    rotation_offset_x: int = 90  # Rotation offset in degrees
    correction_rotation_x: int = -90  # Correction rotation in degrees

    excluded_shading_objects: List[str] = field(
        default_factory=lambda: ["book_03"]
    )  # Objects to exclude from shading
    default_shading_mode: int = 1  # Default shading mode

    default_json_file: str = "scene_parsed.json"  # Default JSON file name
    default_output_file: str = "entities_apt_0.json"  # Default output file name


@dataclass
class SceneType:
    """Scene Type configuration"""

    NEED_COLLISION_ADJUSTMENT: bool = True  # use collision to first apply gravity.
    RGBD_SCENE: bool = False  # use RGBD scene, which will treat everything as cuboids.


@dataclass
class BasicGeometryConfig:
    """Basic Geometry configuration"""

    EPS: float = 1e-5


@dataclass
class ImageRendererConfig:
    """Image Renderer configuration"""

    EPS: float  = 1e-6
    default_fovy: float = float(np.deg2rad(60.0))  # Default field of view in radians
    default_fovy_range: List[float] = field(
        default_factory=lambda: [float(np.deg2rad(10.0)), float(np.deg2rad(100.0))]
    )
    default_focus_ratio: float = 0.5
    default_near: float = 0.1
    default_far: float = 100.0
    default_camera_xy: List[float] = field(default_factory=lambda: [0.0, 0.0])
    z_range: List[float] = field(
        default_factory=lambda: [0.2, 2.5]
    )  # Default Z range for camera
    font_size: int = 48
    width: int = 1920
    height: int = 1080
    roll_range: List[float] = field(
        default_factory=lambda: [-np.pi / 900, np.pi / 900]
    )  # Very small range for roll

    number_font_size: int = 40
    default_scipy_minimize_ftol: float = 1e-3
    default_scipy_minimize_maxiter: int = 250
    trans_visiblity: float = 0.2

    high_contrast_color_list = [
        # Deep red series
        (180, 30, 45),  # Deep red
        (220, 50, 50),  # Bright red
        (150, 30, 70),  # Wine red
        # Blue series
        (30, 70, 150),  # Deep blue
        (0, 90, 170),  # Royal blue
        (70, 130, 180),  # Steel blue
        # Green series
        (30, 120, 50),  # Deep green
        (0, 100, 80),  # Forest green
        (60, 140, 60),  # Grass green
        # Yellow/Orange series
        (200, 120, 0),  # Deep orange
        (180, 140, 20),  # Golden yellow
        (215, 150, 0),  # Amber
        # Purple series
        (110, 40, 120),  # Deep purple
        (140, 70, 140),  # Violet
        (90, 50, 140),  # Blue-purple
        # Cyan series
        (0, 110, 120),  # Deep cyan
        (40, 140, 140),  # Blue-green
        (0, 130, 130),  # Teal
        # Neutral tones
        (80, 80, 80),  # Dark gray
        (120, 100, 80),  # Brown
        (70, 90, 100),  # Blue-gray
        # Other high contrast colors
        (180, 80, 80),  # Indian red
        (70, 100, 50),  # Olive green
        (90, 60, 140),  # Deep blue-purple
        (170, 70, 0),  # Ochre
        (80, 60, 30),  # Dark brown
        (150, 80, 100),  # Berry color
    ]


@dataclass
class ConcaveProcessorConfig:
    eps: float = 1e-4
    min_polygon_area: float = 0.1  # Minimum polygon area threshold
    target_aspect_ratio: float = 1.8  # Target aspect ratio
    max_target_strips: int = 4  # Maximum target strips
    merge_tolerance: float = 0.01  # Tolerance for merging polygons
    concave_threshold: float = (
        0.2  # Concavity threshold for determining if a polygon is concave
    )
    concave_min_area: float = 1e-5  # Minimum concave polygon area threshold


@dataclass
class GroundCoverageConfig:
    """Ground coverage configuration"""

    eps: float = 1e-3
    resolution: float = 0.01  # Grid resolution (meters)
    min_rect_size: float = 0.4  # Minimum rectangle size
    standing_point_distance: float = 0.8  # Distance from standing point to object
    global_bounds: List[float] = field(
        default_factory=lambda: [-5.0, 5.0, -5.0, 5.0]
    )  # Global bounds (min_x, max_x, min_y, max_y)
    z_range: List[float] = field(default_factory=lambda: [0.1, 1])  # Z-axis range


# @dataclass
# class TaskPrimitiveConfig:
#     """Task primitive configuration"""

#     default_action: str = "move"
#     support_directions: List[str] = field(
#         default_factory=lambda: [
#             "front",
#             "rear",
#             "left",
#             "right",
#             "center",
#             "front-left",
#             "front-right",
#             "rear-left",
#             "rear-right",
#         ]
#     )
#     support_relations: List[str] = field(
#         default_factory=lambda: ["at", "on", "in", "around", "between", "freespace"]
#     )


@dataclass
class ProcessbasedTaskConfig:
    """Atomic task configuration"""

    max_task_length: int = 5  # Maximum length of an atomic task
    max_task_num: int = 1000  # Maximum number of atomic tasks
    use_level1_tasks: bool = True  # Whether to use level 1 tasks


@dataclass
class SceneConfig:
    """Scene configuration"""

    global_bounds: List[float] = field(default_factory=lambda: [-5.0, 5.0, -5.0, 5.0])
    safety_margin: float = 0.1
    collision_check_enabled: bool = True


@dataclass
class OpenRouterConfig:
    """OpenRouter configuration"""

    api_key: str = (
        "Bearer sk-or-v1-YourAPIKeyHere"  # Replace with your OpenRouter API key
    )
    model: str = (
        "irrelevant/placeholder-model-name"  # Placeholder for model selection - not relevant to current context
    )
    """

     # 'openai/gpt-4.1'

        # 'openai/gpt-4.1-mini'

        # 'qwen/qwen2.5-vl-72b-instruct'

        # 'meta-llama/llama-3.3-70b-instruct'

        #'openai/gpt-4o-2024-11-20'

        #'google/gemini-2.5-flash-preview'

        #'openai/gpt-4o-2024-11-20'

        #'google/gemini-2.5-pro-preview-03-25'

        # "anthropic/claude-3.7-sonnet"

        # anthropic/claude-3.5-haiku

        # "meta-llama/llama-3.2-90b-vision-instruct" #"openai/gpt-4.1-nano"  # "openai/chatgpt-4o-latest" #"meta-llama/llama-3.2-90b-vision-instruct"



    

    

    """


@dataclass
class MeshProcessorConfig:
    """MeshProcessor configuration"""

    min_size: float = 0.0025
    relative_size_ratio: float = 0.25
    EPS: float = 1e-6
    coverage_threshold: float = 0.6
    height_threshold: float = 0.01  # Minimum height threshold for platforms


@dataclass
class VlmInteractorConfig:
    """VLM Interactor configuration"""

    MAX_INTERACTION_COUNT: int = 20


@dataclass
class SceneElementConfig:
    """Scene Element configuration"""

    contact_eps: float = 5e-2
    bbox_eps: float = 4e-1
    ground_level_correction: float = 1e-4


@dataclass
class RectangleQueryConfig:
    """Rectangle Query configuration"""

    EPS: float = 1e-3
    placement_coverage_threshold: float = 0.95


@dataclass
class BenchmarkExecutorConfig:
    """Benchmark Executor configuration"""

    max_interaction_count: int = 20

    picture_width: int = 1366
    picture_height: int = 768

    # prompt_templates_path: str = "data/templates/benchmark_prompts.json"
    # reflection_prompts_path: str = "data/templates/reflection_prompts.json"
    # image_save_base_path: str = "image4interact/"

    default_fovy_deg_min: float = 40.0
    default_fovy_deg_max: float = 60.0
    focus_ratio: float = 0.6

    # reflection_txt_load_path: Optional[str] = (
    #     "./out/load_reflection.txt"  # Path to the reflection text file
    # )
    # reflection_txt_save_path: Optional[str] = "./out/save_reflection.txt"  # Path to save

    enable_detailed_logging: bool = False
    save_interaction_history: bool = True


@dataclass
class TaskInteractionConfig:
    """Task Interaction specific configuration"""

    enable_hint_prompts: bool = True
    enable_ambiguous_item_handling: bool = True
    enable_reflection_prompts: bool = True


@dataclass
class OutcomeBaseGenerationConfig:
    """Configuration for outcome-based task generation"""

    vlm_list: List[str] = field(
            default_factory=lambda:[
            "openai/gpt-4.1",
            "anthropic/claude-3.5-haiku",
            "google/gemini-2.5-flash-lite-preview-06-17",
        ]
    )
    
    task_num_per_pattern: int = 5
    # manitaskot_pattern_file: str = "data/templates/manitask_ot200.txt"
    # output_dir: str = "./out/outcome_based_task.txt"

# @dataclass
# class InteractPromptHelperConfig:
#     prompt_template_path: str = "data/templates/benchmark_prompts.json"


@dataclass
class RenameEngineConfig:
    model: str = "openai/gpt-4.1-mini"


@dataclass
class CommonConfig:
    """Common configuration parameters"""

    # openrouter api
    open_router: OpenRouterConfig = field(default_factory=OpenRouterConfig)

    scene_graph_pkl_load_path: Optional[str] = (
        "${run_dir}/cache/scene_graph.pkl"  # Path to the input JSON scene file
    )


@dataclass
class PreProcessingConfig:
    """Stage 1 specific configuration parameters"""

    raw_scene: RawSceneConfig = field(default_factory=RawSceneConfig)

    rename_engine: RenameEngineConfig = field(default_factory=RenameEngineConfig)

    adjust_with_gravity: bool = (
        True  # Whether to adjust gravity (may affect object pose)
    )
    
    use_renaming_engine: bool = True  # Whether to use renaming engine
    input_json_path: Optional[str] = (
        "./data/datasets/replica_dataset/configs/scenes/apt_0.scene_instance.json"  # Scene file path
    )
    output_json_path: Optional[str] = (
        ".${run_dir}/cache/scene_parsed.json"  # Output file path
    )
    entity_json_path: Optional[str] = (
        ".${run_dir}/cache/scene_entities.json"  # Entity file path
    )
    output_dir: str = "./output/"  # Output directory for results

    dataset_root_path: str = (
        "data/datasets/replica_dataset"  # Path to the SAPIEN dataset root directory
    )
    stage_path_prefix: str = (
        "data/datasets/replica_dataset"  # Path prefix for stage files
    )
    visual_path_prefix: str = (
        "data/datasets/replica_dataset/objects"  # Path prefix for visual objects
    )
    collision_path_prefix: str = (
        "data/datasets/replica_dataset/objects/convex"  # Path prefix for collision objects, don't need if the dataset has no collision objects
    )
    urdf_path_prefix: str = (
        "data/datasets/replica_dataset/urdf"  # Path prefix for URDF files, don't need if the dataset has no URDF files
    )
    object_config_path: str = (
        "data/datasets/replica_dataset/configs/objects"  # Path to the object configuration
    )

    scene_graph_pkl_save_path: Optional[str] = (
        "${run_dir}/cache/scene_graph.pkl"  # Path to the scene graph pickle file
    )

    image4rename_path: Optional[str] = (
        "${run_dir}/images/image4rename"  # Path to the image for renaming
    )

    rename_dict_path: Optional[str] = (
        "${run_dir}/cache/rename_dict.json"  # Path to the renaming dictionary
    )


@dataclass
class ProcessTaskGenConfig:
    """Stage 2a specific configuration parameters"""

    process_based_task: ProcessbasedTaskConfig = field(
        default_factory=ProcessbasedTaskConfig
    )

    process_based_task_pkl_save_path: Optional[str] = (
        "${run_dir}/cache/process_based_task.pkl"
    )

    process_based_task_txt_save_path: Optional[str] = (
        "${run_dir}/output/process_based_task.txt"
    )


@dataclass
class OutcomeTaskGenConfig:
    """Stage 2b specific configuration parameters"""

    outcome_based_task: OutcomeBaseGenerationConfig = field(
        default_factory=OutcomeBaseGenerationConfig
    )

    outcome_based_task_txt_save_path: Optional[str] = (
        "${run_dir}/output/outcome_based_task.txt"
    )

    image4vote_path: Optional[str] = (
        "${run_dir}/images/image4vote"  # Path to the image for voting
    )

    manitaskot_pattern_file: str = "data/templates/manitask_ot200.txt"


@dataclass
class BenchmarkConfig:
    """Stage 3 specific configuration parameters"""

    vlm_interactor: VlmInteractorConfig = field(default_factory=VlmInteractorConfig)

    image4interaction_path: Optional[str] = (
        "${run_dir}/images/image4interact"  # Path to the image for interaction
    )
    image4reflection_path: Optional[str] = (
        "${run_dir}/images/image4reflection"  # Path to the image for reflection
    )
    reflection_txt_load_path: Optional[str] = (
        "${run_dir}/reflection/load_reflection.txt"  # Path to the reflection text file
    )

    reflection_txt_save_path: Optional[str] = (
        "${run_dir}/reflection/save_reflection.txt"  # Path to save
    )
    mode: str = "manual"  # Mode: "online" or "manual"
    benchmark_task_num: int = 5  # Number of tasks to generate
    benchmark_model_name: str = "openai/gpt-4.1-mini"
    generate_mistake_note: bool = True  # Whether to generate mistake notes
    use_mistake_note: int = 1  # Whether to use mistake notes (
    result_file_path: Optional[str] = (
        "${run_dir}/output/result.txt"  # Path to save the result file
    )


@dataclass
class MiscConfig:
    """Miscellaneous configuration parameters"""

    
    image_path: Optional[str] = "${run_dir}/data/images"  # Path to save images
    sapien_config: SapienConfig = field(default_factory=SapienConfig)
    scene_type: SceneType = field(default_factory=SceneType)
    basic_geometry_config: BasicGeometryConfig = field(
        default_factory=BasicGeometryConfig
    )
    image_renderer_config: ImageRendererConfig = field(
        default_factory=ImageRendererConfig
    )
    concave_processor_config: ConcaveProcessorConfig = field(
        default_factory=ConcaveProcessorConfig
    )
    scene_config: SceneConfig = field(default_factory=SceneConfig)
    mesh_processor_config: MeshProcessorConfig = field(
        default_factory=MeshProcessorConfig
    )
    scene_element_config: SceneElementConfig = field(default_factory=SceneElementConfig)
    rectangle_query_config: RectangleQueryConfig = field(
        default_factory=RectangleQueryConfig
    )
    task_interaction_config: TaskInteractionConfig = field(
        default_factory=TaskInteractionConfig
    )
    benchmark_executor_config: BenchmarkExecutorConfig = field(
        default_factory=BenchmarkExecutorConfig
    )
    ground_coverage_config: GroundCoverageConfig = field(
        default_factory=GroundCoverageConfig
    )

    benchmark_prompt_template_path: str = "data/templates/benchmark_prompts.json"
    reflection_prompt_template_path: str = "data/templates/reflection_prompts.json"
    rename_engine_prompt_template_path: str = "data/templates/renaming_engine.json"
    interact_prompt_template_path: str = "data/templates/interact_prompts.json"
    
    bbox_only: bool = False  # Whether to use bounding box only for collision detection
    


@dataclass
class StageBasedConfig:
    """Stage-based configuration parameters"""

    common: CommonConfig = field(default_factory=CommonConfig)
    stage1_pre_processing: PreProcessingConfig = field(
        default_factory=PreProcessingConfig
    )
    stage2a_process_task_generation: ProcessTaskGenConfig = field(
        default_factory=ProcessTaskGenConfig
    )
    stage2b_outcome_task_generation: OutcomeTaskGenConfig = field(
        default_factory=OutcomeTaskGenConfig
    )
    stage3_benchmark: BenchmarkConfig = field(default_factory=BenchmarkConfig)
    utilities: MiscConfig = field(default_factory=MiscConfig)


@dataclass
class StageBasedConfigLoader:
    """Loader for stage-based configuration from a YAML file"""

    def __init__(self, app_config=None):
        self.stage_config = StageBasedConfig()
        if app_config is not None:
            self.import_from_app_config(app_config)

    def load_from_dict(self, config_dict: Dict[str, Any]) -> None:
        """load configuration from a dictionary"""

        if "common" in config_dict:
            self._update_nested_config(self.stage_config.common, config_dict["common"])
        #  import ipdb; ipdb.set_trace()
        if "stage1_pre_processing" in config_dict:
            self._update_nested_config(
                self.stage_config.stage1_pre_processing,
                config_dict["stage1_pre_processing"],
            )
        #  import ipdb; ipdb.set_trace()
        if "stage2a_process_task_generation" in config_dict:
            self._update_nested_config(
                self.stage_config.stage2a_process_task_generation,
                config_dict["stage2a_process_task_generation"],
            )

        if "stage2b_outcome_task_generation" in config_dict:
            self._update_nested_config(
                self.stage_config.stage2b_outcome_task_generation,
                config_dict["stage2b_outcome_task_generation"],
            )

        if "stage3_benchmark" in config_dict:
            self._update_nested_config(
                self.stage_config.stage3_benchmark, config_dict["stage3_benchmark"]
            )

        if "utilities" in config_dict:
            self._update_nested_config(
                self.stage_config.utilities, config_dict["utilities"]
            )

    def _update_nested_config(

        self, config_obj: Any, config_dict: Dict[str, Any]

    ) -> None:
        """Recursively update nested configuration objects from a dictionary"""
        for key, value in config_dict.items():
            if hasattr(config_obj, key):
                attr = getattr(config_obj, key)
                if isinstance(attr, (int, float, str, bool, type(None))):
                    setattr(config_obj, key, value)
                    glog.info(f"Set attribute {key} to value {value}")
                elif isinstance(attr, list) and isinstance(value, list):
                    setattr(config_obj, key, value)
                    glog.info(f"Set list attribute {key} to value {value}")
                elif hasattr(attr, "__dataclass_fields__") and isinstance(value, dict):
                    self._update_nested_config(attr, value)
                else:
                    try:
                        setattr(config_obj, key, value)
                    except Exception as e:
                        glog.error(
                            f"Failed to set attribute {key} with value {value}: {e}"
                        )

    def import_from_app_config(self, app_config: "AppConfig") -> None:
        """Populate stage-based configuration from the main application configuration"""

        app_config_attrs = set(app_config.__dict__.keys())
        stage_configs = [
            self.stage_config.common,
            self.stage_config.stage1_pre_processing,
            self.stage_config.stage2a_process_task_generation,
            self.stage_config.stage2b_outcome_task_generation,
            self.stage_config.stage3_benchmark,
            self.stage_config.utilities,
        ]

        for stage_config in stage_configs:
            for attr_name in app_config_attrs:
                if hasattr(stage_config, attr_name):
                    attr_value = getattr(app_config, attr_name)
                    setattr(stage_config, attr_name, attr_value)

    def export_to_app_config(self, app_config: "AppConfig") -> Any:
        """Populate the main application configuration from stage-based configuration"""

        app_config_attrs = set(app_config.__dict__.keys())
        # import ipdb;
        # ipdb.set_trace()
        stage_configs = [
            self.stage_config.common,
            self.stage_config.stage1_pre_processing,
            self.stage_config.stage2a_process_task_generation,
            self.stage_config.stage2b_outcome_task_generation,
            self.stage_config.stage3_benchmark,
            self.stage_config.utilities,
        ]

        for stage_config in stage_configs:
            for attr_name, attr_value in stage_config.__dict__.items():
                if attr_name in app_config_attrs:
                    setattr(app_config, attr_name, attr_value)

        return app_config


@dataclass
class AppConfig:
    """Main application configuration"""

    # common: CommonConfig = field(default_factory=CommonConfig)
    # pre_processing: PreProcessingConfig = field(
    #     default_factory=PreProcessingConfig
    # )
    # process_task_generation: ProcessTaskGenConfig = field(default_factory=ProcessTaskGenConfig)
    # outcome_task_generation: OutcomeTaskGenConfig = field(default_factory=OutcomeTaskGenConfig)
    # benchmark: BenchmarkConfig = field(default_factory=BenchmarkConfig)
    # misc: MiscConfig = field(default_factory=MiscConfig)

    pass

    ground_coverage: GroundCoverageConfig = field(default_factory=GroundCoverageConfig)
    # task_primitive: TaskPrimitiveConfig = field(default_factory=TaskPrimitiveConfig)
    process_based_task: ProcessbasedTaskConfig = field(
        default_factory=ProcessbasedTaskConfig
    )
    scene: SceneConfig = field(default_factory=SceneConfig)
    scene_type: SceneType = field(default_factory=SceneType)
    basic_geometry: BasicGeometryConfig = field(default_factory=BasicGeometryConfig)
    image_renderer: ImageRendererConfig = field(default_factory=ImageRendererConfig)
    concave_processor: ConcaveProcessorConfig = field(
        default_factory=ConcaveProcessorConfig
    )
    openrouter: OpenRouterConfig = field(default_factory=OpenRouterConfig)
    meshprocessor: MeshProcessorConfig = field(default_factory=MeshProcessorConfig)
    vlm_interactor: VlmInteractorConfig = field(default_factory=VlmInteractorConfig)
    scene_element: SceneElementConfig = field(default_factory=SceneElementConfig)
    rectangle_query: RectangleQueryConfig = field(default_factory=RectangleQueryConfig)
    raw_scene: RawSceneConfig = field(default_factory=RawSceneConfig)
    sapien: SapienConfig = field(default_factory=SapienConfig)
    benchmark_executor: BenchmarkExecutorConfig = field(
        default_factory=BenchmarkExecutorConfig
    )
    task_interaction: TaskInteractionConfig = field(
        default_factory=TaskInteractionConfig
    )
    outcome_based_task_generation: OutcomeBaseGenerationConfig = field(
        default_factory=OutcomeBaseGenerationConfig
    )
    rename_engine: RenameEngineConfig = field(default_factory=RenameEngineConfig)

    # Global configuration

    adjust_with_gravity: bool = (
        True  # Whether to adjust gravity (may affect object pose)
    )
    use_renaming_engine: bool = True  # Whether to use renaming engine
    bbox_only: bool = False  # Whether to use bounding box only
    input_json_path: Optional[str] = (
        "./data/datasets/replica_dataset/configs/scenes/apt_0.scene_instance.json"  # Scene file path
    )
    output_json_path: Optional[str] = "./scene_parsed.json"  # Output file path
    entity_json_path: Optional[str] = (
        "./scene_entities.json"  # Entity file path
    )
    output_dir: str = "./output/"  # Output directory for results
    mode: str = "online"  # Mode: "online" or "manual"
    # log_level: str = "INFO"

    # cache_enabled: bool = True
    # random_seed: Optional[int] = None

    benchmark_task_num: int = 5  # Number of tasks to generate

    dataset_root_path: str = (
        "data/datasets/replica_dataset"  # Path to the SAPIEN dataset root directory
    )
    stage_path_prefix: str = (
        "data/datasets/replica_dataset"  # Path prefix for stage files
    )
    visual_path_prefix: str = (
        "data/datasets/replica_dataset/objects"  # Path prefix for visual objects
    )
    collision_path_prefix: str = (
        "data/datasets/replica_dataset/objects/convex"  # Path prefix for collision objects, don't need if the dataset has no collision objects
    )
    urdf_path_prefix: str = (
        "data/datasets/replica_dataset/urdf"  # Path prefix for URDF files, don't need if the dataset has no URDF files
    )
    object_config_path: str = (
        "data/datasets/replica_dataset/configs/objects"  # Path to the object configuration
        # "/mnt/windows_e/workplace/task_generation/replica_dataset/configs/objects"  # Path to the object configuration
    )

    benchmark_prompt_template_path: str = "data/templates/benchmark_prompts.json"
    reflection_prompt_template_path: str = "data/templates/reflection_prompts.json"
    rename_engine_prompt_template_path: str = "data/templates/renaming_engine.json"
    interact_prompt_template_path: str = "data/templates/interact_prompts.json"

    scene_graph_pkl_load_path: Optional[str] = (
        "${run_dir}/cache/scene_graph.pkl"  # Path to the input JSON scene file
    )
    scene_graph_pkl_save_path: Optional[str] = (
        "${run_dir}/cache/scene_graph.pkl"  # Path to the scene graph pickle file
    )
    process_based_task_pkl_load_path: Optional[str] = (
        "${run_dir}/cache/process_based_task.pkl"
    )
    process_based_task_pkl_save_path: Optional[str] = (
        "${run_dir}/cache/process_based_task.pkl"
    )
    process_based_task_txt_save_path: Optional[str] = (
        "${run_dir}/output/process_based_task.txt"
    )
    outcome_based_task_txt_save_path: Optional[str] = (
        "${run_dir}/output/outcome_based_task.txt"
    )
    image4rename_path: Optional[str] = (
        "${run_dir}/images/image4rename"  # Path to the image for renaming
    )
    image4interaction_path: Optional[str] = (
        "${run_dir}/images/image4interact"  # Path to the image for interaction
    )
    image4vote_path: Optional[str] = (
        "${run_dir}/images/image4vote"  # Path to the image for voting
    )
    image4reflection_path: Optional[str] = (
        "${run_dir}/images/image4reflection"  # Path to the image for reflection
    )
    reflection_txt_load_path: Optional[str] = (
        "${run_dir}/reflection/load_reflection.txt"  # Path to the reflection text file
    )
    reflection_txt_save_path: Optional[str] = (
        "${run_dir}/reflection/save_reflection.txt"  # Path to save
    )

    rename_dict_path: Optional[str] = (
        "${run_dir}/cache/rename_dict.json"  # Path to the renaming dictionary
    )

    image_path: Optional[str] = "${run_dir}/data/images"  # Path to save images

    benchmark_model_name: str = "openai/gpt-4.1-mini"
    generate_mistake_note: bool = True  # Whether to generate mistake notes
    use_mistake_note: int = 1  # Whether to use mistake notes (

    result_file_path: Optional[str] = (
        "${run_dir}/output/result.txt"  # Path to save the result file
    )
    manitaskot_pattern_file: str = "data/templates/manitask_ot200.txt"


"""

sapien.render.set_camera_shader_dir("rt")

sapien.render.set_ray_tracing_denoiser('oidn')

parser.add_argument("--adjust_with_gravity", action="store_true", default=False, help="Enable debug mode")

    parser.add_argument("--use_renaming_engine", action="store_true", default=True,help="Use renaming engine for item classification")

    parser.add_argument("--bbox_only", action="store_true", default=False, help="Use bounding box only for item representation")

    parser.add_argument('--input_file', type=str, help="Path to the scene file")

    parser.add_argument("--mode", type=str, default="online")

    parser.add_argument("--model_name", type=str, default="human")

    parser.add_argument("--generate_reflection", type=bool, default=False)

    parser.add_argument("--use_mistake_note", type=int, default=0)

    parser.add_argument("--config_file", type=str, default="config.json", help="Path to the configuration file")

"""


class ConfigManager:
    """Configuration Manager"""

    _instance = None

    def __new__(

        cls, config_file_path: Optional[str] = None, run_dir: Optional[str] = None

    ):
        if cls._instance is None:
            cls._instance = super(ConfigManager, cls).__new__(cls)
            cls._instance._initialized = False
        return cls._instance

    @classmethod
    def get_instance(cls):
        """Get the singleton instance of ConfigManager"""
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

    def save_to_yaml_staged(self, config_path: str) -> None:

        config_path = Path(config_path)
        # import ipdb; ipdb.set_trace()
        try:
            staged_config_dict = self._convert_app_config_to_staged_format()

            config_path.parent.mkdir(parents=True, exist_ok=True)
            with open(config_path, "w", encoding="utf-8") as f:
                yaml.dump(
                    staged_config_dict, f, default_flow_style=False, allow_unicode=True
                )

            glog.info(f"Configuration saved to {config_path} in staged format")
        except Exception as e:
            glog.error(f"Failed to save configuration to {config_path}: {e}")

    def _convert_app_config_to_staged_format(self) -> StageBasedConfig:
        """Convert AppConfig to StageBasedConfig format"""

        staged_config = StageBasedConfig()

        loader = StageBasedConfigLoader()
        
        loader.import_from_app_config(self.config)
        staged_config = loader.stage_config

        import dataclasses
       # import ipdb; ipdb.set_trace()
        def dataclass_to_dict(obj):
            if dataclasses.is_dataclass(obj):
                result = {}
                for field in dataclasses.fields(obj):
                    value = getattr(obj, field.name)
                    result[field.name] = dataclass_to_dict(value)
                return result
            elif isinstance(obj, list):
                return [dataclass_to_dict(item) for item in obj]
            else:
                return obj

        # import ipdb; ipdb.set_trace()
        return dataclass_to_dict(staged_config)

    def __init__(

        self, config_file_path: Optional[str] = None, run_dir: Optional[str] = None

    ):
        if (
            self._initialized
            and self.config_file_path == config_file_path
            and self.run_dir == run_dir
        ):
            return
        # import ipdb; ipdb.set_trace()
        if run_dir:
            self.run_dir = run_dir
        else:
            self.run_dir = os.path.abspath(os.getcwd())

        self.path_resolver = PathResolver(self.run_dir)

        self.config = AppConfig()
        self.config_file_path = config_file_path

        self.config_file_export_dir = "run/configs_used/"
        self._initialized = True
        # import ipdb; ipdb.set_trace()
        #  glog.info("config_file_path", config_file_path)
        if config_file_path:

            self.load_config(config_file_path)
        #   import ipdb; ipdb.set_trace()
        self.save_used_config()

        self._resolve_all_paths()

    # import ipdb; ipdb.set_trace()

    def _resolve_all_paths(self):

        import dataclasses

        for field in dataclasses.fields(self.config):
            value = getattr(self.config, field.name)

            if isinstance(value, str) and value.startswith("${run_dir}"):
                resolved_path = value.replace("${run_dir}", self.run_dir)
                setattr(self.config, field.name, resolved_path)

    def save_used_config(self):
        config_path = f"{self.run_dir}/latest_config/used_config.yaml"
        self.save_to_yaml_staged(config_path)
        glog.info(f"Saved used configuration to {config_path}")

    def load_config(self, config_file_path: str) -> None:
        """Load configuration from file (supports both YAML and JSON)"""
        if config_file_path.endswith(".yaml") or config_file_path.endswith(".yml"):
            self.load_from_yaml(config_file_path)
        elif config_file_path.endswith(".json"):
            self.load_from_json(config_file_path)
        else:
            glog.info(f"Unsupported configuration file format: {config_file_path}")

    def load_from_yaml(self, config_path: str) -> None:
        """Load configuration from YAML file"""
        config_path = Path(config_path)
        if not config_path.exists():
            glog.info(
                f"Configuration file {config_path} does not exist, using default configuration"
            )
            return
        glog.info(f"Loading configuration from {config_path}")

        try:
            with open(config_path, "r", encoding="utf-8") as f:
                config_dict = yaml.safe_load(f)

            try:
                self._update_config_from_dict(config_dict)

            except Exception as e:
                glog.warning(
                    f"Failed to update config using new method, falling back to legacy method: {e}"
                )
                self._update_config_from_dict_legacy(config_dict)
            self.config_file_path = config_path
            glog.info(f"Loaded configuration file: {config_path}")
        except Exception as e:
            glog.info(f"Failed to load configuration file: {e}")
        # import ipdb; ipdb.set_trace()

    def load_from_json(self, config_path: str) -> None:
        """Load configuration from JSON file"""
        config_path = Path(config_path)
        if not config_path.exists():
            glog.info(
                f"Configuration file {config_path} does not exist, using default configuration"
            )
            return

        try:
            with open(config_path, "r", encoding="utf-8") as f:
                config_dict = json.load(f)

            self._update_config_from_dict(config_dict)
            self.config_file_path = config_path
            glog.info(f"Loaded configuration file: {config_path}")
        except Exception as e:
            glog.info(f"Failed to load configuration file: {e}")

    def _update_nested_config(

        self, config_obj: Any, config_dict: Dict[str, Any]

    ) -> None:
        """Recursively update nested configuration objects from a dictionary"""
        for key, value in config_dict.items():
            if hasattr(config_obj, key):
                attr = getattr(config_obj, key)
                if isinstance(attr, (int, float, str, bool, type(None))):
                    setattr(config_obj, key, value)
                elif isinstance(attr, list) and isinstance(value, list):
                    setattr(config_obj, key, value)
                elif hasattr(attr, "__dataclass_fields__") and isinstance(value, dict):
                    self._update_nested_config(attr, value)
                else:
                    try:
                        setattr(config_obj, key, value)
                    except Exception as e:
                        glog.error(
                            f"Failed to set attribute {key} with value {value}: {e}"
                        )

    def _update_config_from_dict(self, config_dict: Dict[str, Any]) -> None:
        """Update configuration from dictionary"""

        # Check if the config_dict uses legacy keys
        stage_base_config_loader = StageBasedConfigLoader(self.config)
        stage_base_config_loader.load_from_dict(config_dict)
        stage_based_config = stage_base_config_loader.stage_config
        stage_base_config_loader.export_to_app_config(self.config)
        #   import ipdb; ipdb.set_trace()

        self._resolve_all_paths()

    def _update_config_from_dict_legacy(self, config_dict: Dict[str, Any]) -> None:
        """Update configuration from dictionary"""

        # Update ground coverage configuration
        if "ground_coverage" in config_dict:
            gc_config = config_dict["ground_coverage"]
            for key, value in gc_config.items():
                if hasattr(self.config.ground_coverage, key):
                    setattr(self.config.ground_coverage, key, value)

        # # Update task primitive configuration
        # if "task_primitive" in config_dict:
        #     tp_config = config_dict["task_primitive"]
        #     for key, value in tp_config.items():
        #         if hasattr(self.config.task_primitive, key):
        #             setattr(self.config.task_primitive, key, value)

        # Update process-based task configuration
        if "process_based_task" in config_dict:
            at_config = config_dict["process_based_task"]
            for key, value in at_config.items():
                if hasattr(self.config.process_based_task, key):
                    setattr(self.config.process_based_task, key, value)

        # Update scene configuration
        if "scene" in config_dict:
            scene_config = config_dict["scene"]
            for key, value in scene_config.items():
                if hasattr(self.config.scene, key):
                    setattr(self.config.scene, key, value)

        # Update scene type configuration
        if "scene_type" in config_dict:
            st_config = config_dict["scene_type"]
            for key, value in st_config.items():
                if hasattr(self.config.scene_type, key):
                    setattr(self.config.scene_type, key, value)

        # Update basic geometry configuration
        if "basic_geometry" in config_dict:
            bg_config = config_dict["basic_geometry"]
            for key, value in bg_config.items():
                if hasattr(self.config.basic_geometry, key):
                    setattr(self.config.basic_geometry, key, value)

        # Update image renderer configuration
        if "image_renderer" in config_dict:
            ir_config = config_dict["image_renderer"]
            for key, value in ir_config.items():
                if hasattr(self.config.image_renderer, key):
                    setattr(self.config.image_renderer, key, value)

        # Update concave processor configuration
        if "concave_processor" in config_dict:
            cp_config = config_dict["concave_processor"]
            for key, value in cp_config.items():
                if hasattr(self.config.concave_processor, key):
                    setattr(self.config.concave_processor, key, value)

        # Update OpenRouter configuration
        if "openrouter" in config_dict:
            or_config = config_dict["openrouter"]
            for key, value in or_config.items():
                if hasattr(self.config.openrouter, key):
                    setattr(self.config.openrouter, key, value)

        # Update mesh processor configuration
        if "meshprocessor" in config_dict:
            mp_config = config_dict["meshprocessor"]
            for key, value in mp_config.items():
                if hasattr(self.config.meshprocessor, key):
                    setattr(self.config.meshprocessor, key, value)

        # Update VLM interactor configuration
        if "vlm_interactor" in config_dict:
            vlm_config = config_dict["vlm_interactor"]
            for key, value in vlm_config.items():
                if hasattr(self.config.vlm_interactor, key):
                    setattr(self.config.vlm_interactor, key, value)

        # Update scene element configuration
        if "scene_element" in config_dict:
            se_config = config_dict["scene_element"]
            for key, value in se_config.items():
                if hasattr(self.config.scene_element, key):
                    setattr(self.config.scene_element, key, value)

        # Update rectangle query configuration
        if "rectangle_query" in config_dict:
            rq_config = config_dict["rectangle_query"]
            for key, value in rq_config.items():
                if hasattr(self.config.rectangle_query, key):
                    setattr(self.config.rectangle_query, key, value)

        # Update raw scene configuration
        if "raw_scene" in config_dict:
            rs_config = config_dict["raw_scene"]
            for key, value in rs_config.items():
                if hasattr(self.config.raw_scene, key):
                    setattr(self.config.raw_scene, key, value)

        # Update sapien configuration
        if "sapien" in config_dict:
            sap_config = config_dict["sapien"]
            for key, value in sap_config.items():
                if hasattr(self.config.sapien, key):
                    setattr(self.config.sapien, key, value)

        # Update benchmark executor configuration
        if "benchmark_executor" in config_dict:
            be_config = config_dict["benchmark_executor"]
            for key, value in be_config.items():
                if hasattr(self.config.benchmark_executor, key):
                    setattr(self.config.benchmark_executor, key, value)

        # Update task interaction configuration
        if "task_interaction" in config_dict:
            ti_config = config_dict["task_interaction"]
            for key, value in ti_config.items():
                if hasattr(self.config.task_interaction, key):
                    setattr(self.config.task_interaction, key, value)

        # Update outcome-based task generation configuration
        if "outcome_based_task_generation" in config_dict:
            obtg_config = config_dict["outcome_based_task_generation"]
            for key, value in obtg_config.items():
                if hasattr(self.config.outcome_based_task_generation, key):
                    setattr(self.config.outcome_based_task_generation, key, value)

        # Update rename engine configuration
        if "rename_engine" in config_dict:
            re_config = config_dict["rename_engine"]
            for key, value in re_config.items():
                if hasattr(self.config.rename_engine, key):
                    setattr(self.config.rename_engine, key, value)

        # Update global configuration
        for key in [
            "input_json_path",
            "output_json_path",
            "entity_json_path",
            "adjust_with_gravity",
            "use_renaming_engine",
            "bbox_only",
            "mode",
            "model_name",
            "log_level",
            "output_dir",
            "cache_enabled",
            "random_seed",
            "generate_mistake_note",
            "use_mistake_note",
            "result_file_path",
            "reflection_txt_load_path",
            "reflection_txt_save_path",
            "task_num",
            "scene_graph_pkl_load_path",
            "scene_graph_pkl_save_path",
            "process_based_task_pkl_load_path",
            "process_based_task_pkl_save_path",
            "image4rename_path",
            "image4interaction_path",
            "image4vote_path",
            "benchmark_prompt_template_path",
            "reflection_prompt_template_path",
            "rename_engine_prompt_template_path",
            "interact_prompt_template_path",
            "dataset_root_path",
            "stage_path_prefix",
            "visual_path_prefix",
            "collision_path_prefix",
            "urdf_path_prefix",
            "object_config_path",
            "rename_dict_path",
            "benchmark_model_name",
        ]:
            if key in config_dict:
                setattr(self.config, key, config_dict[key])

        self._resolve_all_paths()

    def update_from_args(self, args: argparse.Namespace) -> None:
        """Update configuration from command line arguments"""
        # Update ground coverage configuration
        if hasattr(args, "resolution") and args.resolution is not None:
            self.config.ground_coverage.resolution = args.resolution
        if hasattr(args, "min_rect_size") and args.min_rect_size is not None:
            self.config.ground_coverage.min_rect_size = args.min_rect_size

        # Update global configuration
        if hasattr(args, "log_level") and args.log_level is not None:
            self.config.log_level = args.log_level
        if hasattr(args, "output_dir") and args.output_dir is not None:
            self.config.output_dir = args.output_dir
        if hasattr(args, "debug") and args.debug is not None:
            self.config.process_based_task.debug_mode = args.debug
        if hasattr(args, "random_seed") and args.random_seed is not None:
            self.config.random_seed = args.random_seed

        # Update additional global configuration from args
        if (
            hasattr(args, "adjust_with_gravity")
            and args.adjust_with_gravity is not None
        ):
            self.config.adjust_with_gravity = args.adjust_with_gravity
        if (
            hasattr(args, "use_renaming_engine")
            and args.use_renaming_engine is not None
        ):
            self.config.use_renaming_engine = args.use_renaming_engine
        if hasattr(args, "bbox_only") and args.bbox_only is not None:
            self.config.bbox_only = args.bbox_only
        if hasattr(args, "input_file") and args.input_file is not None:
            self.config.input_file = args.input_file
        if hasattr(args, "mode") and args.mode is not None:
            self.config.mode = args.mode
        if hasattr(args, "model_name") and args.model_name is not None:
            self.config.model_name = args.model_name

    # def save_to_yaml(self, config_path: str) -> None:
    #     """Save current configuration to YAML file"""
    #     config_path = Path(config_path)
    #     try:
    #         with open(config_path, "w", encoding="utf-8") as f:
    #             yaml.dump(
    #                 self.config.__dict__,
    #                 f,
    #                 default_flow_style=False,
    #                 allow_unicode=True,
    #             )
    #         glog.info(f"Configuration saved to: {config_path}")
    #     except Exception as e:
    #         glog.info(f"Failed to save configuration: {e}")

    def save_to_yaml(self, config_path: str) -> None:
        """Save current configuration to YAML file"""
        config_path = Path(config_path)
        try:
            # Convert the dataclass to a dictionary
            config_dict = self._config_to_dict(self.config)
            # Ensure the directory exists
            config_path.parent.mkdir(parents=True, exist_ok=True)
            with open(config_path, "w", encoding="utf-8") as f:
                yaml.dump(
                    config_dict,
                    f,
                    default_flow_style=False,
                    allow_unicode=True,
                )
            glog.info(f"Configuration saved to: {config_path}")
        except Exception as e:
            glog.info(f"Failed to save configuration: {e}")

    def _convert_value_to_serializable(self, value: Any) -> Any:
        """Recursively converts values to be YAML-serializable, handling numpy types."""
        # Check if the value is a Numpy integer type
        if isinstance(value, np.integer):
            return int(value)
        # Check if the value is a Numpy floating type
        if isinstance(value, np.floating):
            return float(value)
        # Check if the value is a Numpy array
        if isinstance(value, np.ndarray):
            return value.tolist()

        if isinstance(value, list):
            return [self._convert_value_to_serializable(item) for item in value]
        if isinstance(value, tuple):
            return tuple(self._convert_value_to_serializable(item) for item in value)
        if isinstance(value, dict):
            return {k: self._convert_value_to_serializable(v) for k, v in value.items()}

        # Check if the value is another dataclass instance, recursively convert
        if hasattr(value, "__dict__") and not isinstance(value, type):
            return self._config_to_dict(value)

        return value

    def _config_to_dict(self, obj) -> Any:
        """Convert a configuration object to a dictionary, handling numpy types"""
        if obj is None:
            return None
        elif isinstance(obj, (str, int, bool)):
            return obj
        elif isinstance(obj, float):
            return float(obj)  # ensure float is standard Python float
        elif isinstance(obj, np.floating):
            return float(obj)  # turn numpy float into Python float
        elif isinstance(obj, np.integer):
            return int(obj)  # convert numpy integer to Python int
        elif isinstance(obj, np.ndarray):
            return obj.tolist()  # convert numpy array to list
        elif isinstance(obj, (list, tuple)):
            return [self._config_to_dict(item) for item in obj]
        elif isinstance(obj, dict):
            return {key: self._config_to_dict(value) for key, value in obj.items()}
        elif hasattr(obj, "__dataclass_fields__"):
            # handle dataclass objects
            result = {}
            for field in obj.__dataclass_fields__:
                value = getattr(obj, field)
                result[field] = self._config_to_dict(value)
            return result
        elif hasattr(obj, "__dict__"):
            # handle general objects
            result = {}
            for key, value in obj.__dict__.items():
                if not key.startswith("_"):  # skip private attributes
                    result[key] = self._config_to_dict(value)
            return result
        else:
            # Fallback for other types
            try:
                if isinstance(obj, (np.number, np.bool_)):
                    return obj.item()  # convert numpy scalar to native Python type
                else:
                    return obj
            except:
                return str(obj)

    def print_config(self) -> None:
        """Print current configuration"""
        glog.info("=" * 50)
        glog.info("Current Configuration:")
        glog.info(f"Ground Coverage Analyzer:")
        glog.info(f"  Resolution: {self.config.ground_coverage.resolution}")
        glog.info(f"  Min rectangle size: {self.config.ground_coverage.min_rect_size}")
        glog.info(f"  Z range: {self.config.ground_coverage.z_range}")
        glog.info(f"Task Primitive:")
        glog.info(f"  Default action: {self.config.task_primitive.default_action}")
        glog.info(
            f"  Support directions: {len(self.config.task_primitive.support_directions)} directions"
        )
        glog.info(f"Atomic Task:")
        glog.info(
            f"  Max intermediate states: {self.config.process_based_task.max_intermediate_states}"
        )
        glog.info(f"  Debug mode: {self.config.process_based_task.debug_mode}")
        glog.info(f"Scene Type:")
        glog.info(
            f"  Need collision adjustment: {self.config.scene_type.NEED_COLLISION_ADJUSTMENT}"
        )
        glog.info(f"  RGBD scene: {self.config.scene_type.RGBD_SCENE}")
        glog.info(f"Basic Geometry:")
        glog.info(f"  EPS: {self.config.basic_geometry.EPS}")
        glog.info(f"Image Renderer:")
        glog.info(f"  Default FOV: {self.config.image_renderer.default_fovy}")
        glog.info(
            f"  Resolution: {self.config.image_renderer.width}x{self.config.image_renderer.height}"
        )
        glog.info(f"  Z range: {self.config.image_renderer.z_range}")
        glog.info(f"Concave Processor:")
        glog.info(
            f"  Min polygon area: {self.config.concave_processor.min_polygon_area}"
        )
        glog.info(
            f"  Target aspect ratio: {self.config.concave_processor.target_aspect_ratio}"
        )
        glog.info(
            f"  Max target strips: {self.config.concave_processor.max_target_strips}"
        )
        glog.info(f"OpenRouter:")
        glog.info(f"  Model: {self.config.openrouter.model}")
        glog.info(f"Global:")
        glog.info(f"  Adjust with gravity: {self.config.adjust_with_gravity}")
        glog.info(f"  Use renaming engine: {self.config.use_renaming_engine}")
        glog.info(f"  BBox only: {self.config.bbox_only}")
        glog.info(f"  Mode: {self.config.mode}")
        glog.info(f"  Model name: {self.config.model_name}")
        glog.info(f"  Log level: {self.config.log_level}")
        glog.info(f"  Output directory: {self.config.output_dir}")
        glog.info(f"  Random seed: {self.config.random_seed}")
        glog.info("=" * 50)

    def save_to_json(self, config_path: str) -> None:
        """Save current configuration to JSON file"""
        config_path = Path(config_path)
        try:
            with open(config_path, "w", encoding="utf-8") as f:
                json.dump(self.config.__dict__, f, indent=4, ensure_ascii=False)
            glog.info(f"Configuration saved to: {config_path}")
        except Exception as e:
            glog.info(f"Failed to save configuration: {e}")

    def temp_set_model(self, model_name: str):

        model_config_dict = {"openrouter": {"model": model_name}}
        self._update_config_from_dict(model_config_dict)
        glog.info(f"Temporarily set model to {model_name}")


# Global configuration manager instance
config_manager = ConfigManager()


def get_config() -> AppConfig:
    """Get global configuration"""
    return config_manager.config


def get_config_manager() -> ConfigManager:
    """Get the global config manager instance"""
    return config_manager


def get_ground_coverage_config() -> GroundCoverageConfig:
    """Get ground coverage configuration"""
    return config_manager.config.ground_coverage


def get_image_renderer_config() -> ImageRendererConfig:
    """Get image renderer configuration"""
    return config_manager.config.image_renderer


def get_concave_processor_config() -> ConcaveProcessorConfig:
    """Get concave processor configuration"""
    return config_manager.config.concave_processor


def get_process_based_task_config() -> ProcessbasedTaskConfig:
    """Get atomic task configuration"""
    return config_manager.config.process_based_task


def get_scene_config() -> SceneConfig:
    """Get scene configuration"""
    return config_manager.config.scene


def get_scene_type_config() -> SceneType:
    """Get scene type configuration"""
    return config_manager.config.scene_type


def get_basic_geometry_config() -> BasicGeometryConfig:
    """Get basic geometry configuration"""
    return config_manager.config.basic_geometry


def get_openrouter_config() -> OpenRouterConfig:
    """Get OpenRouter configuration"""
    return config_manager.config.openrouter


def get_mesh_processor_config() -> MeshProcessorConfig:
    """Get MeshProcessor configuration"""
    return config_manager.config.meshprocessor


def get_vlm_interactor_config() -> VlmInteractorConfig:
    """Get VLM Interactor configuration"""
    return config_manager.config.vlm_interactor


def get_scene_element_config() -> SceneElementConfig:
    """Get Scene Element configuration"""
    return config_manager.config.scene_element


def get_rectangle_query_config() -> RectangleQueryConfig:
    """Get Rectangle Query configuration"""
    return config_manager.config.rectangle_query


def get_raw_scene_config() -> RawSceneConfig:
    """Get raw scene configuration"""
    return config_manager.config.raw_scene


def get_sapien_config() -> SapienConfig:
    """Get SAPIEN configuration"""
    return config_manager.config.sapien


def get_benchmark_executor_config() -> BenchmarkExecutorConfig:
    """Get Benchmark Executor configuration"""
    return config_manager.config.benchmark_executor


def get_task_interaction_config() -> TaskInteractionConfig:
    """Get Task Interaction configuration"""
    return config_manager.config.task_interaction


def get_outcome_based_task_generation_config() -> OutcomeBaseGenerationConfig:
    """Get Outcome Base Generation configuration"""
    return OutcomeBaseGenerationConfig()


def get_rename_engine_config() -> RenameEngineConfig:
    """Get Rename Engine configuration"""
    return config_manager.config.rename_engine


def init_config(config_file_path: Optional[str] = None) -> None:
    """Initialize global configuration manager with config file"""
    global config_manager
    config_manager = ConfigManager(config_file_path)


def main():

    config_manager = ConfigManager(config_file_path="configs/staged_config.yaml")

    config_manager._convert_app_config_to_staged_format()

    config_manager.save_to_yaml_staged("configs/staged_config_2.yaml")


if __name__ == "__main__":
    main()