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 for capturing simulation
        init_video_writers(obs)

        # Wrap the task steps for recording
        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()

        # === Oracle Plan Execution ===
        try:
            # Step 1: Rotate gripper to 90 degrees around Z to align with drawer handle
            print("[Task] Step 1: Rotating gripper to 90° around Z-axis")
            target_quat = np.array([0.0, 0.0, np.sqrt(2)/2, np.sqrt(2)/2])  # [x, y, z, w]
            obs, reward, done = rotate(env, task, target_quat)
            if done:
                print("[Task] Terminated after rotate")
                return

            # Step 2: Move gripper to the side position of the bottom drawer
            side_pos = np.array(positions['bottom_side_pos'])
            print(f"[Task] Step 2: Moving to bottom drawer side position {side_pos}")
            obs, reward, done = move(env, task, side_pos)
            if done:
                print("[Task] Terminated after move")
                return

    [Frozen Code Start]
    obs, reward, done = rotate(env, task, target_quat)
obs, reward, done = move(env, task, side_pos)
    [Frozen Code End]

            # Step 3: Pull to open the drawer
            print("[Task] Step 3: Pulling drawer open")
            obs, reward, done = pull(env, task, pull_distance=0.1, pull_axis='x')
            if done:
                print("[Task] Terminated after pull")
                return

            # Step 4: Pick up the rubbish from the table
            rubbish_pos = np.array(positions['rubbish'])
            print(f"[Task] Step 4: Picking up rubbish at {rubbish_pos}")
            obs, reward, done = pick(env, task, rubbish_pos)
            if done:
                print("[Task] Terminated after pick")
                return

            # Step 5: Place the rubbish into the bin
            bin_pos = np.array(positions['bin'])
            print(f"[Task] Step 5: Placing rubbish into bin at {bin_pos}")
            obs, reward, done = place(env, task, bin_pos)
            if done:
                print(f"[Task] Completed successfully with final reward {reward}")
            else:
                print("[Task] Finished plan but done=False")

        except Exception as e:
            print(f"[Task] Error during plan execution: {e}")

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

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

if __name__ == "__main__":
    run_skeleton_task()