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():
    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()

        # === Oracle Plan Execution ===
        # Step 1: Rotate gripper to 90 degrees about Z axis
        print("[Plan] Step 1: rotate gripper to 90° about Z")
        target_quat = np.array([0.0, 0.0, np.sin(np.pi/4), np.cos(np.pi/4)])

        # Step 2: Move to side position of bottom drawer
        print("[Plan] Step 2: move to bottom_side_pos")
        side_pos = positions['bottom_side_pos']

        # Step 3: Move to anchor position of bottom drawer
        print("[Plan] Step 3: move to bottom_anchor_pos")
        anchor_pos = positions['bottom_anchor_pos']

        # Step 4: Pull drawer open
        print("[Plan] Step 4: pull drawer open")

        # Step 5: Move to trash item (item3)
        print("[Plan] Step 5: move to trash item (item3)")
        trash_pos = positions['item3']

        # === Frozen Code Start ===
        obs, reward, done = rotate(env, task, target_quat)
        obs, reward, done = move(env, task, side_pos)
        obs, reward, done = move(env, task, anchor_pos)
        obs, reward, done = pull(env, task, pull_distance=0.1, pull_axis='x')
        obs, reward, done = move(env, task, trash_pos)
        # === Frozen Code End ===

        if done:
            print("[Plan] Task ended early. Reward:", reward)
            return

        # Step 6: Pick up the trash
        print("[Plan] Step 6: pick up trash")
        obs, reward, done = pick(env, task, target_pos=trash_pos)
        if done:
            print("[Plan] Task ended during pick. Reward:", reward)
            return

        # Step 7: Move to bin
        print("[Plan] Step 7: move to bin")
        bin_pos = positions['bin']
        obs, reward, done = move(env, task, bin_pos)
        if done:
            print("[Plan] Task ended during move to bin. Reward:", reward)
            return

        # Step 8: Place trash into bin
        print("[Plan] Step 8: place trash into bin")
        obs, reward, done = place(env, task, target_pos=bin_pos)
        if done:
            print("[Plan] Task ended during place. Reward:", reward)
            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()