import numpy as np
from scipy.spatial.transform import Rotation as R
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():
    print("===== Starting Skeleton Task =====")
    
    env, task = setup_environment()
    try:
        descriptions, obs = task.reset()
        init_video_writers(obs)
        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)
        
        positions = get_object_positions()
        
        # Step 1: Rotate gripper to ninety_deg
        print("[Plan] Step 1: rotate to ninety_deg")
        target_quat = R.from_euler('z', 90, degrees=True).as_quat()
        obs, reward, done = rotate(env, task, target_quat=target_quat)
        if done:
            print("[Plan] Early termination after rotate")
            return
        
        # Step 2: Move to side position of bottom drawer
        print("[Plan] Step 2: move to bottom_side_pos")
        side_pos = positions['bottom_side_pos']
        obs, reward, done = move(env, task, target_pos=np.array(side_pos))
        if done:
            print("[Plan] Early termination after move to side")
            return
        
        # Step 3: Move to anchor position of bottom drawer
        print("[Plan] Step 3: move to bottom_anchor_pos")
        anchor_pos = positions['bottom_anchor_pos']
        obs, reward, done = move(env, task, target_pos=np.array(anchor_pos))
        if done:
            print("[Plan] Early termination after move to anchor")
            return
        
        # Step 4: Pull drawer fully open
        print("[Plan] Step 4: pull drawer open")
        pull_distance = 0.1
        obs, reward, done = pull(env, task, pull_distance=pull_distance, pull_axis='x')
        if done:
            print("[Plan] Early termination after pull")
            return
        
        # Step 5: Move to the rubbish object
        print("[Plan] Step 5: move to rubbish")
        rubbish_pos = positions['rubbish']
        obs, reward, done = move(env, task, target_pos=np.array(rubbish_pos))
        if done:
            print("[Plan] Early termination after move to rubbish")
            return
        
        # Step 6: Pick up the rubbish
        print("[Plan] Step 6: pick rubbish")
        obs, reward, done = pick(env, task, target_pos=np.array(rubbish_pos))
        if done:
            print("[Plan] Early termination after pick")
            return
        
        # Step 7: Move to the bin
        print("[Plan] Step 7: move to bin")
        bin_pos = positions['bin']
        obs, reward, done = move(env, task, target_pos=np.array(bin_pos))
        if done:
            print("[Plan] Early termination after move to bin")
            return
        
        # Step 8: Place the rubbish in the bin
        print("[Plan] Step 8: place rubbish in bin")
        obs, reward, done = place(env, task, target_pos=np.array(bin_pos))
        if done:
            print("[Plan] Early termination after place")
            return
        
        if reward is not None:
            print(f"[Plan] Task completed successfully! Final reward: {reward}")
        else:
            print("[Plan] Task completed. Check environment for success.")
    
    except Exception as e:
        print(f"[Error] Exception during plan execution: {e}")
    finally:
        shutdown_environment(env)
    
    print("===== End of Skeleton Task =====")

if __name__ == "__main__":
    run_skeleton_task()