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()
        # We choose the bottom drawer because it is the only unlocked one
        bottom_side_pos = np.array(positions['bottom_side_pos'])
        bottom_anchor_pos = np.array(positions['bottom_anchor_pos'])

        # === Oracle Plan Execution ===
        # Step 1: Rotate gripper to ninety_deg orientation (around Z axis)
        print("[Plan] Step 1: rotate gripper to 90 degrees around Z")
        # Quaternion for 90° about Z: [x, y, z, w] = [0,0, sin(45°), cos(45°)]
        target_quat = np.array([0.0, 0.0, np.sin(np.pi/4), np.cos(np.pi/4)])
        obs, reward, done = rotate(env, task, target_quat)
        if done:
            print("[Plan] Task ended during rotate.")
            return

        # Step 2: Move to side position of bottom drawer
        print(f"[Plan] Step 2: move to side position {bottom_side_pos}")
        obs, reward, done = move(env, task, bottom_side_pos)
        if done:
            print("[Plan] Task ended during move-to-side.")
            return

        # Step 3: Move to anchor position of bottom drawer
        print(f"[Plan] Step 3: move to anchor position {bottom_anchor_pos}")
        obs, reward, done = move(env, task, bottom_anchor_pos)
        if done:
            print("[Plan] Task ended during move-to-anchor.")
            return

        # Step 4: Pick the drawer handle at anchor position
        print(f"[Plan] Step 4: pick drawer at {bottom_anchor_pos}")
        obs, reward, done = pick(env, task, bottom_anchor_pos)
        if done:
            print("[Plan] Task ended during pick.")
            return

        # Step 5: Pull to open the drawer fully
        print("[Plan] Step 5: pull drawer to open")
        # Pull distance: choose 0.2m along X axis by default
        obs, reward, done = pull(env, task, pull_distance=0.2, pull_axis='x')
        if done:
            print("[Plan] Task ended during pull.")
            return

        # Final check
        print("[Plan] Completed all steps. Reward:", reward)

    except Exception as e:
        print(f"[Error] Exception during plan execution: {e}")
    finally:
        # Always ensure the environment is properly shutdown
        shutdown_environment(env)

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

if __name__ == "__main__":
    run_skeleton_task()