# run_skeleton_task.py

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: Find an unlocked drawer ---
        # According to the initial state, 'bottom' drawer is not locked, 'middle' and 'top' are locked.
        # We'll use the 'bottom' drawer.
        # The relevant positions for the bottom drawer:
        #   - side: 'bottom_side_pos'
        #   - anchor: 'bottom_anchor_pos'
        #   - joint: 'bottom_joint_pos'
        #   - gripper starts at 'nowhere_pos'
        #   - To pull, we need to move to side, rotate, move to anchor, pick-drawer, then pull.
        # However, per the provided plan steps and available skills, we must use only rotate, move, pull, pick, place.

        # --- Step 2: Plan Execution ---

        # 1. ROTATE gripper to 90 degrees (so it can approach the drawer from the side)
        #    - We'll use the quaternion for 90 degrees rotation about z axis.
        #    - The skill expects a quaternion (xyzw).
        #    - Let's assume the gripper's default orientation is aligned with zero_deg, and we want to rotate to ninety_deg.
        #    - We'll use scipy's Rotation to get the quaternion for 90 deg about z.
        from scipy.spatial.transform import Rotation as R
        ninety_deg_quat = R.from_euler('z', 90, degrees=True).as_quat()  # xyzw

        try:
            obs, reward, done = rotate(env, task, target_quat=ninety_deg_quat)
            if done:
                print("[Task] Task ended during rotate!")
                return
        except Exception as e:
            print(f"[Error] 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')
            if bottom_side_pos is None:
                raise KeyError("bottom_side_pos not found in positions.")
            obs, reward, done = move(env, task, target_pos=bottom_side_pos)
            if done:
                print("[Task] Task ended during move to side!")
                return
        except Exception as e:
            print(f"[Error] Exception during move to side: {e}")
            shutdown_environment(env)
            return

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

        # 4. MOVE to the joint position of the bottom drawer (simulate grasping the handle)
        try:
            bottom_joint_pos = positions.get('bottom_joint_pos')
            if bottom_joint_pos is None:
                raise KeyError("bottom_joint_pos not found in positions.")
            obs, reward, done = move(env, task, target_pos=bottom_joint_pos)
            if done:
                print("[Task] Task ended during move to joint!")
                return
        except Exception as e:
            print(f"[Error] Exception during move to joint: {e}")
            shutdown_environment(env)
            return

        # 5. PULL the drawer open (pull along the x axis, positive direction)
        #    - We'll pull by a fixed distance, e.g., 0.15 meters.
        try:
            pull_distance = 0.15
            obs, reward, done = pull(env, task, pull_distance=pull_distance, pull_axis='x')
            if done:
                print("[Task] Task ended during pull!")
                return
        except Exception as e:
            print(f"[Error] Exception during pull: {e}")
            shutdown_environment(env)
            return

        # 6. PICK 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,
                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(f"[Error] Exception during pick rubbish: {e}")
            shutdown_environment(env)
            return

        # 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,
                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(f"[Error] Exception during place rubbish: {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()
