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()
        bottom_side_pos = np.array(positions['bottom_side_pos'])
        bottom_anchor_pos = np.array(positions['bottom_anchor_pos'])

        # === Execute Oracle Plan ===

        # Step 1: Rotate gripper from zero_deg to ninety_deg
        print("[Task] Step 1: Rotating gripper to 90 degrees about Z")
        # Quaternion for 90° rotation around Z in xyzw format
        target_quat = np.array([0.0, 0.0, 0.7071, 0.7071])
        obs, reward, done = rotate(env, task, target_quat)
        if done:
            print("[Task] Task ended during rotate.")
            return

        # Step 2: Move gripper to the side position of the bottom drawer
        print("[Task] Step 2: Moving to bottom drawer side position:", bottom_side_pos)
        obs, reward, done = move(env, task, target_pos=bottom_side_pos)
        if done:
            print("[Task] Task ended during move to side.")
            return

        # Step 3: Move gripper to the anchor position of the bottom drawer
        print("[Task] Step 3: Moving to bottom drawer anchor position:", bottom_anchor_pos)
        obs, reward, done = move(env, task, target_pos=bottom_anchor_pos)
        if done:
            print("[Task] Task ended during move to anchor.")
            return

        # Step 4: Pick the bottom drawer at its anchor position
        print("[Task] Step 4: Picking bottom drawer at anchor position")
        obs, reward, done = pick(env, task, target_pos=bottom_anchor_pos)
        if done:
            print("[Task] Task ended during pick.")
            return

        # Step 5: Pull open the bottom drawer
        print("[Task] Step 5: Pulling open bottom drawer")
        obs, reward, done = pull(env, task, pull_distance=0.2, pull_axis='x')
        if done:
            print("[Task] Drawer pull completed with done=True. Reward:", reward)
        else:
            print("[Task] Drawer pull completed. Reward:", reward)

        print("[Task] Goal reached: bottom drawer opened.")

    finally:
        # Always ensure the environment is properly shutdown
        shutdown_environment(env)

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

if __name__ == "__main__":
    run_skeleton_task()