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():
    '''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()
        # Object keys (from object list): 
        # 'bottom_anchor_pos', 'bottom_joint_pos', 'bottom_side_pos',
        # 'middle_anchor_pos', 'middle_joint_pos', 'middle_side_pos',
        # 'top_anchor_pos', 'top_joint_pos', 'top_side_pos',
        # 'waypoint1', 'item1', 'item2', 'item3', 'bin'

        # --- PLAN: Open a drawer fully, pick up the rubbish, and place it in the bin ---

        # 1. Select a drawer: We'll use the 'bottom' drawer for this plan.
        #    - bottom_side_pos: position to approach the side of the bottom drawer
        #    - bottom_anchor_pos: position to grasp the handle/anchor of the bottom drawer
        #    - bottom_joint_pos: (not used directly here)
        #    - bin: trash can position
        #    - item3: the rubbish (as per observation, 'rubbish' is not in the object list, but 'item3' is likely the rubbish)

        # Defensive: Check all required keys exist
        required_keys = [
            'bottom_side_pos', 'bottom_anchor_pos', 'bin', 'item3'
        ]
        for k in required_keys:
            if k not in positions:
                raise RuntimeError(f"Required object position '{k}' not found in positions dictionary.")

        # Step 1: Move to the side position of the bottom drawer
        print("[Plan] Step 1: Move to bottom_side_pos (side of bottom drawer)")
        obs, reward, done = move(
            env, task, target_pos=positions['bottom_side_pos']
        )
        if done:
            print("[Task] Task ended after move to bottom_side_pos!")
            return

        # Step 2: Rotate gripper to 90 degrees (for grasping drawer handle)
        print("[Plan] Step 2: Rotate gripper to 90 degrees")
        # We'll use a quaternion for 90 deg rotation about z axis
        # RLBench uses [x, y, z, w] (xyzw) format
        from scipy.spatial.transform import Rotation as R
        quat_ninety_deg = R.from_euler('z', 90, degrees=True).as_quat()  # [x, y, z, w]
        obs, reward, done = rotate(
            env, task, target_quat=quat_ninety_deg
        )
        if done:
            print("[Task] Task ended after rotate to 90 deg!")
            return

        # Step 3: Move to anchor position (handle) of the bottom drawer
        print("[Plan] Step 3: Move to bottom_anchor_pos (handle of bottom drawer)")
        obs, reward, done = move(
            env, task, target_pos=positions['bottom_anchor_pos']
        )
        if done:
            print("[Task] Task ended after move to bottom_anchor_pos!")
            return

        # Step 4: Pull the drawer open (pull along x axis, positive direction)
        print("[Plan] Step 4: Pull the drawer open")
        # We'll pull by a fixed distance (e.g., 0.18m) along x axis
        pull_distance = 0.18
        obs, reward, done = pull(
            env, task, pull_distance=pull_distance, pull_axis='x'
        )
        if done:
            print("[Task] Task ended after pull!")
            return

        # Step 5: Move to the rubbish (item3) on the table
        print("[Plan] Step 5: Move to item3 (rubbish)")
        obs, reward, done = move(
            env, task, target_pos=positions['item3']
        )
        if done:
            print("[Task] Task ended after move to item3!")
            return

        # Step 6: Pick up the rubbish (item3)
        print("[Plan] Step 6: Pick up item3 (rubbish)")
        obs, reward, done = pick(
            env, task, target_pos=positions['item3']
        )
        if done:
            print("[Task] Task ended after pick!")
            return

        # Step 7: Move to the bin
        print("[Plan] Step 7: Move to bin")
        obs, reward, done = move(
            env, task, target_pos=positions['bin']
        )
        if done:
            print("[Task] Task ended after move to bin!")
            return

        # Step 8: Place the rubbish in the bin
        print("[Plan] Step 8: Place item3 (rubbish) in bin")
        obs, reward, done = place(
            env, task, target_pos=positions['bin']
        )
        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 task execution: {e}")
    finally:
        # Always ensure the environment is properly shutdown
        shutdown_environment(env)

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


if __name__ == "__main__":
    run_skeleton_task()