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

        # === Define key orientations and positions for the plan ===
        zero_quat = np.array([0.0, 0.0, 0.0, 1.0])
        ninety_quat = np.array([0.0, 0.0, 0.70710678, 0.70710678])

        side_bottom_pos = np.array(positions.get('bottom_side_pos', [0,0,0]))
        anchor_bottom_pos = np.array(positions.get('bottom_anchor_pos', [0,0,0]))
        bin_pos = np.array(positions.get('bin', [0,0,0]))

        # === Execute Oracle Plan ===
        print("[Task] Rotating gripper to 90 degrees.")
[Frozen Code Start]
    obs, reward, done = rotate(env, task, ninety_quat)
obs, reward, done = move(env, task, side_bottom_pos)
[Frozen Code End]
        if done:
            print("[Task] Task ended during initial rotate/move.")
            return

        # Step 3: Move to anchor position of bottom drawer
        print("[Task] Moving to bottom anchor position:", anchor_bottom_pos)
        obs, reward, done = move(env, task, anchor_bottom_pos)
        if done:
            print("[Task] Task ended during move to anchor position.")
            return

        # Step 4: Pull to open the bottom drawer
        print("[Task] Pulling to open the bottom drawer.")
        obs, reward, done = pull(env, task, pull_distance=0.2, pull_axis='x')
        if done:
            print("[Task] Task ended during pull.")
            return

        # Steps 5 & 6: Pick any rubbish items on the table and place them into the bin
        rubbish_items = ['item1', 'item2', 'item3']
        for item in rubbish_items:
            if item not in positions:
                print(f"[Task] Warning: Position for {item} not found, skipping.")
                continue
            item_pos = np.array(positions[item])
            print(f"[Task] Picking up {item} at:", item_pos)
            obs, reward, done = pick(env, task, target_pos=item_pos)
            if done:
                print(f"[Task] Task ended during pick of {item}.")
                return
            print(f"[Task] Placing {item} into bin at:", bin_pos)
            obs, reward, done = place(env, task, target_pos=bin_pos)
            if done:
                print(f"[Task] Task ended during place of {item}.")
                return

        print("[Task] Completed all plan steps.")

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

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

if __name__ == "__main__":
    run_skeleton_task()