[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 *  # move, pick, place, rotate, pull, normalize_quaternion

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 the open‐drawer and dispose‐rubbish task.'''
    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
        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()
        # Map names to the keys returned by get_object_positions()
        # side-pos-bottom  -> bottom_side_pos
        # anchor-pos-bottom -> bottom_anchor_pos
        # rubbish          -> rubbish
        # bin              -> bin
        try:
            side_pos = np.array(positions['bottom_side_pos'])
            anchor_pos = np.array(positions['bottom_anchor_pos'])
            rubbish_pos = np.array(positions['rubbish'])
            bin_pos = np.array(positions['bin'])
        except KeyError as e:
            raise RuntimeError(f"Missing position for {e} in object_positions()")

        # === Execute Oracle Plan ===
        # Step 1: move to side‐position of bottom drawer
        print("[Plan Step 1] move to side-pos-bottom:", side_pos)
        obs, reward, done = move(env, task, target_pos=side_pos)
        if done:
            print("[Plan] Ended early at step 1")
            return

        # Step 2: rotate gripper to 90 degrees about Z (approximate)
        print("[Plan Step 2] rotate gripper by 90° about Z")
        # Quaternion for 90° about Z: [x, y, z, w] = [0,0,sin(45°),cos(45°)]
        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] Ended early at step 2")
            return

        # Step 3: move gripper to anchor‐position of bottom drawer
        print("[Plan Step 3] move to anchor-pos-bottom:", anchor_pos)
        obs, reward, done = move(env, task, target_pos=anchor_pos)
        if done:
            print("[Plan] Ended early at step 3")
            return

        # Step 4: pull the drawer open
        print("[Plan Step 4] pull drawer open (distance=0.05)")
        obs, reward, done = pull(env, task, pull_distance=0.05, pull_axis='x')
        if done:
            print("[Plan] Ended early at step 4")
            return

        # Step 5: move to the rubbish object
        print("[Plan Step 5] move to rubbish at:", rubbish_pos)
        obs, reward, done = move(env, task, target_pos=rubbish_pos)
        if done:
            print("[Plan] Ended early at step 5")
            return

        # Step 6: pick up the rubbish
        print("[Plan Step 6] pick up rubbish")
        obs, reward, done = pick(env, task, target_pos=rubbish_pos)
        if done:
            print("[Plan] Ended early at step 6")
            return

        # Step 7: move to the bin
        print("[Plan Step 7] move to bin at:", bin_pos)
        obs, reward, done = move(env, task, target_pos=bin_pos)
        if done:
            print("[Plan] Ended early at step 7")
            return

        # Step 8: place the rubbish into the bin
        print("[Plan Step 8] place rubbish in bin")
        obs, reward, done = place(env, task, target_pos=bin_pos)
        if done:
            print("[Plan] Ended at final step with done=True. Reward:", reward)
        else:
            print("[Plan] Completed all steps. Final reward:", reward)

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

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

if __name__ == "__main__":
    run_skeleton_task()