from env import setup_environment, shutdown_environment
from skill_code import pick, place, move, rotate, pull
from video import init_video_writers, recording_step, recording_get_observation
from object_positions import get_object_positions
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:
        # Reset the task and start recording
        descriptions, obs = task.reset()
        init_video_writers(obs)
        task.step = recording_step(task.step)
        task.get_observation = recording_get_observation(task.get_observation)

        # Retrieve object positions from the scene
        positions = get_object_positions()
        bottom_side_pos = positions['bottom_side_pos']
        bottom_anchor_pos = positions['bottom_anchor_pos']
        plate_pos = positions['plate']
        item1_pos = positions['item1']
        item2_pos = positions['item2']

        # Step 1: Rotate gripper to 90 degrees about the Y axis
        ninety_quat = R.from_euler('y', 90, degrees=True).as_quat()  # Returns [x, y, z, w]
        print("[Plan] Step 1: rotate to ninety_deg")
        obs, reward, done = rotate(env, task, ninety_quat)
        if done:
            print("Task ended after rotate")
            return

        # Step 2: Move to the side position of the bottom drawer
        print(f"[Plan] Step 2: move to bottom_side_pos {bottom_side_pos}")
        obs, reward, done = move(env, task, np.array(bottom_side_pos))
        if done:
            print("Task ended after move to side")
            return

        # Step 3: Move to the anchor position of the bottom drawer
        print(f"[Plan] Step 3: move to bottom_anchor_pos {bottom_anchor_pos}")
        obs, reward, done = move(env, task, np.array(bottom_anchor_pos))
        if done:
            print("Task ended after move to anchor")
            return

        # Step 4: Pull the drawer open by 0.1m along the X axis
        print("[Plan] Step 4: pull drawer open")
        obs, reward, done = pull(env, task, pull_distance=0.1, pull_axis='x')
        if done:
            print("Task ended after pull")
            return

        # Step 5: Pick the first tomato (item1)
        print(f"[Plan] Step 5: pick item1 at {item1_pos}")
        obs, reward, done = pick(env, task, np.array(item1_pos))
        if done:
            print("Task ended after pick item1")
            return

        # Step 6: Place item1 on the plate
        print(f"[Plan] Step 6: place item1 on plate at {plate_pos}")
        obs, reward, done = place(env, task, np.array(plate_pos))
        if done:
            print("Task ended after place item1")
            return

        # Step 7: Pick the second tomato (item2)
        print(f"[Plan] Step 7: pick item2 at {item2_pos}")
        obs, reward, done = pick(env, task, np.array(item2_pos))
        if done:
            print("Task ended after pick item2")
            return

        # Step 8: Place item2 on the plate
        print(f"[Plan] Step 8: place item2 on plate at {plate_pos}")
        obs, reward, done = place(env, task, np.array(plate_pos))
        if done:
            print("Task ended after place item2")
            return

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

    except Exception as e:
        print("Error during task execution:", e)

    finally:
        shutdown_environment(env)
        print("===== End of Skeleton Task =====")

if __name__ == "__main__":
    run_skeleton_task()