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

        # Choose a drawer to open (any unlocked drawer; choose 'bottom' for simplicity)
        drawer = 'bottom'
        side_pos = positions[f'{drawer}_side_pos']
        anchor_pos = positions[f'{drawer}_anchor_pos']

        # Compute a quaternion representing 90° rotation around the Y axis
        ninety_deg_quat = R.from_euler('y', 90, degrees=True).as_quat()

        # === Oracle Plan Execution ===

        # Step 1: Rotate gripper to 90 degrees
        print("[Task] Step 1: rotate to align gripper for side approach")
        obs, reward, done = rotate(env, task, ninety_deg_quat)
        if done:
            print("[Task] Ended after rotate. Reward:", reward)
            return

        # Step 2: Move gripper to the side position of the drawer
        print(f"[Task] Step 2: move to side of drawer at {side_pos}")
        obs, reward, done = move(env, task, side_pos)
        if done:
            print("[Task] Ended after move to side. Reward:", reward)
            return

        # Step 3: Move gripper from side position to anchor (handle) position
        print(f"[Task] Step 3: move to anchor of drawer at {anchor_pos}")
        obs, reward, done = move(env, task, anchor_pos)
        if done:
            print("[Task] Ended after move to anchor. Reward:", reward)
            return

        # Step 4: Pick (grasp) the drawer handle
        print(f"[Task] Step 4: pick drawer handle at {anchor_pos}")
        obs, reward, done = pick(env, task, anchor_pos)
        if done:
            print("[Task] Ended after pick. Reward:", reward)
            return

        # Step 5: Pull to open the drawer
        print("[Task] Step 5: pull to open drawer")
        pull_distance = 0.2
        obs, reward, done = pull(env, task, pull_distance, pull_axis='x')
        if done:
            print("[Task] Task completed successfully! Reward:", reward)
        else:
            print("[Task] Task not completed. Final reward:", reward)

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

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


if __name__ == "__main__":
    run_skeleton_task()