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():
    '''Task: Open one of the drawers in the cabinet, then put the rubbish in the bin.'''
    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 and observation:
        # Drawers: 'bottom', 'middle', 'top'
        # Drawer positions: 'bottom_side_pos', 'bottom_anchor_pos', etc.
        # Items: 'item1', 'item2', 'item3'
        # Bin: 'bin'
        # Gripper: 'gripper'
        # Angles: 'zero_deg', 'ninety_deg'
        # We'll use 'middle' drawer for this plan.

        # Defensive: check required keys
        required_keys = [
            'middle_side_pos', 'middle_anchor_pos', 'item3', 'bin'
        ]
        for k in required_keys:
            if k not in positions:
                raise RuntimeError(f"Required object position '{k}' not found in get_object_positions().")

        # Step 1: Move gripper to the side position of the middle drawer
        print("[Plan] Step 1: Move gripper to middle_side_pos")
        middle_side_pos = positions['middle_side_pos']
        obs, reward, done = move(
            env,
            task,
            target_pos=middle_side_pos,
            max_steps=100,
            threshold=0.01,
            timeout=10.0
        )
        if done:
            print("[Task] Task ended after move to middle_side_pos!")
            return

        # Step 2: Rotate gripper to 90 degrees (for drawer handle grasp)
        print("[Plan] Step 2: Rotate gripper to 90 degrees")
        # Assume 'ninety_deg' is a quaternion or can be mapped to one
        # If positions['ninety_deg'] is a quaternion, use it directly
        # Otherwise, construct quaternion for 90 deg rotation about z
        if 'ninety_deg' in positions:
            target_quat = positions['ninety_deg']
        else:
            # 90 deg about z axis
            from scipy.spatial.transform import Rotation as R
            target_quat = R.from_euler('z', 90, degrees=True).as_quat()
        obs, reward, done = rotate(
            env,
            task,
            target_quat=target_quat,
            max_steps=100,
            threshold=0.05,
            timeout=10.0
        )
        if done:
            print("[Task] Task ended after rotate!")
            return

        # Step 3: Move gripper to anchor position of the middle drawer (to grasp handle)
        print("[Plan] Step 3: Move gripper to middle_anchor_pos")
        middle_anchor_pos = positions['middle_anchor_pos']
        obs, reward, done = move(
            env,
            task,
            target_pos=middle_anchor_pos,
            max_steps=100,
            threshold=0.01,
            timeout=10.0
        )
        if done:
            print("[Task] Task ended after move to middle_anchor_pos!")
            return

        # Step 4: Pick the drawer handle (simulate grasp)
        print("[Plan] Step 4: Pick (close gripper) at anchor position")
        # For pick, we use the anchor position as the target
        obs, reward, done = pick(
            env,
            task,
            target_pos=middle_anchor_pos,
            approach_distance=0.10,
            max_steps=100,
            threshold=0.01,
            approach_axis='z',
            timeout=10.0
        )
        if done:
            print("[Task] Task ended after pick (drawer handle)!")
            return

        # Step 5: Pull the drawer open (pull along -x axis, e.g., 0.15m)
        print("[Plan] Step 5: Pull the drawer open")
        pull_distance = 0.15  # meters, adjust as needed for your environment
        obs, reward, done = pull(
            env,
            task,
            pull_distance=pull_distance,
            pull_axis='-x',  # Assuming -x is outwards from cabinet
            max_steps=100,
            threshold=0.01,
            timeout=10.0
        )
        if done:
            print("[Task] Task ended after pull (open drawer)!")
            return

        # Step 6: Move to the rubbish (item3) on the table
        print("[Plan] Step 6: Move gripper to item3 (rubbish)")
        item3_pos = positions['item3']
        obs, reward, done = move(
            env,
            task,
            target_pos=item3_pos,
            max_steps=100,
            threshold=0.01,
            timeout=10.0
        )
        if done:
            print("[Task] Task ended after move to item3!")
            return

        # Step 7: Pick the rubbish (item3)
        print("[Plan] Step 7: Pick item3")
        obs, reward, done = pick(
            env,
            task,
            target_pos=item3_pos,
            approach_distance=0.10,
            max_steps=100,
            threshold=0.01,
            approach_axis='z',
            timeout=10.0
        )
        if done:
            print("[Task] Task ended after pick (item3)!")
            return

        # Step 8: Move to the bin
        print("[Plan] Step 8: Move gripper to bin")
        bin_pos = positions['bin']
        obs, reward, done = move(
            env,
            task,
            target_pos=bin_pos,
            max_steps=100,
            threshold=0.01,
            timeout=10.0
        )
        if done:
            print("[Task] Task ended after move to bin!")
            return

        # Step 9: Place the rubbish in the bin
        print("[Plan] Step 9: Place item3 in bin")
        obs, reward, done = place(
            env,
            task,
            target_pos=bin_pos,
            approach_distance=0.10,
            max_steps=100,
            threshold=0.01,
            approach_axis='z',
            timeout=10.0
        )
        if done:
            print("[Task] Task completed successfully! Reward:", reward)
        else:
            print("[Task] Task not completed yet (done=False).")

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

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


if __name__ == "__main__":
    run_skeleton_task()