[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():
    '''Generic skeleton for running any task in your simulation.'''
    print("===== Starting Skeleton Task =====")
    
    # === Environment Setup ===
    env, task = setup_environment()
    try:
        # Reset the task to its initial state
        descriptions, obs = task.reset()

        # (Optional) Initialize video writers for capturing your simulation
        init_video_writers(obs)

        # Wrap the task steps for recording (if needed)
        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()
        # Expected keys in positions dict:
        #   'bottom_side_pos', 'bottom_anchor_pos', 'nowhere_pos',
        #   'table', 'bin', 'rubbish'
        try:
            bottom_side_pos = positions['bottom_side_pos']
            bottom_anchor_pos = positions['bottom_anchor_pos']
            nowhere_pos = positions.get('nowhere_pos', None)
            table_pos = positions['table']
            bin_pos = positions['bin']
            rubbish_pos = positions['rubbish']
        except KeyError as e:
            print(f"[Error] Missing object position: {e}")
            return

        # === Execute Oracle Plan ===

        # Step 1: Rotate gripper from zero_deg to ninety_deg
        print("[Plan] Step 1: rotate to ninety_deg")
        # Define quaternion for 90° about the local z-axis: [x, y, z, w]
        target_quat = np.array([0.0, 0.0, np.sin(np.pi/4), np.cos(np.pi/4)])
        obs, reward, done = rotate(env, task, target_quat)
        if done:
            print("[Plan] Terminated after rotation with reward:", reward)
            return

        # Step 2: Move gripper to side position of bottom drawer
        print("[Plan] Step 2: move-to-side (nowhere -> bottom_side_pos)")
        obs, reward, done = move(env, task, bottom_side_pos)
        if done:
            print("[Plan] Terminated after move-to-side with reward:", reward)
            return

        # Step 3: Move gripper to anchor position of bottom drawer
        print("[Plan] Step 3: move-to-anchor (side -> anchor)")
        obs, reward, done = move(env, task, bottom_anchor_pos)
        if done:
            print("[Plan] Terminated after move-to-anchor with reward:", reward)
            return

        # Step 4: Pick the drawer handle (at anchor position)
        print("[Plan] Step 4: pick drawer handle")
        obs, reward, done = pick(env, task, bottom_anchor_pos)
        if done:
            print("[Plan] Terminated after pick-drawer with reward:", reward)
            return

        # Step 5: Pull the drawer open
        print("[Plan] Step 5: pull drawer")
        # Assume a pull distance of 0.1m along the local x-axis opens the drawer
        obs, reward, done = pull(env, task, pull_distance=0.1, pull_axis='x')
        if done:
            print("[Plan] Terminated after pull with reward:", reward)
            return

        # Step 6: Pick up the rubbish on the table
        print("[Plan] Step 6: pick rubbish")
        obs, reward, done = pick(env, task, rubbish_pos)
        if done:
            print("[Plan] Terminated after picking rubbish with reward:", reward)
            return

        # Step 7: Place the rubbish into the bin
        print("[Plan] Step 7: place rubbish in bin")
        obs, reward, done = place(env, task, bin_pos)
        if done:
            print("[Plan] Completed placing rubbish with reward:", reward)
            return

        # Final report
        print("[Plan] Oracle plan executed. Final reward:", reward)

    except Exception as e:
        print(f"[Exception] During plan execution: {e}")
    finally:
        # Always ensure the environment is properly shutdown
        shutdown_environment(env)

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

if __name__ == "__main__":
    run_skeleton_task()