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():
    '''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()

        # === Plan Execution ===
        # Goal: Select a drawer and open it fully, then pick up the rubbish and leave it in the trash can.

        # --- Step 1: Rotate gripper to 90 degrees (vertical) for drawer manipulation ---
        # We'll use the 'rotate' skill to set the gripper orientation to 90 degrees about z.
        # Assume 'ninety_deg' means vertical orientation for drawer handle.
        # We'll use the current gripper position and set the orientation accordingly.
        try:
            obs = task.get_observation()
            # Get current gripper position and orientation
            gripper_pos = obs.gripper_pose[:3]
            # Target orientation: 90 degrees about z axis
            from scipy.spatial.transform import Rotation as R
            # Assuming the default orientation is [0,0,0,1] (no rotation), 90 deg about z is:
            target_rot = R.from_euler('z', 90, degrees=True)
            target_quat = target_rot.as_quat()  # xyzw
            obs, reward, done = rotate(env, task, target_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

        # --- Step 2: Move to the side position of the bottom drawer ---
        # We'll use the 'move' skill to move to the 'bottom_side_pos' (side of bottom drawer)
        try:
            if 'bottom_side_pos' in positions:
                side_pos = positions['bottom_side_pos']
            elif 'side-pos-bottom' in positions:
                side_pos = positions['side-pos-bottom']
            else:
                raise KeyError("bottom_side_pos not found in positions.")
            obs, reward, done = move(env, task, side_pos)
            if done:
                print("[Task] Task ended during move to side position!")
                return
        except Exception as e:
            print(f"[ERROR] Exception during move to side position: {e}")
            shutdown_environment(env)
            return

        # --- Step 3: Move to the anchor position of the bottom drawer (handle) ---
        # Move to 'bottom_anchor_pos' (the drawer handle)
        try:
            if 'bottom_anchor_pos' in positions:
                anchor_pos = positions['bottom_anchor_pos']
            elif 'anchor-pos-bottom' in positions:
                anchor_pos = positions['anchor-pos-bottom']
            else:
                raise KeyError("bottom_anchor_pos not found in positions.")
            obs, reward, done = move(env, task, anchor_pos)
            if done:
                print("[Task] Task ended during move to anchor position!")
                return
        except Exception as e:
            print(f"[ERROR] Exception during move to anchor position: {e}")
            shutdown_environment(env)
            return

        # --- Step 4: Pick the drawer handle (simulate grasping the handle) ---
        # Use the 'pick' skill to close the gripper on the handle position
        try:
            obs, reward, done = pick(env, task, 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"[ERROR] Exception during pick drawer handle: {e}")
            shutdown_environment(env)
            return

        # --- Step 5: Pull the drawer open ---
        # Use the 'pull' skill to pull along the x-axis (assume drawer opens along +x)
        try:
            # Estimate a reasonable pull distance (e.g., 0.18 meters)
            pull_distance = 0.18
            obs, reward, done = pull(env, task, 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

        # --- Step 6: Pick up the rubbish from the table ---
        try:
            if 'rubbish' in positions:
                rubbish_pos = positions['rubbish']
            else:
                raise KeyError("rubbish not found in positions.")
            obs, reward, done = pick(env, task, 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"[ERROR] Exception during pick rubbish: {e}")
            shutdown_environment(env)
            return

        # --- Step 7: Place the rubbish in the bin ---
        try:
            if 'bin' in positions:
                bin_pos = positions['bin']
            else:
                raise KeyError("bin not found in positions.")
            obs, reward, done = place(env, task, 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"[ERROR] 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()