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 only the provided skills

from video import init_video_writers, recording_step, recording_get_observation

from object_positions import get_object_positions


def run_skeleton_task():
    '''Task: Pull open any unlocked drawer, then drop the rubbish into the bin.'''
    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()

        # === Step 1: Pull open any unlocked drawer ===
        # From the initial state, 'bottom' drawer is not locked, 'middle' and 'top' are locked.
        # We'll use the 'bottom' drawer.
        # We need to:
        #   - Move gripper to the side position of the bottom drawer
        #   - Rotate gripper to 90 degrees (if not already)
        #   - Move to anchor position
        #   - Pick the drawer handle (simulate grasp)
        #   - Pull the drawer open

        # Get relevant positions for the bottom drawer
        try:
            gripper_side_pos = positions.get('bottom_side_pos', None)
            gripper_anchor_pos = positions.get('bottom_anchor_pos', None)
            if gripper_side_pos is None or gripper_anchor_pos is None:
                raise KeyError("Missing bottom drawer side/anchor positions in object_positions.")
        except Exception as e:
            print("[Error] Could not retrieve bottom drawer positions:", e)
            shutdown_environment(env)
            return

        # 1. Move gripper to the side position of the bottom drawer
        print("[Task] Moving gripper to bottom drawer side position:", gripper_side_pos)
        try:
            obs, reward, done = move(
                env,
                task,
                target_pos=np.array(gripper_side_pos),
                max_steps=100,
                threshold=0.01,
                timeout=10.0
            )
            if done:
                print("[Task] Task ended during move to side position!")
                return
        except Exception as e:
            print("[Error] Exception during move to side position:", e)
            shutdown_environment(env)
            return

        # 2. Rotate gripper to 90 degrees (if not already)
        # We'll assume 90 degrees is [0, 0, sin(π/4), cos(π/4)] in quaternion (z-axis rotation)
        # But let's try to get the current orientation and only rotate if needed
        try:
            from scipy.spatial.transform import Rotation as R
            obs = task.get_observation()
            current_quat = obs.gripper_pose[3:7]
            # 90 deg about z: Euler (0,0,90) deg
            target_rot = R.from_euler('z', 90, degrees=True)
            target_quat = target_rot.as_quat()  # xyzw
            obs, reward, done = rotate(
                env,
                task,
                target_quat=target_quat,
                max_steps=100,
                threshold=0.05,
                timeout=10.0
            )
            if done:
                print("[Task] Task ended during rotate!")
                return
        except Exception as e:
            print("[Error] Exception during rotate to 90 degrees:", e)
            shutdown_environment(env)
            return

        # 3. Move to anchor position (handle position)
        print("[Task] Moving gripper to bottom drawer anchor position:", gripper_anchor_pos)
        try:
            obs, reward, done = move(
                env,
                task,
                target_pos=np.array(gripper_anchor_pos),
                max_steps=100,
                threshold=0.01,
                timeout=10.0
            )
            if done:
                print("[Task] Task ended during move to anchor position!")
                return
        except Exception as e:
            print("[Error] Exception during move to anchor position:", e)
            shutdown_environment(env)
            return

        # 4. Pick the drawer handle (simulate grasp)
        # We'll use the pick skill to close the gripper at the anchor position
        print("[Task] Grasping the bottom drawer handle at anchor position.")
        try:
            obs, reward, done = pick(
                env,
                task,
                target_pos=np.array(gripper_anchor_pos),
                approach_distance=0.10,
                max_steps=100,
                threshold=0.01,
                approach_axis='z',
                timeout=10.0
            )
            if done:
                print("[Task] Task ended during pick (drawer handle)!")
                return
        except Exception as e:
            print("[Error] Exception during pick (drawer handle):", e)
            shutdown_environment(env)
            return

        # 5. Pull the drawer open
        # We'll pull along the x-axis by a reasonable distance (e.g., 0.15m)
        print("[Task] Pulling the bottom drawer open.")
        try:
            obs, reward, done = pull(
                env,
                task,
                pull_distance=0.15,
                pull_axis='x',
                max_steps=100,
                threshold=0.01,
                timeout=10.0
            )
            if done:
                print("[Task] Task ended during pull!")
                return
        except Exception as e:
            print("[Error] Exception during pull:", e)
            shutdown_environment(env)
            return

        # === Step 2: Pick up the rubbish ===
        # The object to pick is 'item3' (assuming 'item3' is the rubbish).
        # The initial state says (at item3 table)
        try:
            rubbish_pos = positions.get('item3', None)
            if rubbish_pos is None:
                raise KeyError("Missing 'item3' (rubbish) position in object_positions.")
        except Exception as e:
            print("[Error] Could not retrieve rubbish position:", e)
            shutdown_environment(env)
            return

        print("[Task] Picking up the rubbish (item3) at:", rubbish_pos)
        try:
            obs, reward, done = pick(
                env,
                task,
                target_pos=np.array(rubbish_pos),
                approach_distance=0.15,
                max_steps=100,
                threshold=0.01,
                approach_axis='z',
                timeout=10.0
            )
            if done:
                print("[Task] Task ended during pick (rubbish)!")
                return
        except Exception as e:
            print("[Error] Exception during pick (rubbish):", e)
            shutdown_environment(env)
            return

        # === Step 3: Place the rubbish into the bin ===
        try:
            bin_pos = positions.get('bin', None)
            if bin_pos is None:
                raise KeyError("Missing 'bin' position in object_positions.")
        except Exception as e:
            print("[Error] Could not retrieve bin position:", e)
            shutdown_environment(env)
            return

        print("[Task] Placing the rubbish into the bin at:", bin_pos)
        try:
            obs, reward, done = place(
                env,
                task,
                target_pos=np.array(bin_pos),
                approach_distance=0.15,
                max_steps=100,
                threshold=0.01,
                approach_axis='z',
                timeout=10.0
            )
            if done:
                print("[Task] Task completed successfully! Reward:", reward)
            else:
                print("[Task] Task not completed yet (done=False).")
        except Exception as e:
            print("[Error] Exception during place (rubbish into bin):", e)
            shutdown_environment(env)
            return

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

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


if __name__ == "__main__":
    run_skeleton_task()