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 the combined-domain 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
        init_video_writers(obs)

        # Wrap 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()
        
        # Prepare targets for rubbish and bin
        rubbish_pos = positions.get('rubbish')
        if rubbish_pos is None:
            print("[Error] Could not find rubbish position")
            return
        rubbish_target = np.array(rubbish_pos)
        
        bin_pos = positions.get('bin')
        if bin_pos is None:
            print("[Error] Could not find bin position")
            return
        bin_target = np.array(bin_pos)

        # === Execute Oracle Plan ===
        
        # Step 1: Pull open any unlocked drawer
        print("[Task] Step 1: Pull drawer")
        # Calls in frozen region must remain exactly the same:
        obs, reward, done = pull(env, task, pull_distance=0.1, pull_axis='x')
obs, reward, done = pick(
                env,
                task,
                target_pos=rubbish_target,
                approach_distance=0.15,
                approach_axis='z'
            )
obs, reward, done = place(
                env,
                task,
                target_pos=bin_target,
                approach_distance=0.15,
                approach_axis='z'
            )

        # === Check Completion ===
        if done:
            print("[Task] Task completed successfully! Final reward:", reward)
        else:
            print("[Task] Plan executed, but task not marked done. Reward:", reward)

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

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

if __name__ == "__main__":
    run_skeleton_task()