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

        # 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_pos = positions['bottom_side_pos']
        bottom_anchor_pos = positions['bottom_anchor_pos']
        rubbish_pos = positions['rubbish']
        bin_pos = positions['bin']

        # Step 1: Rotate gripper to 90 degrees
        print("[Task] Step 1: Rotating gripper to 90 degrees")
        ninety_deg_quat = np.array([0.0, 0.0, np.sin(np.pi/4), np.cos(np.pi/4)])

        # [Frozen Code Start]
        obs, reward, done = rotate(env, task, ninety_deg_quat)
        obs, reward, done = move(env, task, bottom_side_pos)
        obs, reward, done = move(env, task, bottom_anchor_pos)
        obs, reward, done = pull(env, task, pull_distance=0.1, pull_axis='x')
        obs, reward, done = pick(env, task, target_pos=np.array(rubbish_pos)
        # [Frozen Code End]

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

        # Step 6: Place rubbish into bin
        print("[Task] Step 6: Placing rubbish into bin at:", bin_pos)
        obs, reward, done = place(env, task, target_pos=np.array(bin_pos))
        if done:
            print("[Task] Task ended during place. Reward:", reward)
            return

        # Final outcome
        if not done:
            print("[Task] Plan executed. Final reward:", reward)
        else:
            print("[Task] Done flag True. 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()