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 *  # you don't need to redefine primitives like move, pick, place

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 =====")
    
    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()
        tomato1_pos = positions.get('tomato1')
        tomato2_pos = positions.get('tomato2')
        plate_pos = positions.get('plate')

        if tomato1_pos is None or tomato2_pos is None or plate_pos is None:
            raise ValueError("Required object positions ('tomato1', 'tomato2', or 'plate') not found.")

        tomato1_pos = np.array(tomato1_pos)
        tomato2_pos = np.array(tomato2_pos)
        plate_pos = np.array(plate_pos)

        # === Oracle Plan Execution ===
        # Step 1: Pick up 'tomato1'
        print("[Task] Picking up 'tomato1' from its current location at:", tomato1_pos)
        obs, reward, done = pick(
                env,
                task,
                target_pos=tomato1_pos,
                approach_distance=0.15,
                max_steps=100,
                threshold=0.01,
                approach_axis='z',
                timeout=10.0
            )
        if done:
            print(f"[Task] Execution ended prematurely after pick step for tomato1. Reward: {reward}")
            return

        # Step 2: Place 'tomato1' onto 'plate'
        print("[Task] Placing 'tomato1' onto 'plate' at:", plate_pos)
        try:
            obs, reward, done = place(
                env,
                task,
                target_pos=plate_pos,
                approach_distance=0.15,
                max_steps=100,
                threshold=0.01,
                approach_axis='z',
                timeout=10.0
            )
        except Exception as e:
            print(f"[Task] Exception during place step for tomato1: {e}")
            return
        if done:
            print(f"[Task] Task completed successfully after placing tomato1! Reward: {reward}")
        else:
            print(f"[Task] Continue executing plan. Current reward: {reward}")

        # Step 3: Pick up 'tomato2'
        print("[Task] Picking up 'tomato2' from its current location at:", tomato2_pos)
        try:
            obs, reward, done = pick(
                env,
                task,
                target_pos=tomato2_pos,
                approach_distance=0.15,
                max_steps=100,
                threshold=0.01,
                approach_axis='z',
                timeout=10.0
            )
        except Exception as e:
            print(f"[Task] Exception during pick step for tomato2: {e}")
            return
        if done:
            print(f"[Task] Execution ended prematurely after pick step for tomato2. Reward: {reward}")
            return

        # Step 4: Place 'tomato2' onto 'plate'
        print("[Task] Placing 'tomato2' onto 'plate' at:", plate_pos)
        try:
            obs, reward, done = place(
                env,
                task,
                target_pos=plate_pos,
                approach_distance=0.15,
                max_steps=100,
                threshold=0.01,
                approach_axis='z',
                timeout=10.0
            )
        except Exception as e:
            print(f"[Task] Exception during place step for tomato2: {e}")
            return
        if done:
            print(f"[Task] Task completed successfully after placing tomato2! Final reward: {reward}")
        else:
            print(f"[Task] Plan execution finished but done flag is False. 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()