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 *  # Use provided skills: move, pick, place, rotate, pull

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()
        # Object keys: 'rubbish', 'bin', 'bottom_anchor_pos', 'bottom_side_pos', etc.

        # === PLAN EXECUTION ===
        # Goal: Pull open any drawer that is not locked, then drop the rubbish into the bin.

        # --- Step 1: Rotate gripper to 90 degrees (for side approach to drawer) ---
        # We'll use the 'bottom' drawer (bottom_anchor_pos, bottom_side_pos) as it's likely not locked.
        # Get current gripper pose
        obs = task.get_observation()
        start_quat = obs.gripper_pose[3:7]
        # Target orientation: 90 deg about z axis (assuming 'z' is up)
        # We'll use scipy's Rotation to get the quaternion for 90 deg about z
        from scipy.spatial.transform import Rotation as R
        target_rot = R.from_euler('z', 90, degrees=True)
        target_quat = target_rot.as_quat()  # xyzw
        # Ensure it's numpy array
        target_quat = np.array(target_quat)
        # Call rotate
        try:
            obs, reward, done = rotate(env, task, target_quat)
            if done:
                print("[Task] Task ended during rotate!")
                return
        except Exception as e:
            print(f"[Task] Exception during rotate: {e}")
            return

        # --- Step 2: Move to side position of bottom drawer ---
        try:
            side_pos = positions.get('bottom_side_pos')
            if side_pos is None:
                raise KeyError("bottom_side_pos not found in positions.")
            obs, reward, done = move(env, task, side_pos)
            if done:
                print("[Task] Task ended during move to side position!")
                return
        except Exception as e:
            print(f"[Task] Exception during move to side position: {e}")
            return

        # --- Step 3: Move to anchor position of bottom drawer ---
        try:
            anchor_pos = positions.get('bottom_anchor_pos')
            if anchor_pos is None:
                raise KeyError("bottom_anchor_pos not found in positions.")
            obs, reward, done = move(env, task, anchor_pos)
            if done:
                print("[Task] Task ended during move to anchor position!")
                return
        except Exception as e:
            print(f"[Task] Exception during move to anchor position: {e}")
            return

        # --- Step 4: Move slightly into the drawer handle (simulate grasp) ---
        # We'll move a small offset along the x axis (assuming drawer opens along x)
        try:
            # Move a little further in x to ensure gripper is in contact
            offset = np.array([0.03, 0.0, 0.0])  # 3cm forward
            pull_start_pos = np.array(anchor_pos) + offset
            obs, reward, done = move(env, task, pull_start_pos)
            if done:
                print("[Task] Task ended during move to pull start position!")
                return
        except Exception as e:
            print(f"[Task] Exception during move to pull start position: {e}")
            return

        # --- Step 5: Pull the drawer open ---
        try:
            # Pull along x axis, positive direction, e.g., 0.12m (12cm)
            pull_distance = 0.12
            obs, reward, done = pull(env, task, pull_distance, pull_axis='x')
            if done:
                print("[Task] Task ended during pull!")
                return
        except Exception as e:
            print(f"[Task] Exception during pull: {e}")
            return

        # --- Step 6: Pick up the rubbish from the table ---
        try:
            rubbish_pos = positions.get('rubbish')
            if rubbish_pos is None:
                raise KeyError("rubbish not found in positions.")
            obs, reward, done = pick(env, task, target_pos=rubbish_pos, approach_distance=0.15, approach_axis='z')
            if done:
                print("[Task] Task ended during pick rubbish!")
                return
        except Exception as e:
            print(f"[Task] Exception during pick rubbish: {e}")
            return

        # --- Step 7: Place the rubbish into the bin ---
        try:
            bin_pos = positions.get('bin')
            if bin_pos is None:
                raise KeyError("bin not found in positions.")
            obs, reward, done = place(env, task, target_pos=bin_pos, approach_distance=0.15, approach_axis='z')
            if done:
                print("[Task] Task completed successfully! Reward:", reward)
            else:
                print("[Task] Task not completed yet (done=False).")
        except Exception as e:
            print(f"[Task] Exception during place rubbish: {e}")
            return

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

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


if __name__ == "__main__":
    run_skeleton_task()