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()
        # We expect keys like 'bottom_side_pos', 'bottom_anchor_pos', 'rubbish', 'bin'
        bottom_side = positions['bottom_side_pos']
        bottom_anchor = positions['bottom_anchor_pos']
        rubbish_pos = positions['rubbish']
        bin_pos = positions['bin']

        # === Task Plan Execution ===

        # 1) Rotate gripper from zero to ninety degrees around Z axis
        zero_quat = R.from_euler('z', 0, degrees=True).as_quat()
        ninety_quat = R.from_euler('z', 90, degrees=True).as_quat()
        print("[Task] Rotating gripper to 90°")
        obs, reward, done = rotate(env, task, ninety_quat)
        if done:
            print("[Task] Episode ended after rotate. Reward:", reward)
            return

        # 2) Move gripper to drawer side position
        print(f"[Task] Moving to side position of bottom drawer: {bottom_side}")
        obs, reward, done = move(env, task, array(bottom_side))
        if done:
            print("[Task] Episode ended after move-to-side. Reward:", reward)
            return

        # 3) Move gripper to drawer anchor position
        print(f"[Task] Moving to anchor position of bottom drawer: {bottom_anchor}")
        obs, reward, done = move(env, task, array(bottom_anchor))
        if done:
            print("[Task] Episode ended after move-to-anchor. Reward:", reward)
            return

        # 4) Pick the drawer handle (treat as pick action)
        print(f"[Task] Picking drawer handle at: {bottom_anchor}")
        obs, reward, done = pick(env, task, array(bottom_anchor))
        if done:
            print("[Task] Episode ended after pick-drawer. Reward:", reward)
            return

        # 5) Pull the drawer open (pull along x by 0.2m)
        print("[Task] Pulling drawer open")
        obs, reward, done = pull(env, task, pull_distance=0.2, pull_axis='x')
        if done:
            print("[Task] Episode ended after pull. Reward:", reward)
            return

        # 6) Pick up the rubbish on the table
        print(f"[Task] Picking up rubbish at: {rubbish_pos}")
        obs, reward, done = pick(env, task, array(rubbish_pos))
        if done:
            print("[Task] Episode ended after pick rubbish. Reward:", reward)
            return

        # 7) Place the rubbish into the bin
        print(f"[Task] Placing rubbish into bin at: {bin_pos}")
        obs, reward, done = place(env, task, array(bin_pos))
        if done:
            print("[Task] Task completed successfully! Reward:", reward)
        else:
            print("[Task] Placed rubbish but episode 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()