import numpy as np
from env import setup_environment, shutdown_environment
from video import init_video_writers, recording_step, recording_get_observation
from object_positions import get_object_positions
from skill_code import move, pick, place, rotate, pull, normalize_quaternion
from scipy.spatial.transform import Rotation as R

def run_skeleton_task():
    print("===== Starting Skeleton Task =====")
    
    # === Environment Setup ===
    env, task = setup_environment()
    try:
        # Reset the task to its initial state
        descriptions, obs = task.reset()

        # Initialize video writers if desired
        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()
        side_pos_bottom   = positions['bottom_side_pos']
        anchor_pos_bottom = positions['bottom_anchor_pos']
        table_pos         = positions['table']
        bin_pos           = positions['bin']
        rubbish_pos       = positions['rubbish']

        # === Oracle Plan Execution ===

        # Step 1: Rotate gripper from 0 to 90 degrees about z-axis
        zero_quat   = normalize_quaternion(R.from_euler('xyz', [0,0,0],  degrees=True).as_quat())
        ninety_quat = normalize_quaternion(R.from_euler('xyz', [0,0,90], degrees=True).as_quat())
        print("[Plan] Step 1: rotate gripper to ninety_deg")
        obs, reward, done = rotate(env, task, ninety_quat)
        if done:
            print("[Plan] Finished early after rotate.")
            return

        # Step 2: Move gripper to side-pos-bottom
        print("[Plan] Step 2: move gripper to side-pos-bottom")
        obs, reward, done = move(env, task, side_pos_bottom)
        if done:
            print("[Plan] Finished early after move to side-pos-bottom.")
            return

        # Step 3: Move gripper to anchor-pos-bottom
        print("[Plan] Step 3: move gripper to anchor-pos-bottom")
        obs, reward, done = move(env, task, anchor_pos_bottom)
        if done:
            print("[Plan] Finished early after move to anchor-pos-bottom.")
            return

        # Step 4: Pull drawer open
        print("[Plan] Step 4: pull bottom drawer open")
        vec = anchor_pos_bottom - side_pos_bottom
        abs_vec = np.abs(vec)
        idx = int(np.argmax(abs_vec))
        axis_label = ['x','y','z'][idx]
        pull_axis = axis_label if vec[idx] > 0 else '-' + axis_label
        pull_distance = float(abs_vec[idx])
        obs, reward, done = pull(env, task, pull_distance, pull_axis)
        if done:
            print("[Plan] Finished early after pull.")
            return

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

        # Step 6: Place the rubbish into the bin
        print("[Plan] Step 6: place rubbish into bin")
        obs, reward, done = place(env, task, bin_pos)
        if done:
            print("[Plan] Task completed successfully with reward:", reward)
        else:
            print("[Plan] Task ended without done=True. Reward:", reward)

    finally:
        # Always ensure the environment is properly shutdown
        shutdown_environment(env)

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

if __name__ == "__main__":
    run_skeleton_task()