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 *

from video import init_video_writers, recording_step, recording_get_observation

from object_positions import get_object_positions

[Frozen Code Start]
    
[Frozen Code End]

def run_skeleton_task():
    '''Runs the oracle plan: open drawer, then toss tomatoes onto plate.'''
    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 task.step and task.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()
        # Expecting keys: 'bottom_side_pos', 'bottom_anchor_pos', 'tomato1', 'tomato2', 'plate'
        
        # === Oracle Plan Execution ===

        # Step 1: Rotate gripper from zero_deg to ninety_deg
        # Create a quaternion for 90 degrees around Z axis: [x,y,z,w]
        ninety_deg_quat = np.array([0.0, 0.0, np.sin(np.pi/4), np.cos(np.pi/4)])
        print("[Plan] Step 1: rotate gripper to ninety_deg")
        obs, reward, done = rotate(env, task, ninety_deg_quat)
        if done:
            print("[Plan] Early termination after rotate.")
            return

        # Step 2: Move to side position of bottom drawer
        side_pos = positions.get('bottom_side_pos')
        print(f"[Plan] Step 2: move to side pos {side_pos}")
        obs, reward, done = move(env, task, np.array(side_pos))
        if done:
            print("[Plan] Early termination after move-to-side.")
            return

        # Step 3: Move to anchor position of bottom drawer
        anchor_pos = positions.get('bottom_anchor_pos')
        print(f"[Plan] Step 3: move to anchor pos {anchor_pos}")
        obs, reward, done = move(env, task, np.array(anchor_pos))
        if done:
            print("[Plan] Early termination after move-to-anchor.")
            return

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

        # Step 5: Pull drawer open
        # choice of pull distance and axis; adjust as needed
        pull_distance = 0.1
        pull_axis = 'x'
        print(f"[Plan] Step 5: pull drawer by {pull_distance} along {pull_axis}")
        obs, reward, done = pull(env, task, pull_distance=pull_distance, pull_axis=pull_axis)
        if done:
            print("[Plan] Early termination after pull.")
            return

        # Step 6: Pick tomato1 from table
        tomato1_pos = positions.get('tomato1')
        print(f"[Plan] Step 6: pick tomato1 at {tomato1_pos}")
        obs, reward, done = pick(env, task, np.array(tomato1_pos))
        if done:
            print("[Plan] Early termination after pick(tomato1).")
            return

        # Step 7: Place tomato1 on plate
        plate_pos = positions.get('plate')
        print(f"[Plan] Step 7: place tomato1 on plate at {plate_pos}")
        obs, reward, done = place(env, task, np.array(plate_pos))
        if done:
            print("[Plan] Early termination after place(tomato1).")
            return

        # Step 8: Pick tomato2 from table
        tomato2_pos = positions.get('tomato2')
        print(f"[Plan] Step 8: pick tomato2 at {tomato2_pos}")
        obs, reward, done = pick(env, task, np.array(tomato2_pos))
        if done:
            print("[Plan] Early termination after pick(tomato2).")
            return

        # Step 9: Place tomato2 on plate
        print(f"[Plan] Step 9: place tomato2 on plate at {plate_pos}")
        obs, reward, done = place(env, task, np.array(plate_pos))
        if done:
            print("[Plan] Early termination after place(tomato2).")
            return

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

    except Exception as e:
        print(f"[Error] Exception during plan execution: {e}")
        raise
    finally:
        # Always ensure the environment is properly shutdown
        shutdown_environment(env)

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


if __name__ == "__main__":
    run_skeleton_task()
