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

def run_skeleton_task():
    print("===== Starting Skeleton Task =====")
    env, task = setup_environment()
    try:
        descriptions, obs = task.reset()
        init_video_writers(obs)
        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)

        positions = get_object_positions()
        side_bottom_pos = np.array(positions['bottom_side_pos'])
        anchor_bottom_pos = np.array(positions['bottom_anchor_pos'])
        joint_bottom_pos = np.array(positions['bottom_joint_pos'])
        pull_distance = np.linalg.norm(joint_bottom_pos - anchor_bottom_pos)

        # Step 1: rotate gripper to 90 degrees
        print("[Plan] Step 1: rotate gripper to 90 degrees")
        target_quat = R.from_euler('z', 90, degrees=True).as_quat()

        # Step 2: move to side-bottom position
        print("[Plan] Step 2: move to side-bottom position")

[Frozen Code Start]
    obs, reward, done = rotate(env, task, target_quat=target_quat)
obs, reward, done = move(env, task, target_pos=side_bottom_pos)
[Frozen Code End]

        if done:
            print("[Plan] Task ended early. Reward:", reward)
            return

        # Step 3: move to anchor-bottom position
        print("[Plan] Step 3: move to anchor-bottom position")
        try:
            obs, reward, done = move(env, task, target_pos=anchor_bottom_pos)
            if done:
                print("[Plan] Task ended after move to anchor. Reward:", reward)
                return
        except Exception as e:
            print("[Plan] Error during move to anchor position:", e)
            return

        # Step 4: pick bottom drawer
        print("[Plan] Step 4: pick bottom drawer")
        try:
            obs, reward, done = pick(env, task, target_pos=anchor_bottom_pos)
            if done:
                print("[Plan] Task ended after pick. Reward:", reward)
                return
        except Exception as e:
            print("[Plan] Error during pick:", e)
            return

        # Step 5: pull bottom drawer open
        print(f"[Plan] Step 5: pull bottom drawer by distance {pull_distance:.3f}")
        try:
            obs, reward, done = pull(env, task, pull_distance=pull_distance, pull_axis='x')
            if done:
                print("[Plan] Task ended after pull. Reward:", reward)
                return
        except Exception as e:
            print("[Plan] Error during pull:", e)
            return

        print("[Plan] Completed oracle plan. Final reward:", reward)
    finally:
        shutdown_environment(env)
    print("===== End of Skeleton Task =====")

if __name__ == "__main__":
    run_skeleton_task()