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 "open drawer" 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 for capturing your simulation
        init_video_writers(obs)

        # Wrap the task steps 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()
        # We choose to open the bottom drawer
        bottom_side_pos   = positions['bottom_side_pos']
        bottom_anchor_pos = positions['bottom_anchor_pos']

        # === Oracle Plan Execution ===
        # Step 1: Rotate gripper to ninety_deg orientation
        try:
            print("[Plan] Step 1: rotate to 90 degrees about z")
            target_quat = R.from_euler('z', 90, degrees=True).as_quat()
            obs, reward, done = rotate(env, task, target_quat)
            if done:
                print("[Plan] Early termination after rotate")
                return
        except Exception as e:
            print(f"[Error] rotate failed: {e}")
            return

        # Step 2: Move gripper to side of drawer
        try:
            print("[Plan] Step 2: move to drawer side position", bottom_side_pos)
            obs, reward, done = move(env, task, bottom_side_pos)
            if done:
                print("[Plan] Early termination after move to side")
                return
        except Exception as e:
            print(f"[Error] move to side failed: {e}")
            return

        # [Frozen Code Start]
        obs, reward, done = rotate(env, task, target_quat)
        obs, reward, done = move(env, task, bottom_side_pos)
        # [Frozen Code End]

        # Step 3: Move gripper to anchor position on drawer
        try:
            print("[Plan] Step 3: move to drawer anchor position", bottom_anchor_pos)
            obs, reward, done = move(env, task, bottom_anchor_pos)
            if done:
                print("[Plan] Early termination after move to anchor")
                return
        except Exception as e:
            print(f"[Error] move to anchor failed: {e}")
            return

        # Step 4: Pick/grasp the drawer handle
        try:
            print("[Plan] Step 4: pick at anchor position", bottom_anchor_pos)
            obs, reward, done = pick(env, task, bottom_anchor_pos)
            if done:
                print("[Plan] Early termination after pick")
                return
        except Exception as e:
            print(f"[Error] pick failed: {e}")
            return

        # Step 5: Pull the drawer to open it
        try:
            print("[Plan] Step 5: pull to open drawer by 0.1m along x-axis")
            obs, reward, done = pull(env, task, pull_distance=0.1, pull_axis='x')
            if done:
                print("[Plan] Early termination after pull")
                return
        except Exception as e:
            print(f"[Error] pull failed: {e}")
            return

        # Check completion
        if done or (reward is not None and reward > 0):
            print("[Task] Task completed! Reward:", reward)
        else:
            print("[Task] Plan executed. Final state reached but done=False.")

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

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

if __name__ == "__main__":
    run_skeleton_task()