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 =====")
    # === Environment Setup ===
    env, task = setup_environment()
    try:
        # Reset and initialize video 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 ===
        positions = get_object_positions()
        # Choose the bottom drawer for opening
        bottom_side_pos = np.array(positions['bottom_side_pos'])
        bottom_anchor_pos = np.array(positions['bottom_anchor_pos'])
        # Rubbish and bin positions
        rubbish_pos = np.array(positions['rubbish'])
        bin_pos = np.array(positions['bin'])

        # === Execute Oracle Plan ===

        # Step 1: Rotate gripper from zero to ninety degrees about the z-axis
        print("[Plan] Step 1: rotate to ninety_deg")
        quat_ninety = R.from_euler('z', 90, degrees=True).as_quat()
        obs, reward, done = rotate(env, task, quat_ninety)
        if done:
            print("[Plan] Early termination after rotate.")
            return

        # Step 2: Move to side position of bottom drawer
        print("[Plan] Step 2: move to bottom side position")
        obs, reward, done = move(env, task, bottom_side_pos)
        if done:
            print("[Plan] Early termination after move to side.")
            return

        # Step 3: Move to anchor position of bottom drawer
        print("[Plan] Step 3: move to bottom anchor position")
        obs, reward, done = move(env, task, bottom_anchor_pos)
        if done:
            print("[Plan] Early termination after move to anchor.")
            return

        # Step 4: Pick the drawer handle at the anchor position
        print("[Plan] Step 4: pick drawer handle")
        obs, reward, done = pick(env, task, bottom_anchor_pos)
        if done:
            print("[Plan] Early termination after pick drawer.")
            return

        # Step 5: Pull the drawer out by a small distance along x-axis
        print("[Plan] Step 5: pull drawer open")
        pull_distance = 0.1  # Adjust as needed to open fully
        obs, reward, done = pull(env, task, pull_distance, pull_axis='x')
        if done:
            print("[Plan] Early termination after pull.")
            return

        # Step 6: Pick up the rubbish from the table
        print("[Plan] Step 6: pick rubbish from table")
        obs, reward, done = pick(env, task, rubbish_pos)
        if done:
            print("[Plan] Early termination after pick rubbish.")
            return

        # Step 7: Place the rubbish into the bin
        print("[Plan] Step 7: place rubbish in bin")
        obs, reward, done = place(env, task, bin_pos)
        if done:
            print("[Plan] Task completed successfully! Reward:", reward)
        else:
            print("[Plan] Task finished but done=False. Reward:", reward)

    except Exception as e:
        print(f"[Error] Exception during task execution: {e}")
        raise
    finally:
        shutdown_environment(env)
        print("===== End of Skeleton Task =====")

if __name__ == "__main__":
    run_skeleton_task()