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()
        # Map the key names from object_positions to variables
        side_pos = positions['bottom_side_pos']
        anchor_pos = positions['bottom_anchor_pos']
        rubbish_pos = positions['item3']
        bin_pos = positions['bin']

        # === Task Plan ===
        # Step 1: Move to the side position of the bottom drawer
        print("[Task] Step 1: Moving to bottom drawer side position at", side_pos)
        obs, reward, done = move(env, task, target_pos=np.array(side_pos))
        if done:
            print("[Task] Episode ended after step 1. Reward:", reward)
            return

        # Step 2: Rotate gripper to 90 degrees for drawer handle alignment
        quat_90 = np.array([0.0, 0.0, 0.7071, 0.7071])  # quaternion for 90° around Z
        print("[Task] Step 2: Rotating gripper to 90° orientation:", quat_90)
        obs, reward, done = rotate(env, task, target_quat=quat_90)
        if done:
            print("[Task] Episode ended after step 2. Reward:", reward)
            return

        # Step 3: Move to the anchor (handle) position of the bottom drawer
        print("[Task] Step 3: Moving to bottom drawer anchor position at", anchor_pos)
        obs, reward, done = move(env, task, target_pos=np.array(anchor_pos))
        if done:
            print("[Task] Episode ended after step 3. Reward:", reward)
            return

        # Step 4: Pull the drawer open
        print("[Task] Step 4: Pulling drawer open")
        obs, reward, done = pull(env, task, pull_distance=0.1, pull_axis='x')
        if done:
            print("[Task] Episode ended after step 4. Reward:", reward)
            return

        # Step 5: Move to the rubbish on the table (item3)
        print("[Task] Step 5: Moving to rubbish at", rubbish_pos)
        obs, reward, done = move(env, task, target_pos=np.array(rubbish_pos))
        if done:
            print("[Task] Episode ended after step 5. Reward:", reward)
            return

        # Step 6: Pick up the rubbish
        print("[Task] Step 6: Picking up rubbish at", rubbish_pos)
        obs, reward, done = pick(env, task, target_pos=np.array(rubbish_pos))
        if done:
            print("[Task] Episode ended after step 6. Reward:", reward)
            return

        # Step 7: Move to the bin
        print("[Task] Step 7: Moving to bin at", bin_pos)
        obs, reward, done = move(env, task, target_pos=np.array(bin_pos))
        if done:
            print("[Task] Episode ended after step 7. Reward:", reward)
            return

        # Step 8: Place the rubbish in the bin
        print("[Task] Step 8: Placing rubbish in bin at", bin_pos)
        obs, reward, done = place(env, task, target_pos=np.array(bin_pos))
        if done:
            print("[Task] Episode ended after step 8. Reward:", reward)
            return

        print("[Task] Completed all steps successfully. Final Reward:", reward)

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

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

if __name__ == "__main__":
    run_skeleton_task()