import numpy as np
from scipy.spatial.transform import Rotation as R

from env import setup_environment, shutdown_environment
from skill_code import move, pick, place, rotate, pull
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 =====")
    env, task = setup_environment()
    try:
        # Reset the task to its initial state
        descriptions, obs = task.reset()

        # Initialize video writers for 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()  # e.g., {'bottom_side_pos': array([...]), ...}

        # Prepare quaternions for zero_deg and ninety_deg about the Y axis
        zero_quat = R.from_euler('y', 0.0, degrees=True).as_quat()
        ninety_quat = R.from_euler('y', 90.0, degrees=True).as_quat()

        # Extract required positions
        bottom_side_pos = np.array(positions['bottom_side_pos'])
        bottom_anchor_pos = np.array(positions['bottom_anchor_pos'])

        # === Oracle Plan Execution ===

        # Step 1: rotate gripper to ninety_deg orientation
        print("[Step 1] rotate gripper to ninety_deg orientation")
        # Step 2: move gripper to side of bottom drawer
        print("[Step 2] move gripper to bottom side position")
        # Step 3: move gripper to anchor of bottom drawer
        print("[Step 3] move gripper to bottom anchor position")
        # Step 4: pick the drawer handle at anchor position
        print("[Step 4] pick bottom drawer handle")
        # [Frozen Code Start]
        obs, reward, done = rotate(env, task, target_quat=ninety_quat)
        obs, reward, done = move(env, task, target_pos=bottom_side_pos)
        obs, reward, done = move(env, task, target_pos=bottom_anchor_pos)
        obs, reward, done = pick(env, task, target_pos=bottom_anchor_pos)
        # [Frozen Code End]
        if done:
            print("[Step 4] Task ended during one of the first four steps")
            return

        # Step 5: pull the drawer open
        print("[Step 5] pull bottom drawer to open cabinet")
        pull_distance = 0.2
        obs, reward, done = pull(env, task, pull_distance=pull_distance)
        if done:
            print("[Step 5] Task ended during pull")
            return

        # Success
        print("===== Task completed: drawer should now be open =====")

    finally:
        shutdown_environment(env)

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

if __name__ == "__main__":
    run_skeleton_task()