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 the combined-domain task.'''
    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 task.step and task.get_observation for recording
        task.step = recording_step(task.step)
        task.get_observation = recording_get_observation(task.get_observation)

        # Retrieve object positions from the environment
        positions = get_object_positions()

        # Step 1: Rotate gripper to current orientation
        print("[Step 1] Rotating gripper to current orientation")
        obs = task.get_observation()
        current_quat = obs.gripper_pose[3:7]

        # Step 2: Move to bottom drawer anchor position
        print("[Step 2] Moving to bottom drawer anchor position")
        bottom_anchor_pos = np.array(positions['bottom_anchor_pos'])

        # Step 3: Pulling the drawer open
        print("[Step 3] Pulling the drawer open")
        obs, reward, done = rotate(env, task, current_quat)
obs, reward, done = move(env, task, bottom_anchor_pos)
        obs, reward, done = pull(env, task, pull_distance=0.1, pull_axis='x')

        if done:
            print("Task ended after pull. Reward:", reward)
            return

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

        # Step 5: Place the rubbish into the bin
        print("[Step 5] Placing the rubbish into the bin")
        bin_pos = np.array(positions['bin'])
        obs, reward, done = place(env, task, bin_pos)
        if done:
            print("Task completed successfully! Reward:", reward)
        else:
            print("Task ended without completion. Done flag:", done)

    except Exception as e:
        print("Exception during task execution:", str(e))
    finally:
        # Always ensure the environment is properly shutdown
        shutdown_environment(env)

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

if __name__ == "__main__":
    run_skeleton_task()