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():
    print("===== Starting Skeleton Task =====")
    
    # === Environment Setup ===
    env, task = setup_environment()
    try:
        # Reset to initial state
        descriptions, obs = task.reset()

        # Initialize video recording
        init_video_writers(obs)

        # Wrap step and get_observation 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()
        # Define key positions and orientations
        side_pos = np.array(positions['bottom_side_pos'])
        target_quat = np.array(positions['ninety_deg'])
        anchor_pos = np.array(positions['bottom_anchor_pos'])
        rubbish_pos = np.array(positions['rubbish'])
        bin_pos = np.array(positions['bin'])

        # === Execute Oracle Plan ===
        print("[Step 1] Move to bottom drawer side position:", side_pos)
[Frozen Code Start]
        obs, reward, done = move(env, task, target_pos=side_pos)
        obs, reward, done = rotate(env, task, target_quat=target_quat)
        obs, reward, done = move(env, task, target_pos=anchor_pos)
        obs, reward, done = pull(env, task, pull_distance=0.2, pull_axis='x')
        obs, reward, done = move(env, task, target_pos=rubbish_pos)
        obs, reward, done = pick(env, task, target_pos=rubbish_pos)
        obs, reward, done = move(env, task, target_pos=bin_pos)
[Frozen Code End]
        if done:
            print("[Plan] Ended prematurely after moving to bin. Reward:", reward)
            return

        print("[Step 8] Place rubbish in bin at:", bin_pos)
        obs, reward, done = place(env, task, target_pos=bin_pos)
        if done:
            print("[Plan] Ended after placing rubbish. Reward:", reward)
            return

        print("===== Task completed successfully! Reward:", reward)

    finally:
        shutdown_environment(env)

if __name__ == "__main__":
    run_skeleton_task()