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
from scipy.spatial.transform import Rotation as R

def run_skeleton_task():
    '''Generic skeleton for running the combined drawer‐and‐disposal task.'''
    print("===== Starting Skeleton Task =====")
    
    # === Environment Setup ===
    env, task = setup_environment()
    try:
        # Reset the task to its initial state
        descriptions, obs = task.reset()

        # Initialize video recording if needed
        init_video_writers(obs)

        # Wrap step and observation for recording
        task.step = recording_step(task.step)
        task.get_observation = recording_get_observation(task.get_observation)

        # === Retrieve Object Positions ===
        positions = get_object_positions()
        side_pos_bottom   = positions['bottom_side_pos']
        anchor_pos_bottom = positions['bottom_anchor_pos']
        table_pos         = positions['table']
        bin_pos           = positions['bin']
        rubbish_pos       = positions['rubbish']

        # === Execute Oracle Plan Steps ===

        # Step 1: move to side‐pos‐bottom
        print("[Task] Step 1: move to side-pos-bottom")
        obs, reward, done = move(env, task, target_pos=side_pos_bottom)
        if done:
            print("[Task] Terminated early after move. Reward:", reward)
            return

        # Step 2: rotate gripper to ninety_deg about Z
        print("[Task] Step 2: rotate to ninety_deg")
        target_quat = R.from_euler('z', 90, degrees=True).as_quat()
        obs, reward, done = rotate(env, task, target_quat)
        if done:
            print("[Task] Terminated early after rotate. Reward:", reward)
            return

        # Step 3: move to anchor‐pos‐bottom
        print("[Task] Step 3: move to anchor-pos-bottom")
        obs, reward, done = move(env, task, target_pos=anchor_pos_bottom)
        if done:
            print("[Task] Terminated early after move to anchor. Reward:", reward)
            return

        # Step 4: pull the drawer open
        print("[Task] Step 4: pull drawer")
        obs, reward, done = pull(env, task, pull_distance=0.1, pull_axis='x')
        if done:
            print("[Task] Terminated early after pull. Reward:", reward)
            return

        # Step 5: pick up rubbish from the table
        print("[Task] Step 5: pick rubbish from table")
        [Frozen Code Start]
        obs, reward, done = move(env, task, target_pos=side_pos_bottom)
        obs, reward, done = rotate(env, task, target_quat)
        obs, reward, done = move(env, task, target_pos=anchor_pos_bottom)
        obs, reward, done = pull(env, task, pull_distance=0.1, pull_axis='x')
        obs, reward, done = pick(env, task, target_pos=rubbish_pos)
        [Frozen Code End]
        if done:
            print("[Task] Terminated early after pick. Reward:", reward)
            return

        # Step 6: place rubbish into the bin
        print("[Task] Step 6: place rubbish into bin")
        obs, reward, done = place(env, task, target_pos=bin_pos)
        if done:
            print("[Task] Completed successfully! Reward:", reward)
        else:
            print("[Task] Finished execution with done=False. Reward:", reward)

    except Exception as e:
        print(f"[Task] Exception during execution: {e}")
    finally:
        # Always ensure the environment is properly shutdown
        shutdown_environment(env)

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

if __name__ == "__main__":
    run_skeleton_task()
