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
from scipy.spatial.transform import Rotation as R

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()

        # Compute orientation quaternions for zero_deg and ninety_deg around Z axis
        zero_quat = R.from_euler('z', 0, degrees=True).as_quat()
        ninety_quat = R.from_euler('z', 90, degrees=True).as_quat()

        # === Execute Oracle Plan Steps ===

        # Step 1: Rotate the gripper from zero_deg to ninety_deg
        print("[Task] Step 1: Rotating gripper from zero_deg to ninety_deg")
        [Frozen Code Start]
        obs, reward, done = rotate(env, task, target_quat=ninety_quat)
        [Frozen Code End]
        if done:
            print("[Task] Task ended after rotation. Reward:", reward)
            return

        # Step 2: Move to the side position of the bottom drawer
        side_bottom = positions['bottom_side_pos']
        print(f"[Task] Step 2: Moving gripper to bottom side position: {side_bottom}")
        obs, reward, done = move(env, task, target_pos=side_bottom)
        if done:
            print("[Task] Task ended after moving to side position. Reward:", reward)
            return

        # Step 3: Move to the anchor position of the bottom drawer
        anchor_bottom = positions['bottom_anchor_pos']
        print(f"[Task] Step 3: Moving gripper to bottom anchor position: {anchor_bottom}")
        obs, reward, done = move(env, task, target_pos=anchor_bottom)
        if done:
            print("[Task] Task ended after moving to anchor position. Reward:", reward)
            return

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

        # Step 5: Pull to open the bottom drawer
        pull_distance = 0.1  # meters
        print(f"[Task] Step 5: Pulling to open bottom drawer (distance {pull_distance} m)")
        obs, reward, done = pull(env, task, pull_distance=pull_distance)
        if done:
            print("[Task] Task completed successfully! Reward:", reward)
        else:
            print("[Task] Drawer should now be open. Reward:", reward)

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

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

if __name__ == "__main__":
    run_skeleton_task()