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 *

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 ===
        # Step 1: rotate(gripper, zero_deg, ninety_deg)
        # Step 2: move(gripper, side-pos-bottom)
        # Step 3: move(gripper, anchor-pos-bottom)
        # Step 4: pick(gripper, anchor-pos-bottom)
        # Step 5: pull(gripper, bottom)
        # Step 6: pick(rubbish, table)
        # Step 7: place(rubbish, bin)

        # --- Step 1: Rotate gripper from zero_deg to ninety_deg ---
        try:
            # Get target quaternion for ninety_deg
            # Assume positions['gripper'] gives the gripper object, and we can get its pose
            # For rotation, we need the quaternion for 90 degrees about the appropriate axis
            # Let's assume rotation about z axis
            from scipy.spatial.transform import Rotation as R
            quat_ninety_deg = R.from_euler('z', 90, degrees=True).as_quat()  # xyzw
            # RLBench/pyrep uses [x, y, z, w] order
            obs, reward, done = rotate(env, task, quat_ninety_deg)
            if done:
                print("[Task] Task ended after rotate!")
                return
        except Exception as e:
            print(f"[ERROR] Step 1 (rotate) failed: {e}")
            shutdown_environment(env)
            return

        # --- Step 2: Move gripper to side-pos-bottom ---
        try:
            target_pos = positions.get('bottom_side_pos', None)
            if target_pos is None:
                raise KeyError("bottom_side_pos not found in object positions.")
            obs, reward, done = move(env, task, np.array(target_pos))
            if done:
                print("[Task] Task ended after move to side-pos-bottom!")
                return
        except Exception as e:
            print(f"[ERROR] Step 2 (move to side-pos-bottom) failed: {e}")
            shutdown_environment(env)
            return

        # --- Step 3: Move gripper to anchor-pos-bottom ---
        try:
            target_pos = positions.get('bottom_anchor_pos', None)
            if target_pos is None:
                raise KeyError("bottom_anchor_pos not found in object positions.")
            obs, reward, done = move(env, task, np.array(target_pos))
            if done:
                print("[Task] Task ended after move to anchor-pos-bottom!")
                return
        except Exception as e:
            print(f"[ERROR] Step 3 (move to anchor-pos-bottom) failed: {e}")
            shutdown_environment(env)
            return

        # --- Step 4: Pick the drawer handle at anchor-pos-bottom ---
        try:
            # For picking the drawer, approach anchor_pos_bottom
            target_pos = positions.get('bottom_anchor_pos', None)
            if target_pos is None:
                raise KeyError("bottom_anchor_pos not found in object positions.")
            obs, reward, done = pick(env, task, np.array(target_pos), approach_distance=0.10, approach_axis='z')
            if done:
                print("[Task] Task ended after pick at anchor-pos-bottom!")
                return
        except Exception as e:
            print(f"[ERROR] Step 4 (pick at anchor-pos-bottom) failed: {e}")
            shutdown_environment(env)
            return

        # --- Step 5: Pull the bottom drawer open ---
        try:
            # For pull, we need to know the pull direction and distance.
            # Assume pulling along -x axis by 0.15m (typical drawer pull)
            pull_distance = 0.15
            pull_axis = '-x'
            obs, reward, done = pull(env, task, pull_distance, pull_axis=pull_axis)
            if done:
                print("[Task] Task ended after pull!")
                return
        except Exception as e:
            print(f"[ERROR] Step 5 (pull) failed: {e}")
            shutdown_environment(env)
            return

        # --- Step 6: Pick up the rubbish from the table ---
        try:
            target_pos = positions.get('rubbish', None)
            if target_pos is None:
                raise KeyError("rubbish not found in object positions.")
            obs, reward, done = pick(env, task, np.array(target_pos), approach_distance=0.15, approach_axis='z')
            if done:
                print("[Task] Task ended after pick rubbish!")
                return
        except Exception as e:
            print(f"[ERROR] Step 6 (pick rubbish) failed: {e}")
            shutdown_environment(env)
            return

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