[Frozen Code Start]

[Frozen Code End]

import numpy as np
from pyrep.objects.shape import Shape
from pyrep.objects.proximity_sensor import ProximitySensor

from env import setup_environment, shutdown_environment

from skill_code import *
from video import init_video_writers, recording_step, recording_get_observation
from object_positions import get_object_positions

def run_skeleton_task():
    '''Task logic to unlock the cabinet by opening an accessible drawer.'''
    print("===== Starting Skeleton Task =====")
    env, task = setup_environment()
    try:
        descriptions, obs = task.reset()
        init_video_writers(obs)
        # wrap step and get_observation for recording
        original_step = task.step
        task.step = recording_step(original_step)
        original_get_obs = task.get_observation
        task.get_observation = recording_get_observation(original_get_obs)

        # retrieve object positions
        positions = get_object_positions()
        # use bottom drawer positions
        side_pos = positions['bottom_side_pos']
        anchor_pos = positions['bottom_anchor_pos']

        # Step 1: rotate gripper to 90 degrees around z-axis
        print("[Plan] Step 1: rotate to 90° around z-axis")
        quat_ninety = np.array([0., 0., np.sin(np.pi/4), np.cos(np.pi/4)])
        obs, reward, done = rotate(env, task, quat_ninety)
        if done:
            print("[Plan] ended prematurely after rotate")
            return

        # Step 2: move to the side position of the drawer
        print("[Plan] Step 2: move to side position at", side_pos)
        obs, reward, done = move(env, task, np.array(side_pos))
        if done:
            print("[Plan] ended prematurely after move-to-side")
            return

        # Step 3: move to the anchor (handle) position of the drawer
        print("[Plan] Step 3: move to anchor position at", anchor_pos)
        obs, reward, done = move(env, task, np.array(anchor_pos))
        if done:
            print("[Plan] ended prematurely after move-to-anchor")
            return

        # Step 4: pick the drawer handle
        print("[Plan] Step 4: pick at anchor position")
        obs, reward, done = pick(env, task, np.array(anchor_pos))
        if done:
            print("[Plan] ended prematurely after pick")
            return

        # Step 5: pull the drawer open along the +x axis
        pull_distance = 0.1
        print(f"[Plan] Step 5: pull drawer by {pull_distance}m along x-axis")
        obs, reward, done = pull(env, task, pull_distance, pull_axis='x')
        if done:
            print("[Plan] Task ended after pull. Reward:", reward)
        else:
            print("[Plan] Pull completed, drawer should now be open. Reward:", reward)

    except Exception as e:
        print("[Error] Exception during task execution:", e)
    finally:
        shutdown_environment(env)
    print("===== End of Skeleton Task =====")

if __name__ == "__main__":
    run_skeleton_task()