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

def run_skeleton_task():
    '''Generic skeleton for running any task in your simulation.'''
    print("===== Starting Skeleton Task =====")
    
    # === Environment Setup ===
    env, task = setup_environment()
    try:
        # Reset the task to its initial state
        descriptions, obs = task.reset()

        # (Optional) Initialize video writers for capturing your simulation
        init_video_writers(obs)

        # Wrap the task steps for recording (if needed)
        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()
        bottom_side = positions['bottom_side_pos']
        bottom_anchor = positions['bottom_anchor_pos']
        item1_pos = positions['item1']
        item2_pos = positions['item2']
        plate_pos = positions['plate']

        # === Oracle Plan Execution ===
        # Step 1: rotate gripper to 90° around Z
        print("[Plan] Step 1: rotate gripper to 90° around Z")
        ninety_quat = np.array([0.0, 0.0, 0.70710678, 0.70710678])
        # Step 2: move to bottom drawer side position
        print("[Plan] Step 2: move to bottom drawer side position")
        # Step 3: move to bottom drawer anchor position
        print("[Plan] Step 3: move to bottom drawer anchor position")
        # Step 4: pull bottom drawer open
        print("[Plan] Step 4: pull bottom drawer open")
        # Step 5: pick item1 from table
        print("[Plan] Step 5: pick item1 from table")
        # Step 6: place item1 onto plate
        print("[Plan] Step 6: place item1 onto plate")
        [Frozen Code Start]
        obs, reward, done = rotate(env, task, ninety_quat)
        obs, reward, done = move(env, task, bottom_side)
        obs, reward, done = move(env, task, bottom_anchor)
        obs, reward, done = pull(env, task, pull_distance=0.1, pull_axis='x')
        obs, reward, done = pick(env, task, item1_pos, approach_distance=0.15, approach_axis='z')
        obs, reward, done = place(env, task, plate_pos, approach_distance=0.15, approach_axis='z')
        [Frozen Code End]
        if done:
            print("[Plan] Early termination after step 6 (place item1).")
            return

        # Step 7: pick item2 from table
        print("[Plan] Step 7: pick item2 from table")
        obs, reward, done = pick(env, task, item2_pos, approach_distance=0.15, approach_axis='z')
        if done:
            print("[Plan] Early termination after pick item2.")
            return

        # Step 8: place item2 onto plate
        print("[Plan] Step 8: place item2 onto plate")
        obs, reward, done = place(env, task, plate_pos, approach_distance=0.15, approach_axis='z')
        if done:
            print("[Plan] Early termination after place item2.")
            return

        # Final report
        print("[Task] Completed oracle plan. Final reward:", reward)

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

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


if __name__ == "__main__":
    run_skeleton_task()