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: Unlock the cabinet by opening an accessible drawer, then throw away the trash while leaving any other objects alone.'''
    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 ===
        # 1. Rotate gripper to 90 degrees (for side grasp)
        # 2. Move to side position of an accessible (unlocked) drawer (bottom drawer is not locked)
        # 3. Move to anchor position of the same drawer
        # 4. Pick the drawer handle (anchor)
        # 5. Pull the drawer open
        # 6. Pick the rubbish from the table
        # 7. Place the rubbish in the bin

        # --- Step 1: Rotate gripper to 90 degrees (z axis) ---
        # Get the quaternion for 90 degrees rotation about z axis
        from scipy.spatial.transform import Rotation as R
        ninety_deg_quat = R.from_euler('z', 90, degrees=True).as_quat()  # xyzw
        # RLBench uses [x, y, z, w] order
        # Ensure the quaternion is in the correct order
        obs = task.get_observation()
        print("[Task] Rotating gripper to 90 degrees about z axis.")
        obs, reward, done = rotate(
            env,
            task,
            target_quat=ninety_deg_quat,
            max_steps=100,
            threshold=0.05,
            timeout=10.0
        )
        if done:
            print("[Task] Task ended during rotate!")
            return

        # --- Step 2: Move to side position of bottom drawer ---
        # Use 'bottom_side_pos' as the side position for the bottom drawer
        try:
            bottom_side_pos = positions['bottom_side_pos']
        except KeyError:
            print("[Error] bottom_side_pos not found in object positions.")
            return
        print("[Task] Moving to bottom drawer side position.")
        obs, reward, done = move(
            env,
            task,
            target_pos=bottom_side_pos,
            max_steps=100,
            threshold=0.01,
            timeout=10.0
        )
        if done:
            print("[Task] Task ended during move to side position!")
            return

        # --- Step 3: Move to anchor position of bottom drawer ---
        try:
            bottom_anchor_pos = positions['bottom_anchor_pos']
        except KeyError:
            print("[Error] bottom_anchor_pos not found in object positions.")
            return
        print("[Task] Moving to bottom drawer anchor position.")
        obs, reward, done = move(
            env,
            task,
            target_pos=bottom_anchor_pos,
            max_steps=100,
            threshold=0.01,
            timeout=10.0
        )
        if done:
            print("[Task] Task ended during move to anchor position!")
            return

        # --- Step 4: Pick the bottom drawer handle (anchor) ---
        print("[Task] Picking the bottom drawer handle (anchor).")
        obs, reward, done = pick(
            env,
            task,
            target_pos=bottom_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

        # --- Step 5: Pull the drawer open (pull along x axis, e.g., 0.15m) ---
        print("[Task] Pulling the bottom drawer open.")
        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

        # --- Step 6: Pick the rubbish from the table ---
        try:
            rubbish_pos = positions['rubbish']
        except KeyError:
            print("[Error] rubbish not found in object positions.")
            return
        print("[Task] Picking up the rubbish from the table.")
        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

        # --- Step 7: Place the rubbish in the bin ---
        try:
            bin_pos = positions['bin']
        except KeyError:
            print("[Error] bin not found in object positions.")
            return
        print("[Task] Placing the rubbish in the bin.")
        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).")

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

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


if __name__ == "__main__":
    run_skeleton_task()