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():
    '''Task: Slide open any available drawer to access its contents, then chuck away any rubbish remaining on the table.'''
    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 names from object list
        # [
        # 'bottom_anchor_pos', 'bottom_joint_pos', 'bottom_side_pos',
        # 'middle_anchor_pos', 'middle_joint_pos', 'middle_side_pos',
        # 'top_anchor_pos', 'top_joint_pos', 'top_side_pos',
        # 'item1', 'item2', 'item3', 'bin'
        # ]
        # We'll use 'bottom' drawer for opening, and 'item1', 'item2', 'item3' as table items.
        # 'bin' is the disposal location.

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

        # --- Step 2: Rotate gripper to 90 degrees (for drawer grasp) ---
        try:
            # Assume 90 deg is [x, y, z, w] quaternion for 90 deg about z axis
            # We'll use scipy to get quaternion for 90 deg about z
            from scipy.spatial.transform import Rotation as R
            quat_ninety = R.from_euler('z', 90, degrees=True).as_quat()  # xyzw
            print("[Task] Rotating gripper to 90 degrees (about z):", quat_ninety)
            obs, reward, done = rotate(env, task, target_quat=quat_ninety)
            if done:
                print("[Task] Task ended after rotate!")
                return
        except Exception as e:
            print(f"[Error] Failed to rotate gripper: {e}")
            return

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

        # --- Step 4: Pull the drawer open ---
        try:
            # Pull along x axis (assume drawer opens along +x), distance ~0.15m
            print("[Task] Pulling the drawer open along +x axis.")
            obs, reward, done = pull(env, task, pull_distance=0.15, pull_axis='x')
            if done:
                print("[Task] Task ended after pull!")
                return
        except Exception as e:
            print(f"[Error] Failed to pull the drawer: {e}")
            return

        # --- Step 5: Move gripper up to clear the drawer (optional safety) ---
        try:
            # Move up in z by 0.10m from current position
            obs_now = task.get_observation()
            gripper_pos = np.array(obs_now.gripper_pose[:3])
            up_pos = gripper_pos + np.array([0, 0, 0.10])
            print("[Task] Moving gripper up to clear drawer:", up_pos)
            obs, reward, done = move(env, task, target_pos=up_pos)
            if done:
                print("[Task] Task ended after moving up!")
                return
        except Exception as e:
            print(f"[Error] Failed to move up after pull: {e}")
            return

        # --- Step 6: For each item on the table, pick and place into bin ---
        for item_name in ['item1', 'item2', 'item3']:
            try:
                item_pos = positions.get(item_name, None)
                if item_pos is None:
                    print(f"[Warning] {item_name} not found in object positions, skipping.")
                    continue
                print(f"[Task] Picking up {item_name} at {item_pos}")
                obs, reward, done = pick(env, task, target_pos=item_pos, approach_distance=0.15, approach_axis='z')
                if done:
                    print(f"[Task] Task ended after picking {item_name}!")
                    return
            except Exception as e:
                print(f"[Error] Failed to pick {item_name}: {e}")
                continue

            try:
                bin_pos = positions.get('bin', None)
                if bin_pos is None:
                    print("[Error] bin not found in object positions, cannot place item.")
                    continue
                print(f"[Task] Placing {item_name} into bin at {bin_pos}")
                obs, reward, done = place(env, task, target_pos=bin_pos, approach_distance=0.15, approach_axis='z')
                if done:
                    print(f"[Task] Task ended after placing {item_name}!")
                    return
            except Exception as e:
                print(f"[Error] Failed to place {item_name} into bin: {e}")
                continue

        print("[Task] All items processed. Task completed successfully!")

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

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


if __name__ == "__main__":
    run_skeleton_task()