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

        # Initialize video writers if needed
        init_video_writers(obs)

        # Wrap step/get_observation for recording
        task.step = recording_step(task.step)
        task.get_observation = recording_get_observation(task.get_observation)

        # === Retrieve Object Positions ===
        positions = get_object_positions()
        # We only need the middle drawer positions for this plan
        middle_side_pos = positions['middle_side_pos']
        middle_anchor_pos = positions['middle_anchor_pos']

        # === Oracle Plan Execution ===

        # Step 1: Rotate gripper from zero_deg to ninety_deg
        print("[Plan] Step 1: rotate gripper to 90 degrees")
        ninety_quat = R.from_euler('z', 90, degrees=True).as_quat()
        obs, reward, done = rotate(env, task, target_quat=ninety_quat)
        if done:
            print("[Plan] Terminated after rotate. Reward:", reward)
            return

        # Step 2: Move to side position of middle drawer
        print(f"[Plan] Step 2: move to middle side position {middle_side_pos}")
        obs, reward, done = move(env, task, target_pos=np.array(middle_side_pos))
        if done:
            print("[Plan] Terminated after move. Reward:", reward)
            return

        # Step 3: Move to anchor position of middle drawer
        print(f"[Plan] Step 3: move to middle anchor position {middle_anchor_pos}")
        obs, reward, done = move(env, task, target_pos=np.array(middle_anchor_pos))
        if done:
            print("[Plan] Terminated after move. Reward:", reward)
            return

        # Step 4: Pick (grasp) the drawer at anchor position
        print(f"[Plan] Step 4: pick at anchor position {middle_anchor_pos}")
        obs, reward, done = pick(env, task, target_pos=np.array(middle_anchor_pos))
        if done:
            print("[Plan] Terminated after pick. Reward:", reward)
            return

        # Step 5: Pull the drawer open fully
        pull_distance = float(np.linalg.norm(np.array(middle_anchor_pos) - np.array(middle_side_pos)))
        print(f"[Plan] Step 5: pull drawer by distance {pull_distance:.3f}")
        obs, reward, done = pull(env, task, pull_distance=pull_distance, pull_axis='x')
        if done:
            print("[Plan] Drawer opened, task done. Reward:", reward)
        else:
            print("[Plan] Completed pull, but done flag is False. Reward:", reward)

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

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

if __name__ == "__main__":
    run_skeleton_task()