# run_skeleton_task.py

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 *  # Use provided skills: move, pick, place, rotate, pull

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()
        # Object names from object list:
        # [
        # 'bottom_anchor_pos', 'bottom_joint_pos', 'bottom_side_pos',
        # 'middle_anchor_pos', 'middle_joint_pos', 'middle_side_pos',
        # 'top_anchor_pos', 'top_joint_pos', 'top_side_pos', 'waypoint1',
        # 'rubbish', 'tomato1', 'tomato2', 'bin'
        # ]

        # === PLAN EXECUTION ===
        # Goal: Unlock the cabinet by opening an accessible drawer, then throw away the trash while leaving any other objects alone.

        # We will use the bottom drawer (assumed accessible and not locked).
        # Plan (from specification):
        # 1. rotate
        # 2. move
        # 3. move
        # 4. pick (drawer handle)
        # 5. pull (open drawer)
        # 6. pick (rubbish)
        # 7. place (rubbish in bin)

        # Step 1: Rotate gripper to 90 degrees (for side grasp)
        try:
            # Get current gripper pose
            obs = task.get_observation()
            start_quat = obs.gripper_pose[3:7]
            # Target: 90 deg about z axis (assuming 'zero_deg' is [0,0,0,1], 'ninety_deg' is [0,0,sin(45°),cos(45°)])
            # We'll use euler to quat conversion for 90 deg about z
            from scipy.spatial.transform import Rotation as R
            target_euler = [0, 0, np.deg2rad(90)]
            target_quat = R.from_euler('xyz', target_euler).as_quat()  # xyzw
            obs, reward, done = rotate(env, task, target_quat)
            if done:
                print("[Task] Task ended after rotate!")
                return
        except Exception as e:
            print(f"[ERROR] Step 1 (rotate) failed: {e}")
            shutdown_environment(env)
            return

        # Step 2: Move to side position of bottom drawer
        try:
            bottom_side_pos = positions.get('bottom_side_pos')
            if bottom_side_pos is None:
                raise ValueError("bottom_side_pos not found in positions.")
            obs, reward, done = move(env, task, bottom_side_pos)
            if done:
                print("[Task] Task ended after move to bottom_side_pos!")
                return
        except Exception as e:
            print(f"[ERROR] Step 2 (move to side) failed: {e}")
            shutdown_environment(env)
            return

        # Step 3: Move to anchor position of bottom drawer (for grasping handle)
        try:
            bottom_anchor_pos = positions.get('bottom_anchor_pos')
            if bottom_anchor_pos is None:
                raise ValueError("bottom_anchor_pos not found in positions.")
            obs, reward, done = move(env, task, bottom_anchor_pos)
            if done:
                print("[Task] Task ended after move to bottom_anchor_pos!")
                return
        except Exception as e:
            print(f"[ERROR] Step 3 (move to anchor) failed: {e}")
            shutdown_environment(env)
            return

        # Step 4: Pick the drawer handle (anchor position)
        try:
            # Use pick at anchor position (simulate grasping the handle)
            obs, reward, done = pick(env, task, bottom_anchor_pos, approach_distance=0.10, approach_axis='z')
            if done:
                print("[Task] Task ended after pick drawer handle!")
                return
        except Exception as e:
            print(f"[ERROR] Step 4 (pick drawer handle) failed: {e}")
            shutdown_environment(env)
            return

        # Step 5: Pull the drawer open (pull along x axis, e.g., 0.15m)
        try:
            obs, reward, done = pull(env, task, pull_distance=0.15, pull_axis='x')
            if done:
                print("[Task] Task ended after pull!")
                return
        except Exception as e:
            print(f"[ERROR] Step 5 (pull drawer) failed: {e}")
            shutdown_environment(env)
            return

        # Step 6: Pick the rubbish from the table
        try:
            rubbish_pos = positions.get('rubbish')
            if rubbish_pos is None:
                raise ValueError("rubbish not found in positions.")
            obs, reward, done = pick(env, task, rubbish_pos, approach_distance=0.15, approach_axis='z')
            if done:
                print("[Task] Task ended after pick rubbish!")
                return
        except Exception as e:
            print(f"[ERROR] Step 6 (pick rubbish) failed: {e}")
            shutdown_environment(env)
            return

        # Step 7: Place the rubbish in the bin
        try:
            bin_pos = positions.get('bin')
            if bin_pos is None:
                raise ValueError("bin not found in positions.")
            obs, reward, done = place(env, task, bin_pos, approach_distance=0.15, approach_axis='z')
            if done:
                print("[Task] Task completed successfully! Reward:", reward)
            else:
                print("[Task] Task not completed yet (done=False).")
        except Exception as e:
            print(f"[ERROR] Step 7 (place rubbish) failed: {e}")
            shutdown_environment(env)
            return

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

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


if __name__ == "__main__":
    run_skeleton_task()
