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

        # Initialize video writers if needed
        init_video_writers(obs)

        # Wrap the task methods for recording
        task.step = recording_step(task.step)
        task.get_observation = recording_get_observation(task.get_observation)

        # Retrieve object positions
        positions = get_object_positions()
        # Extract relevant positions
        bottom_side_pos = positions['bottom_side_pos']
        bottom_anchor_pos = positions['bottom_anchor_pos']
        rubbish_pos = positions['rubbish']
        bin_pos = positions['bin']

        # Step 1: Rotate gripper to align with drawer handle (90° about some axis)
        print("[Task] Step 1: Rotating gripper to 90° orientation")
        target_quat = np.array([0.0, 0.0, 0.7071, 0.7071])
        obs, reward, done = rotate(env, task, target_quat)
        if done:
            print("[Task] Finished after rotate; exiting early.")
            return

        # Step 2: Move gripper to the side position of the bottom drawer
        print(f"[Task] Step 2: Moving to bottom side position {bottom_side_pos}")
        obs, reward, done = move(env, task, bottom_side_pos)
        if done:
            print("[Task] Finished after move-to-side; exiting early.")
            return

        # Step 3: Move gripper to the anchor position of the bottom drawer
        print(f"[Task] Step 3: Moving to bottom anchor position {bottom_anchor_pos}")
        obs, reward, done = move(env, task, bottom_anchor_pos)
        if done:
            print("[Task] Finished after move-to-anchor; exiting early.")
            return

        # Step 4: Pull the drawer open
        print("[Task] Step 4: Pulling drawer open")
        pull_distance = 0.1
        obs, reward, done = pull(env, task, pull_distance)
        if done:
            print("[Task] Finished after pull; exiting early.")
            return

        # Step 5: Pick up the rubbish from the table
        print(f"[Task] Step 5: Picking up rubbish at {rubbish_pos}")
        obs, reward, done = pick(env, task, target_pos=rubbish_pos)
        if done:
            print("[Task] Finished after pick; exiting early.")
            return

        # Step 6: Place the rubbish into the bin
        print(f"[Task] Step 6: Placing rubbish into bin at {bin_pos}")
        obs, reward, done = place(env, task, target_pos=bin_pos)
        if done:
            print("[Task] Task completed successfully! Reward:", reward)
        else:
            print("[Task] Task ended with done=False. Reward:", reward)

    except Exception as e:
        print(f"[Task] Exception encountered: {e}")
        raise
    finally:
        # Always ensure the environment is properly shutdown
        shutdown_environment(env)

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

if __name__ == "__main__":
    run_skeleton_task()