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 name mapping (from object list and positions) ---
        # Drawer positions
        # For this plan, we will open the "bottom" drawer (as an example).
        # The relevant positions are:
        #   - 'bottom_side_pos': side position for gripper to approach
        #   - 'bottom_anchor_pos': anchor position for gripping the drawer handle
        #   - 'bottom_joint_pos': position to pull the drawer open
        #   - 'waypoint1': a safe waypoint for transitions (if needed)
        # Objects
        #   - 'rubbish': the object to pick and place in the bin
        #   - 'bin': the target location for the rubbish

        # Defensive: check all required keys exist
        required_keys = [
            'bottom_side_pos', 'bottom_anchor_pos', 'bottom_joint_pos',
            'rubbish', 'bin'
        ]
        for key in required_keys:
            if key not in positions:
                raise KeyError(f"Required object position '{key}' not found in positions dictionary.")

        bottom_side_pos = positions['bottom_side_pos']
        bottom_anchor_pos = positions['bottom_anchor_pos']
        bottom_joint_pos = positions['bottom_joint_pos']
        rubbish_pos = positions['rubbish']
        bin_pos = positions['bin']

        # --- Step 1: Rotate gripper to 90 degrees (vertical) for drawer manipulation ---
        # Assume 90 deg corresponds to quaternion [0, 0, sqrt(0.5), sqrt(0.5)] (z axis, 90 deg)
        # If the environment provides a more precise quaternion for 90 deg, use that.
        # We'll use scipy to compute it.
        from scipy.spatial.transform import Rotation as R
        ninety_deg_quat = R.from_euler('z', 90, degrees=True).as_quat()  # xyzw
        # RLBench expects [x, y, z, w]
        print("[Task] Rotating gripper to 90 degrees for drawer manipulation.")
        obs, reward, done = rotate(env, task, target_quat=ninety_deg_quat)
        if done:
            print("[Task] Task ended after rotate!")
            return

        # --- Step 2: Move gripper to the side position of the bottom drawer ---
        print("[Task] Moving gripper to bottom drawer side position:", bottom_side_pos)
        obs, reward, done = move(env, task, target_pos=bottom_side_pos)
        if done:
            print("[Task] Task ended after move to side position!")
            return

        # --- Step 3: Move gripper to the anchor (handle) position of the bottom drawer ---
        print("[Task] Moving gripper to bottom drawer anchor (handle) position:", bottom_anchor_pos)
        obs, reward, done = move(env, task, target_pos=bottom_anchor_pos)
        if done:
            print("[Task] Task ended after move to anchor position!")
            return

        # --- Step 4: Pick (grasp) the drawer handle (simulate pick at anchor position) ---
        # For drawer, we just close the gripper at the anchor position.
        print("[Task] Grasping the bottom drawer handle at anchor position.")
        obs, reward, done = pick(env, task, target_pos=bottom_anchor_pos, approach_distance=0.10, approach_axis='z')
        if done:
            print("[Task] Task ended after picking drawer handle!")
            return

        # --- Step 5: Pull the drawer open along the x axis (assume positive x) ---
        # Pull distance: use the vector from anchor_pos to joint_pos
        pull_vector = bottom_joint_pos - bottom_anchor_pos
        pull_distance = np.linalg.norm(pull_vector)
        if pull_distance < 1e-3:
            print("[Task] Warning: Pull distance is very small, skipping pull.")
        else:
            # Determine axis: if x component is dominant, use 'x' or '-x'
            axis_idx = np.argmax(np.abs(pull_vector))
            axis_names = ['x', 'y', 'z']
            axis_sign = 1 if pull_vector[axis_idx] >= 0 else -1
            pull_axis = axis_names[axis_idx]
            if axis_sign < 0:
                pull_axis = '-' + pull_axis
            print(f"[Task] Pulling drawer along axis '{pull_axis}' by {pull_distance:.3f} meters.")
            obs, reward, done = pull(env, task, pull_distance=pull_distance, pull_axis=pull_axis)
            if done:
                print("[Task] Task ended after pulling drawer!")
                return

        # --- Step 6: Pick up the rubbish from the table ---
        print("[Task] Picking up rubbish at:", rubbish_pos)
        obs, reward, done = pick(env, task, target_pos=rubbish_pos, approach_distance=0.15, approach_axis='z')
        if done:
            print("[Task] Task ended after picking rubbish!")
            return

        # --- Step 7: Place the rubbish in the bin ---
        print("[Task] Placing rubbish in bin at:", bin_pos)
        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 occurred: {e}")
    finally:
        # Always ensure the environment is properly shutdown
        shutdown_environment(env)

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


if __name__ == "__main__":
    run_skeleton_task()