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 to initial state
        descriptions, obs = task.reset()

        # Initialize video writers if desired
        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 from the environment
        positions = get_object_positions()
        # Map to variables
        side_pos_bottom = positions['bottom_side_pos']
        anchor_pos_bottom = positions['bottom_anchor_pos']
        tomato1_pos = positions['tomato1']
        tomato2_pos = positions['tomato2']
        plate_pos = positions['plate']

        # === Execute Oracle Plan ===
        print("===== Executing Oracle Plan =====")
        # Step 1: move gripper to drawer side position
        print("[Step 1] move to bottom side position:", side_pos_bottom)
        obs, reward, done = move(env, task, target_pos=np.array(side_pos_bottom))
        if done:
            print("[Step 1] Task ended early. Reward:", reward)
            return

        # Step 2: rotate gripper 90 degrees about Z
        target_quat = R.from_euler('z', 90, degrees=True).as_quat()
        print("[Step 2] rotate gripper to 90° (quat):", target_quat)
        obs, reward, done = rotate(env, task, target_quat=target_quat)
        if done:
            print("[Step 2] Task ended early. Reward:", reward)
            return

        # Step 3: move gripper to drawer anchor position
        print("[Step 3] move to bottom anchor position:", anchor_pos_bottom)
        obs, reward, done = move(env, task, target_pos=np.array(anchor_pos_bottom))
        if done:
            print("[Step 3] Task ended early. Reward:", reward)
            return

        # Step 4: pull the drawer open
        pull_distance = 0.1
        print(f"[Step 4] pull drawer by distance {pull_distance}")
        obs, reward, done = pull(env, task, pull_distance=pull_distance, pull_axis='x')
        if done:
            print("[Step 4] Task ended early. Reward:", reward)
            return

        # Step 5: pick tomato1 from the table
        print("[Step 5] pick tomato1 at:", tomato1_pos)
        obs, reward, done = pick(env, task, target_pos=np.array(tomato1_pos))
        if done:
            print("[Step 5] Task ended early. Reward:", reward)
            return

        # Step 6: place tomato1 on plate
        print("[Step 6] place tomato1 on plate at:", plate_pos)
        obs, reward, done = place(env, task, target_pos=np.array(plate_pos))
        if done:
            print("[Step 6] Task ended early. Reward:", reward)
            return

        # Step 7: pick tomato2 from the table
        print("[Step 7] pick tomato2 at:", tomato2_pos)
        obs, reward, done = pick(env, task, target_pos=np.array(tomato2_pos))
        if done:
            print("[Step 7] Task ended early. Reward:", reward)
            return

        # Step 8: place tomato2 on plate
        print("[Step 8] place tomato2 on plate at:", plate_pos)
        obs, reward, done = place(env, task, target_pos=np.array(plate_pos))
        if done:
            print("[Step 8] Task ended early. Reward:", reward)
            return

        # Plan complete
        print("===== Oracle Plan Execution Complete =====")
        print("Final reward:", reward, "Done flag:", done)

    except Exception as e:
        print("Exception during task execution:", str(e))
    finally:
        shutdown_environment(env)

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

if __name__ == "__main__":
    run_skeleton_task()