# run_skeleton_task.py

import numpy as np
from pyrep.objects.shape import Shape
from pyrep.objects.proximity_sensor import ProximitySensor

from env import setup_environment, shutdown_environment

from skill_code import *    # provides 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():
    '''Generic skeleton for running the drawer‐and‐tomatoes task in simulation.'''
    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 needed
        init_video_writers(obs)

        # Wrap the step and get_observation methods 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()
        # Drawer handle side position and anchor (handle) position
        drawer_side_pos = positions['bottom_side_pos']
        drawer_anchor_pos = positions['bottom_anchor_pos']
        # Plate position for placing tomatoes
        plate_pos = positions['plate']

        # === Oracle Plan Execution ===

        # Step 1: Rotate gripper to align for drawer handle
        #    (Rotate 90 degrees about Z axis)
        from scipy.spatial.transform import Rotation as R
        target_quat = R.from_euler('xyz', [0, 0, 90], degrees=True).as_quat()
        print("[Plan] Step 1: rotate to target orientation for drawer")
        obs, reward, done = rotate(env, task, target_quat)
        if done:
            print("[Plan] Terminated early during rotate")
            return

        # Step 2: Move gripper to the side position of the drawer
        print("[Plan] Step 2: move to drawer side position")
        obs, reward, done = move(env, task, drawer_side_pos)
        if done:
            print("[Plan] Terminated early during move to side")
            return

        # Step 3: Pull the drawer open
        #    (Assume pulling 0.05m along the local X-axis opens the drawer)
        print("[Plan] Step 3: pull drawer open")
        obs, reward, done = pull(env, task, pull_distance=0.05, pull_axis='x')
        if done:
            print("[Plan] Terminated early during pull")
            return

        # Step 4: Pick first tomato (item1) and place it on the plate
        print("[Plan] Step 4: pick item1 (tomato) from table")
        obs, reward, done = pick(env, task, positions['item1'])
        if done:
            print("[Plan] Terminated early during pick item1")
            return
        print("[Plan] Step 5: place item1 on plate")
        obs, reward, done = place(env, task, plate_pos)
        if done:
            print("[Plan] Terminated early during place item1")
            return

        # Step 6: Pick second tomato (item2) and place it on the plate
        print("[Plan] Step 6: pick item2 (tomato) from table")
        obs, reward, done = pick(env, task, positions['item2'])
        if done:
            print("[Plan] Terminated early during pick item2")
            return
        print("[Plan] Step 7: place item2 on plate")
        obs, reward, done = place(env, task, plate_pos)
        if done:
            print("[Plan] Terminated early during place item2")
            return

        # If we reach here, the plan finished without an early 'done'
        print("[Plan] Task completed successfully. Final reward:", reward)

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

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


if __name__ == "__main__":
    run_skeleton_task()