[Frozen Code Start]
    
[Frozen Code End]

import numpy as np
from scipy.spatial.transform import Rotation as R
from skill_code import *
from env import setup_environment, shutdown_environment
from video import init_video_writers, recording_step, recording_get_observation
from object_positions import get_object_positions

def run_skeleton_task():
    print("===== Starting Skeleton Task =====")
    
    # === Environment Setup ===
    env, task = setup_environment()
    try:
        descriptions, obs = task.reset()
        init_video_writers(obs)
        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()

        # === Plan Execution ===

        # Step 1: Rotate gripper from zero_deg to ninety_deg (about Z axis)
        target_quat = R.from_euler('z', 90, degrees=True).as_quat()
        print("[Task] Step 1: Rotating gripper to 90 degrees around Z-axis")
        obs, reward, done = rotate(env, task, target_quat)
        if done:
            print("[Task] Ended after rotate. Reward:", reward)
            return

        # Step 2: Move gripper to the bottom side position of the drawer
        bottom_side_pos = np.array(positions['bottom_side_pos'])
        print("[Task] Step 2: Moving gripper to bottom side position:", bottom_side_pos)
        obs, reward, done = move(env, task, bottom_side_pos)
        if done:
            print("[Task] Ended after move. Reward:", reward)
            return

        # Step 3: Pull to open the drawer
        OPEN_DISTANCE = 0.1  # meters to pull
        print(f"[Task] Step 3: Pulling drawer by {OPEN_DISTANCE}m")
        obs, reward, done = pull(env, task, OPEN_DISTANCE)
        if done:
            print("[Task] Ended after pull. Reward:", reward)
            return

        # Step 4: Pick up the rubbish (assumed to be 'item3')
        rubbish_key = 'item3'
        rubbish_pos = np.array(positions[rubbish_key])
        print("[Task] Step 4: Picking up rubbish at:", rubbish_pos)
        obs, reward, done = pick(env, task, target_pos=rubbish_pos)
        if done:
            print("[Task] Ended after pick. Reward:", reward)
            return

        # Step 5: Place the rubbish into the bin
        bin_pos = np.array(positions['bin'])
        print("[Task] Step 5: Placing rubbish into bin at:", bin_pos)
        obs, reward, done = place(env, task, target_pos=bin_pos)
        if done:
            print("[Task] Completed successfully! Reward:", reward)
        else:
            print("[Task] Did not complete after place. Reward:", reward)

    except Exception as e:
        print(f"[Task] Exception occurred during execution: {e}")
    finally:
        shutdown_environment(env)

    print("===== End of Skeleton Task =====")

if __name__ == "__main__":
    run_skeleton_task()