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
import numpy as np

def run_skeleton_task():
    print("===== Starting Skeleton Task =====")
    env, task = setup_environment()
    try:
        descriptions, obs = task.reset()
        init_video_writers(obs)
        # wrap for recording
        task.step = recording_step(task.step)
        task.get_observation = recording_get_observation(task.get_observation)

        # retrieve all object positions
        positions = get_object_positions()
        # pick an accessible drawer (bottom), tomatoes and plate
        tomato1_pos = positions['item1']
        tomato2_pos = positions['item2']
        plate_pos   = positions['plate']

        # Step 1: rotate gripper to 90 degrees about Y axis (quaternion [x,y,z,w])
        target_quat = np.array([0.0, 1.0, 0.0, 0.0])
        print("[Plan] Step 1: rotate gripper to 90_deg")
        obs, reward, done = rotate(env, task, target_quat)
        if done:
            print("[Plan] ended early after rotate")
            return

        # Step 2: pull the drawer handle to open (assumes handle aligned along +x)
        pull_distance = 0.05
        print("[Plan] Step 2: pull drawer to open")
        obs, reward, done = pull(env, task, pull_distance=pull_distance, pull_axis='x')
        if done:
            print("[Plan] ended early after pull")
            return

        # Step 3: pick first tomato
        print("[Plan] Step 3: pick tomato1")
        obs, reward, done = pick(env, task, target_pos=tomato1_pos)
        if done:
            print("[Plan] ended early after first pick")
            return

        # Step 4: pick second tomato
        print("[Plan] Step 4: pick tomato2")
        obs, reward, done = pick(env, task, target_pos=tomato2_pos)
        if done:
            print("[Plan] ended early after second pick")
            return

        # Step 5: place first tomato onto plate
        print("[Plan] Step 5: place tomato1 on plate")
        obs, reward, done = place(env, task, target_pos=plate_pos)
        if done:
            print("[Plan] ended early after first place")
            return

        # Step 6: place second tomato onto plate
        print("[Plan] Step 6: place tomato2 on plate")
        obs, reward, done = place(env, task, target_pos=plate_pos)
        if done:
            print("[Plan] ended early after second place")
            return

        print("[Plan] Completed all steps. Final reward:", reward)

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

if __name__ == "__main__":
    run_skeleton_task()