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: Open one of the drawers in the cabinet, then put the rubbish in 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()
        # Object keys expected in positions: 'rubbish', 'bin', 'bottom_anchor_pos', 'bottom_side_pos', etc.

        # --- PLAN: Open a drawer (bottom), then put rubbish in bin ---

        # 1. Rotate gripper to 90 degrees (vertical for side approach)
        #    - Get current gripper pose and compute target quaternion for 90 deg rotation about z
        obs = task.get_observation()
        start_quat = obs.gripper_pose[3:7]
        # 90 deg about z axis (assuming 'zero_deg' is 0, 'ninety_deg' is 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 correct format (xyzw)
        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}")
            shutdown_environment(env)
            return

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

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

        # 4. Pick the drawer handle (simulate grasping the drawer at anchor)
        try:
            obs, reward, done = pick(env, task, np.array(bottom_anchor_pos), approach_distance=0.10, approach_axis='z')
            if done:
                print("[Task] Task ended during pick (drawer handle)!")
                return
        except Exception as e:
            print(f"[Task] Exception during pick (drawer handle): {e}")
            shutdown_environment(env)
            return

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

        # 6. Pick the rubbish from the table
        try:
            rubbish_pos = positions.get('rubbish', None)
            if rubbish_pos is None:
                raise KeyError("rubbish not found in positions.")
            obs, reward, done = pick(env, task, np.array(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}")
            shutdown_environment(env)
            return

        # 7. Place the rubbish in the bin
        try:
            bin_pos = positions.get('bin', None)
            if bin_pos is None:
                raise KeyError("bin not found in positions.")
            obs, reward, done = place(env, task, np.array(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 in 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()