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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
from typing import Callable, Dict, List
import numpy as np
import sys
import os
import inspect

from ...logging_utils import logger

# If run as script directly, add project root to sys.path
if __name__ == "__main__":
    # Get current file directory
    current_file = os.path.abspath(__file__)
    # Project root should be robomme-v5.7.2-sam2act-update
    project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(current_file))))
    if project_root not in sys.path:
        sys.path.insert(0, project_root)

from robomme.robomme_env.utils.subgoal_planner_func import (
    grasp_and_lift_peg_side,
    insert_peg,
    solve_button,
    solve_button_ready,
    solve_hold_obj,
    solve_hold_obj_absTimestep,
    solve_pickup,
    solve_pickup_bin,
    solve_push_to_target,
    solve_push_to_target_with_peg,
    solve_putdown_whenhold,
    solve_putonto_whenhold,
    solve_putonto_whenhold_binspecial,
    solve_swingonto,
    solve_swingonto_withDirection,
    solve_swingonto_whenhold,
    solve_strong_reset,
)


def _options_default(env, planner, require_target, base) -> List[dict]:
    options: List[dict] = []

    return options

def _options_videorepick(env, planner, require_target, base) -> List[dict]:
    options: List[dict] = [
        {
            "label": "a",
            "action": "pick up the cube",
            "solve": lambda require_target=require_target: solve_pickup(
                env, planner, obj=require_target()),
            "available": env.spawned_cubes
        },
        {
            "label": "b",
            "action": "put it down",
            "solve": lambda: solve_putdown_whenhold(
                env, planner, release_z=0.01
            ),
        },
    ]
    button_obj = getattr(base, "button_left", None)
    if button_obj is not None:
        options.append(
            {
                "label": "c",
                "action": "press the button to finish",
                "solve": lambda button_obj=button_obj: solve_button(
                    env, planner, obj=button_obj
                ),
            }
        )
    return options


def _options_binfill(env, planner, require_target, base) -> List[dict]:
    options: List[dict] = [
        {
            "label": "a",
            "action": "pick up the cube",
            "solve": lambda require_target=require_target: solve_pickup(
                env, planner, obj=require_target()
            ),
            "available": env.all_cubes,
        },
    ]
    target = getattr(base, "board_with_hole", None)
    if target is not None:
        options.append(
            {
                "label": "b",
                "action": "put it into the bin",
                "solve": lambda require_target=require_target, target=target: solve_putonto_whenhold_binspecial(
                    env, planner, target=target
                ),
            }
        )
    button_obj = getattr(base, "button", None)
    if button_obj is not None:
        options.append(
            {
                "label": "c",
                "action": "press the button",
                "solve": lambda button_obj=button_obj: solve_button(
                    env, planner, obj=button_obj
                ),
            }
        )
    return options


def _options_button_unmask(env, planner, require_target, base) -> List[dict]:
    options: List[dict] = []
    button_obj = getattr(base, "button_left", None) or getattr(base, "button", None)
    if button_obj is not None:
        options.append(
            {
                "label": "a",
                "action": "press the button",
                "solve": lambda button_obj=button_obj: solve_button(
                    env, planner, obj=button_obj
                ),
            }
        )

    options.extend([{
            "label": "b",
            "action": "pick up the container",
            "solve": lambda require_target=require_target: solve_pickup_bin(
                env, planner, obj=require_target()
            ),
            "available": env.spawned_bins,
        },
        {
            "label": "c",
            "action": "put down the container",
            "solve": lambda: solve_putdown_whenhold(
                env, planner
            ),
        },])
    return options

def _options_button_unmask_swap(env, planner, require_target, base) -> List[dict]:
    options: List[dict] = []
    button_obj_left = getattr(base, "button_left", None) or getattr(base, "button", None)
    if button_obj_left is not None:
        options.append(
            {
                "label": "a",
                "action": "press the first button",
                "solve": lambda button_obj=button_obj_left: solve_button(
                    env, planner, obj=button_obj
                ),
            }
        )
    button_obj_right = getattr(base, "button_right", None)
    if button_obj_right is not None:
        options.append(
            {
                "label": "b",
                "action": "press the second button",
                "solve": lambda button_obj=button_obj_right: solve_button(
                    env, planner, obj=button_obj
                ),
            }
        )


    options.extend([{
            "label": "c",
            "action": "pick up the container",
            "solve": lambda require_target=require_target: solve_pickup_bin(
                env, planner, obj=require_target()
            ),
            "available": env.spawned_bins,
            #"available": env.spawned_bins+[env.button_right],#test gradio execution error
        },
        {
            "label": "d",
            "action": "put down the container",
            "solve": lambda: solve_putdown_whenhold(
                env, planner
            ),
        },])
    return options 


def _options_insertpeg(env, planner, require_target, base) -> List[dict]:
    options: List[dict] = []

    options.append(
        {
            "label": "a",
            "action": "pick up the peg by grasping one end",
            "solve": lambda require_target=require_target: grasp_and_lift_peg_side(
                env, planner, obj=require_target()
            ),
            "available": env.peg_heads + env.peg_tails,
        }
    )

    options.append(
        {
            "label": "b",
            "action": "insert the peg from the right side",
            "solve": lambda direction=1: insert_peg(
                env,
                planner,
                direction=direction,
                obj=env.obj_flag,
                insert_obj=env.insert_target,
                cut_retreat=True,
            ),
        }
    )
    options.append(
        {
            "label": "c",
            "action": "insert the peg from the left side",# Keep consistent with subgoal
            "solve": lambda direction=-1: insert_peg(
                env,
                planner,
                direction=direction,
                obj=env.obj_flag,
                insert_obj=env.insert_target,
                cut_retreat=True,
            ),
        }
    )

    return options


def _options_movecube(env, planner, require_target, base) -> List[dict]:
    options: List[dict] = []
    cube = getattr(base, "cube", None)
    cube_goal = getattr(base, "goal_site", None)
    peg_target = getattr(base, "grasp_target", None)
    obj_flag = getattr(base, "obj_flag", None)
    direction1 = getattr(base, "direction1", None)
    direction2 = getattr(base, "direction2", None)

    if peg_target is not None:
        options.append(
            {
                "label": "a",
                "action": "pick up the peg",
                "solve": lambda peg_target=peg_target: grasp_and_lift_peg_side(
                    env, planner, obj=peg_target
                ),
            }
        )



    if cube is not None and cube_goal is not None and direction2 is not None and obj_flag is not None:
        options.append(
            {
                "label": "b",
                "action": "hook the cube to the target with the peg",
                "solve": lambda cube=cube, goal=cube_goal, direction=direction2, obj_flag=obj_flag: solve_push_to_target_with_peg(
                    env,
                    planner,
                    obj=cube,
                    target=goal,
                    direction=direction,
                    obj_flag=obj_flag,
                ),
            }
        )


    if cube is not None and cube_goal is not None:
        options.append(
            {
                "label": "c",
                "action": "close gripper and push the cube to the target",
                "solve": lambda cube=cube, goal=cube_goal: solve_push_to_target(
                    env, planner, obj=cube, target=goal
                ),
            }
        )
    if cube is not None and cube_goal is not None:
        options.append(
            {
                "label": "d",
                "action": "pick up the cube",
                "solve": lambda cube=cube: solve_pickup(env, planner, obj=cube),
            }
        )
        options.append(
            {
                "label": "e",
                "action": "place the cube onto the target",
                "solve": lambda cube=cube, goal=cube_goal: solve_putonto_whenhold(
                    env, planner,target=goal
                ),
            }
        )

    return options


def _options_patternlock(env, planner, require_target, base) -> List[dict]:
    """
    Dynamically pick the nearest target to the current TCP and move to the
    closest neighbour along the requested direction.
    """
    directions = [
        "forward",
        "backward",
        "left",
        "right",
        "forward-left",
        "forward-right",
        "backward-left",
        "backward-right",
    ]

    dir_vectors = {
        "forward": np.array([1.0, 0.0]),
        "backward": np.array([-1.0, 0.0]),
        "left": np.array([0.0, 1.0]),
        "right": np.array([0.0, -1.0]),
        "forward-left": np.array([1.0, 1.0]) / np.sqrt(2.0),
        "forward-right": np.array([1.0, -1.0]) / np.sqrt(2.0),
        "backward-left": np.array([-1.0, 1.0]) / np.sqrt(2.0),
        "backward-right": np.array([-1.0, -1.0]) / np.sqrt(2.0),
    }

    # Quick half-plane filters so we only consider targets in the intended direction.
    eps = 1e-6
    dir_filters = {
        "forward": lambda dx, dy: dx > eps,
        "backward": lambda dx, dy: dx < -eps,
        "left": lambda dx, dy: dy > eps,
        "right": lambda dx, dy: dy < -eps,
        "forward-left": lambda dx, dy: dx > eps and dy > eps,
        "forward-right": lambda dx, dy: dx > eps and dy < -eps,
        "backward-left": lambda dx, dy: dx < -eps and dy > eps,
        "backward-right": lambda dx, dy: dx < -eps and dy < -eps,
    }

    def _actor_xy(actor):
        pose = getattr(actor, "pose", None)
        if pose is None:
            pose = actor.get_pose() if hasattr(actor, "get_pose") else None
        pos = getattr(pose, "p", None)
        if pos is None:
            return None
        arr = np.asarray(pos).reshape(-1)
        return arr[:2] if arr.size >= 2 else None

    def _collect_targets():
        """
        Gather all available target actors (targets_grid/buttons_grid/selected_buttons)
        and deduplicate by object id.
        """
        buckets = (
            getattr(base, "targets_grid", None),
            getattr(base, "buttons_grid", None),
            getattr(base, "selected_buttons", None),
        )
        seen = set()
        targets = []
        for bucket in buckets:
            if not bucket:
                continue
            for t in bucket:
                if t is None:
                    continue
                t_id = id(t)
                if t_id in seen:
                    continue
                seen.add(t_id)
                targets.append(t)
        return targets

    def _closest_target_to_tcp():
        targets = _collect_targets()
        if not targets:
            raise ValueError("PatternLock requires targets_grid/buttons_grid to be initialized.")

        tcp_pose = np.asarray(env.agent.tcp.pose.p).reshape(-1)
        if tcp_pose.size < 2:
            raise ValueError("TCP pose does not provide x/y coordinates.")
        tcp_xy = tcp_pose[:2]

        dist_list = []
        for t in targets:
            t_xy = _actor_xy(t)
            if t_xy is None:
                continue
            dist = float(np.linalg.norm(t_xy - tcp_xy))
            dist_list.append((dist, t, t_xy))

        if not dist_list:
            raise ValueError("PatternLock could not compute any valid target positions.")

        dist_list.sort(key=lambda item: item[0])
        return dist_list[0][1], dist_list[0][2], targets

    def _target_for_direction(dir_label: str):
        ref_target, ref_xy, candidates = _closest_target_to_tcp()
        vec = dir_vectors[dir_label]
        filt = dir_filters[dir_label]

        best = None
        best_score = None
        for cand in candidates:
            if cand is ref_target:
                continue
            c_xy = _actor_xy(cand)
            if c_xy is None:
                continue
            delta = c_xy - ref_xy
            if delta.shape[0] < 2:
                continue
            dx, dy = float(delta[0]), float(delta[1])
            if not filt(dx, dy):
                continue
            dist = float(np.linalg.norm(delta))
            if dist < eps:
                continue
            if dist>0.2:
                continue  # max distance threshold, won't select points too far
            align = float(np.dot(delta / dist, vec))
            score = (-align*0.5, dist)  # prioritize alignment, then closeness
            if best_score is None or score < best_score:
                best_score = score
                best = cand

        if best is None:
            logger.debug(f"[PatternLock] No candidate in direction '{dir_label}', using nearest target.")
            best = ref_target
        return best

    def _solve_direction(chosen_dir: str):
        try:
            target = _target_for_direction(chosen_dir)
        except ValueError as e:
            logger.debug(f"[PatternLock] {e}")
            return

        record_flag = getattr(base, "swing_qpos", None) is None
        return [solve_swingonto(env, planner, target=target),solve_swingonto(env, planner, target=target)]

    options: List[dict] = []
    for i, dir_label in enumerate(directions):
        options.append(
            {
                "label": chr(ord("a") + i),
                "action": f"move {dir_label}",
                "solve": (lambda d=dir_label: _solve_direction(d)),
            }
        )
    return options


def _options_routestick(env, planner, require_target, base) -> List[dict]:
    def _solve_route(side: str, direction: str):
        """
        Choose a target stick based on the desired side and move around it
        using the requested rotation direction.
        - side: "left"/"right" → pick the nearest target on that side of the
          last visited stick (fallback: current gripper position).
        - direction: "clockwise"/"counterclockwise" (accept short aliases).
        """
        # Normalize direction text
        dir_map = {
            "clock": "clockwise",
            "clockwise": "clockwise",
            "cw": "clockwise",
            "counterclock": "counterclockwise",
            "counterclockwise": "counterclockwise",
            "anticlockwise": "counterclockwise",
            "ccw": "counterclockwise",
        }
        direction_norm = dir_map.get(str(direction).lower(), "counterclockwise")

        def _actor_xy(a):
            if a is None:
                return None
            pose = getattr(a, "pose", None)
            if pose is None:
                pose = a.get_pose()
            p = getattr(pose, "p", None)
            if p is None:
                return None
            arr = np.asarray(p).reshape(-1)
            return arr[:2] if arr.size >= 2 else None

        # Reference actor: allowed button nearest to current TCP.
        ref_actor = None

        # Candidate targets: strictly use allowed indices on the buttons grid.
        grid = list(getattr(base, "buttons_grid", []) or [])
        allowed_idx = [int(i) for i in getattr(base, "route_button_indices", [0, 2, 4, 6, 8])]
        allowed_set = set(allowed_idx)
        allowed_candidates = [
            (idx, actor) for idx, actor in enumerate(grid) if idx in allowed_set and actor is not None
        ]

        # Pick reference as the allowed button closest to the current TCP.
        tcp_pose = np.asarray(env.agent.tcp.pose.p).reshape(-1)
        tcp_xy = tcp_pose[:2] if tcp_pose.size >= 2 else None
        dist_list = []
        for idx, actor in allowed_candidates:
            xy = _actor_xy(actor)
            if xy is None or tcp_xy is None:
                continue
            dist_list.append((np.linalg.norm(xy - tcp_xy), idx, actor))

        if dist_list:
            _, ref_idx, ref_actor = min(dist_list, key=lambda item: item[0])
        elif allowed_candidates:
            ref_idx, ref_actor = allowed_candidates[0]
        else:
            ref_idx, ref_actor = 0, None

        candidates = [(idx, actor) for idx, actor in allowed_candidates if actor is not ref_actor]

        if not candidates:
            raise ValueError("RouteStick: no available targets to swing onto.")

        side_l = str(side).lower()
        side_candidates = []
        for idx, actor in candidates:
            if side_l == "left" and idx > ref_idx:
                side_candidates.append((idx, actor))
            elif side_l == "right" and idx < ref_idx:
                side_candidates.append((idx, actor))

        
        if not side_candidates:
            # Fallback: if no candidate on the requested side, pick the nearest available candidate
            # from the general 'candidates' list (which excludes the reference/current button).
            fallback_target = None
            min_dist = float('inf')
            for idx, actor in allowed_candidates:
                xy = _actor_xy(actor)
                if xy is not None and tcp_xy is not None:
                    d = np.linalg.norm(xy - tcp_xy)
                    if d < min_dist:
                        min_dist = d
                        fallback_target = actor
            
            if fallback_target is None:
                # Should typically not happen if candidates is not empty
                if candidates:
                    fallback_target = allowed_candidates[0][1]
                else:
                    raise ValueError("RouteStick: failed to determine a target for the selected side.")

            logger.debug(f"RouteStick: failed to determine a target for side '{side_l}'. Fallback to nearest target.")
            return solve_swingonto(env, planner, target=fallback_target)

        # Pick the closest candidate by index in the requested direction (no distance check).
        if side_l == "left":
            _target_idx, target = min(side_candidates, key=lambda item: item[0] - ref_idx)
        else:
            _target_idx, target = min(side_candidates, key=lambda item: ref_idx - item[0])

        swing_radius = float(getattr(base, "swing_radius", 0.2) or 0.2)
        return solve_swingonto_withDirection(
            env, planner, target=target, radius=swing_radius, direction=direction_norm
        )


    options: List[dict] = []
    option_defs = [
        ("move to the nearest left target by circling around the stick clockwise", "left", "clockwise"),
        ("move to the nearest right target by circling around the stick clockwise", "right", "clockwise"),
        ("move to the nearest left target by circling around the stick counterclockwise", "left", "counterclockwise"),
        ("move to the nearest right target by circling around the stick counterclockwise", "right", "counterclockwise"),
    ]
    for i, (action_text, side, direction) in enumerate(option_defs):
        options.append(
            {
                "label": chr(ord("a") + i),
                "action": action_text,
                "solve": (lambda s=side, d=direction: _solve_route(s, d)),
            }
        )
    return options

def _options_pickhighlight(env, planner, require_target, base) -> List[dict]:
    options: List[dict] = []

    button_obj = getattr(base, "button", None) or getattr(base, "button_left", None)
    if button_obj is not None:
        options.append(
            {
                "label": "a",
                "action": "press button",
                "solve": lambda button_obj=button_obj: solve_button(
                    env, planner, obj=button_obj
                ),
            }
        )

    target_cubes = list(getattr(base, "target_cubes", []) or [])
    target_labels = list(getattr(base, "target_labels", []) or []) or getattr(
        base, "target_cube_names", []
    )

    options.extend(
        [
            {
                "label": "b",
                "action": "pick up the highlighted cube",
                "solve": lambda require_target=require_target: solve_pickup(
                    env, planner, obj=require_target()
                ),
                'available': env.all_cubes,
            },
            {
                "label": "c",
                "action": "place the cube onto the table",
                "solve": lambda: solve_putdown_whenhold(
                    env, planner, release_z=0.01
                ),
            },
        ]
    )

    return options

def _options_pickxtimes(env, planner, require_target, base) -> List[dict]:
    options: List[dict] = []
    options.extend(
        [
            {
                "label": "a",
                "action": "pick up the cube",
                "solve": lambda require_target=require_target: solve_pickup(
                    env, planner, obj=require_target()
                ),
                "available": env.all_cubes,
            },
            {
                "label": "b",
                "action": "place the cube onto the target",
                "solve": lambda require_target=require_target: solve_putonto_whenhold(
                    env, planner, target=env.target
                ),
            },
            {
                "label": "c",
                "action": "press the button to stop",
                "solve": lambda: solve_button(
                    env, planner, obj=env.button
                ),
            }
        ]
    )

    return options

def _options_swingxtimes(env, planner, require_target, base) -> List[dict]:
    options: List[dict] = []

    options.append(
        {
            "label": "a",
            "action": "pick up the cube",
            "solve": lambda require_target=require_target: solve_pickup(
                env, planner, obj=require_target()
            ),
            "available": env.all_cubes,
        }
    )

    target_cube = getattr(base, "target_cube", None)
    if target_cube is not None:
        options.append(
            {
                "label": "b",
                "action": "move to the top of the target",
                "solve": lambda require_target=require_target, target_cube=target_cube: solve_swingonto_whenhold(
                    env,
                    planner,
                    target=require_target(),
                    height=0.1,
                ),
                "available": [env.target_right]+[env.target_left],
            }
        )
        options.append(
            {
                "label": "c",
                "action": "put the cube on the table",
                "solve": lambda target_cube=target_cube: solve_putdown_whenhold(
                    env, planner
                ),
            }
        )

    button_obj = getattr(base, "button", None) or getattr(base, "button_left", None)
    if button_obj is not None:
        options.append(
            {
                "label": "d",
                "action": "press the button",
                "solve": lambda button_obj=button_obj: solve_button(
                    env, planner, obj=button_obj
                ),
            }
        )

    return options

def _options_videoplaceorder(env, planner, require_target, base) -> List[dict]:
    options: List[dict] = [
        {
            "label": "a",
            "action": "pick up the cube",
            "solve": lambda require_target=require_target: solve_pickup(
                env, planner, obj=require_target()
            ),
            "available": env.all_cubes,
        },
    ]

    target_cube = getattr(base, "target_cube", None)
    if target_cube is not None:
        options.append(
            {
                "label": "b",
                "action": "drop onto",
                "solve": lambda require_target=require_target, target_cube=target_cube: solve_putonto_whenhold(
                    env, planner, target=require_target()
                ),
                "available": env.targets,
            }
        )

    button_obj = getattr(base, "button", None) or getattr(base, "button_left", None)
    if button_obj is not None:
        options.append(
            {
                "label": "c",
                "action": "press the button",
                "solve": lambda button_obj=button_obj: solve_button(
                    env, planner, obj=button_obj
                ),
            }
        )

    return options
def _options_videoplacebutton(env, planner, require_target, base) -> List[dict]:
    options: List[dict] = [
        {
            "label": "a",
            "action": "pick up the cube",
            "solve": lambda require_target=require_target: solve_pickup(
                env, planner, obj=require_target()
            ),
            "available": env.all_cubes,
        },
    ]

    target_cube = getattr(base, "target_cube", None)
    if target_cube is not None:
        options.append(
            {
                "label": "b",
                "action": "drop onto",
                "solve": lambda target_cube=target_cube: solve_putonto_whenhold(
                    env, planner, target=require_target()
                ),
                "available": env.targets,
            }
        )

    button_obj = getattr(base, "button", None) or getattr(base, "button_left", None)
    if button_obj is not None:
        options.append(
            {
                "label": "c",
                "action": "press the button",
                "solve": lambda button_obj=button_obj: solve_button(
                    env, planner, obj=button_obj
                ),
            }
        )

    return options


def _options_stopcube(env, planner, require_target, base) -> List[dict]:
    options: List[dict] = []
    button_obj = getattr(base, "button", None)

    if button_obj is not None:
        options.append(
            {
                "label": "a",
                "action": "move to the top of the button to prepare",
                "solve": lambda button_obj=button_obj: solve_button_ready(
                    env, planner, obj=button_obj
                ),
            }
        )

    steps_press = getattr(base, "steps_press", None)
    if steps_press is not None:
        def solve_with_incremental_steps():
            steps_press_value = getattr(base, "steps_press", None)
            if steps_press_value is None:
                return None

            interval = getattr(base, "interval", 30)
            final_target = max(0, int(steps_press_value - interval))
            current_step = int(getattr(env, "elapsed_steps", 0))

            checkpoints_key = "_stopcube_static_checkpoints"
            index_key = "_stopcube_static_index"
            cached_final_target_key = "_stopcube_static_final_target"
            last_elapsed_step_key = "_stopcube_static_last_elapsed_step"

            checkpoints = getattr(base, checkpoints_key, None)
            index = getattr(base, index_key, None)
            cached_final_target = getattr(base, cached_final_target_key, None)
            last_elapsed_step = getattr(base, last_elapsed_step_key, None)

            needs_rebuild = (
                not isinstance(checkpoints, list)
                or len(checkpoints) == 0
                or index is None
                or cached_final_target is None
                or int(cached_final_target) != final_target
                or (
                    last_elapsed_step is not None
                    and current_step < int(last_elapsed_step)
                )
            )

            if needs_rebuild:
                checkpoints = list(range(100, final_target, 100))
                if not checkpoints or checkpoints[-1] != final_target:
                    checkpoints.append(final_target)
                index = 0
            else:
                index = int(index)
                if index < 0:
                    index = 0
                
                if index >= len(checkpoints):
                    index = len(checkpoints) - 1

            target = checkpoints[index]
            solve_hold_obj_absTimestep(env, planner, absTimestep=target)

            index += 1

            setattr(base, checkpoints_key, checkpoints)
            setattr(base, index_key, index)
            setattr(base, cached_final_target_key, final_target)
            setattr(base, last_elapsed_step_key, current_step)

            return None

        options.append(
            {
                "label": "b",
                "action": "remain static",
                "solve": solve_with_incremental_steps,
            }
        )

    if button_obj is not None:
        options.append(
            {
                "label": "c",
                "action": "press button to stop the cube",
                "solve": lambda button_obj=button_obj: solve_button(
                    env, planner, obj=button_obj, without_hold=True
                ),
            }
        )

    return options
def _options_video_unmask(env, planner, require_target, base) -> List[dict]:
    options: List[dict] = []
    options.extend([{
            "label": "a",
            "action": "pick up the container",
            "solve": lambda require_target=require_target: solve_pickup_bin(
                env, planner, obj=require_target()
            ),
            "available": env.spawned_bins,
        },
        {
            "label": "b",
            "action": "put down the container",
            "solve": lambda: solve_putdown_whenhold(
                env, planner
            ),
        },])
    return options

def _options_video_unmask_swap(env, planner, require_target, base) -> List[dict]:
    options: List[dict] = []
    options.extend([{
            "label": "a",
            "action": "pick up the container",
            "solve": lambda require_target=require_target: solve_pickup_bin(
                env, planner, obj=require_target()
            ),
            "available": env.spawned_bins,
        },
        {
            "label": "b",
            "action": "put down the container",
            "solve": lambda: solve_putdown_whenhold(
                env, planner
            ),
        },])
    return options

OPTION_BUILDERS: Dict[str, Callable] = {
    "VideoRepick": _options_videorepick,
    "BinFill": _options_binfill,
    "ButtonUnmask": _options_button_unmask,
    "ButtonUnmaskSwap": _options_button_unmask_swap,
    "InsertPeg": _options_insertpeg,
    "MoveCube": _options_movecube,
    "PatternLock": _options_patternlock,
    "PickHighlight": _options_pickhighlight,
    "PickXtimes": _options_pickxtimes,
    "RouteStick": _options_routestick,
    "SwingXtimes": _options_swingxtimes,
    "StopCube": _options_stopcube,
    "VideoPlaceButton": _options_videoplacebutton,
    "VideoPlaceOrder": _options_videoplaceorder,
    "VideoUnmask": _options_video_unmask,
    "VideoUnmaskSwap": _options_video_unmask_swap,
    
}


def get_vqa_options(env, planner, selected_target, env_id: str) -> List[dict]:
    """
    Return a fixed set of options (label + solve) based on env_id.
    Target object provided in selected_target after GUI click.
    """
    def _require_target():
        obj = selected_target.get("obj")
        if obj is None:
            raise ValueError("No available target cube found, please click target in segmentation map first.")
        return obj

    base = env.unwrapped
    builder = OPTION_BUILDERS.get(env_id, _options_default)
    return builder(env, planner, _require_target, base)


if __name__ == "__main__":
    """Print options label for all tasks"""
    class MockEnv:
        def __init__(self):
            self.spawned_cubes = ["cube1"]
            self.all_cubes = ["cube1", "cube2"]
            self.spawned_bins = ["bin1"]
            self.targets = ["target1"]
            self.target_right = "target_right"
            self.target_left = "target_left"
            # For InsertPeg
            self.peg_heads = ["peg_head"]
            self.peg_tails = ["peg_tail"]
            self.obj_flag = "obj_flag"
            self.insert_target = "insert_target"
            # For PickXtimes
            self.target = "target"
            self.button = "button"
    
    class MockBase:
        def __init__(self):
            # Common objects
            self.button = "button"
            self.button_left = "button_left"
            self.button_right = "button_right"
            self.cube = "cube"
            self.target = "target"
            
            # BinFill
            self.board_with_hole = "board_with_hole"
            
            # MoveCube
            self.goal_site = "goal_site"
            self.grasp_target = "grasp_target"
            self.obj_flag = "obj_flag"
            self.direction1 = 1
            self.direction2 = 1
            
            # PickHighlight
            self.target_cubes = ["cube1"]
            self.target_labels = ["cube1"]
            self.target_cube_names = ["cube1"]
            
            # SwingXtimes / VideoPlaceOrder / VideoPlaceButton
            self.target_cube = "target_cube"
            
            # StopCube
            self.steps_press = 100
            self.interval = 30
            
            # PatternLock / RouteStick (mocking basic lists to avoid attribute errors if accessed)
            self.targets_grid = []
            self.buttons_grid = []
            self.selected_buttons = []
            self.route_button_indices = []
    
    env = MockEnv()
    planner = None
    base = MockBase()
    
    def _require_target():
        return None
    
    logger.debug("=" * 80)
    logger.debug("Options Labels for all tasks:")
    logger.debug("=" * 80)
    
    for task_name, builder_func in OPTION_BUILDERS.items():
        try:
            options = builder_func(env, planner, _require_target, base)
            logger.debug(f"\nTask: {task_name}")
            valid_options = [opt for opt in options if isinstance(opt, dict)]
            logger.debug(f"  Options Labels ({len(valid_options)} items):")
            
            for i, opt in enumerate(valid_options, 1):
                label = opt.get("label", "No label")
                action = opt.get("action", "")
                solve_func = opt.get("solve")
                needs_target = False
                if solve_func:
                    try:
                        sig = inspect.signature(solve_func)
                        if "require_target" in sig.parameters:
                            needs_target = True
                    except ValueError:
                        pass
                
                target_str = " [Need click target]" if needs_target else ""
                action_str = f" - {action}" if action else ""
                logger.debug(f"    {i}. {label}{action_str}{target_str}")
        except Exception as e:
            logger.debug(f"\nTask: {task_name}")
            logger.debug(f"  Error: Failed to get options - {type(e).__name__}: {e}")
    
    logger.debug("\n" + "=" * 80)


# You need to add the environment library path to LD_LIBRARY_PATH environment variable to force program to load libraries within environment first.
# You can run your script with the following command:
# export LD_LIBRARY_PATH=/home/hongzefu/micromamba/envs/maniskillenv1228/lib:$LD_LIBRARY_PATH
# /home/hongzefu/micromamba/envs/maniskillenv1228/bin/python /home/hongzefu/robomme-v5.7.2-sam2act-update/robomme/robomme_env/util/vqa_options.py