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

import time
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():
    '''Task: Open one of the drawers in the cabinet by rotating the gripper, moving to the handle, picking it, and pulling it open.'''
    print("===== Starting Drawer-Opening Task =====")
    env, task = setup_environment()
    try:
        # Reset environment and initialize 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 all known object positions
        positions = get_object_positions()
        bottom_side_pos = positions['bottom_side_pos']
        bottom_anchor_pos = positions['bottom_anchor_pos']

        # Step 1: Rotate gripper from current orientation to ninety degrees about Z
        print("[Task] Step 1: Rotating gripper to 90° about Z-axis.")
        obs = task.get_observation()
        start_quat = obs.gripper_pose[3:7]
        current_euler = R.from_quat(start_quat).as_euler('xyz', degrees=True)
        target_euler = current_euler.copy()
        target_euler[2] += 90.0
        target_quat = R.from_euler('xyz', target_euler, degrees=True).as_quat()
        obs, reward, done = rotate(env, task, target_quat)
obs, reward, done = move(env, task, np.array(bottom_side_pos)

        if done:
            print("[Task] Ended prematurely after move-to-side. Reward:", reward)
            return

        # Step 3: Move to the anchor (handle) position of the bottom drawer
        print("[Task] Step 3: Moving to bottom drawer anchor position:", bottom_anchor_pos)
        obs, reward, done = move(env, task, np.array(bottom_anchor_pos))
        if done:
            print("[Task] Ended prematurely after move-to-anchor. Reward:", reward)
            return

        # Step 4: Pick (grasp) the bottom drawer handle
        print("[Task] Step 4: Grasping the bottom drawer handle.")
        obs, reward, done = pick(env, task, np.array(bottom_anchor_pos))
        if done:
            print("[Task] Ended prematurely after pick. Reward:", reward)
            return

        # Step 5: Pull the drawer open along its axis
        print("[Task] Step 5: Pulling the drawer open.")
        pull_distance = 0.05
        obs, reward, done = pull(env, task, pull_distance=pull_distance, pull_axis='x')
        if done:
            print("[Task] Task ended immediately after pull. Reward:", reward)
        else:
            print("[Task] Drawer should now be open. Final reward:", reward)

    except Exception as e:
        print(f"[Task] Exception encountered: {e}")
    finally:
        shutdown_environment(env)
        print("===== End of Drawer-Opening Task =====")

if __name__ == "__main__":
    run_skeleton_task()