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

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 the open-drawer 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()
        # Expected keys: 'bottom_side_pos', 'bottom_anchor_pos', etc.
        bottom_side = positions.get('bottom_side_pos')
        if bottom_side is None:
            raise ValueError("bottom_side_pos not found in positions")
        bottom_anchor = positions.get('bottom_anchor_pos')
        if bottom_anchor is None:
            raise ValueError("bottom_anchor_pos not found in positions")

        # === Define angle quaternions ===
        angle_quats = {
            'zero_deg': R.from_euler('z', 0, degrees=True).as_quat(),
            'ninety_deg': R.from_euler('z', 90, degrees=True).as_quat()
        }

        # === Oracle Plan Execution ===

        # Step 1: Rotate gripper from zero_deg to ninety_deg
        print("[Task] Step 1: Rotating gripper to ninety_deg")
        obs, reward, done = rotate(env, task, angle_quats['ninety_deg'])
        if done:
            print("[Task] Finished early after rotate. Reward:", reward)
            return

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

        # Step 3: Move gripper to the anchor position of the bottom drawer
        print(f"[Task] Step 3: Moving to anchor position of bottom drawer: {bottom_anchor}")
        obs, reward, done = move(env, task, bottom_anchor)
        if done:
            print("[Task] Finished early after move to anchor. Reward:", reward)
            return

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

        # Step 5: Pull the drawer to open it (unlock the cabinet)
        pull_distance = 0.2  # meters, adjust if needed
        pull_axis = 'x'
        print(f"[Task] Step 5: Pulling drawer by {pull_distance}m along {pull_axis}-axis")
        obs, reward, done = pull(env, task, pull_distance, pull_axis)
        if done:
            print("[Task] Finished after pull. Reward:", reward)
        else:
            print("[Task] Plan 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()