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 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
        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()
        # Assumed keys in positions dict:
        # 'bottom_side_pos', 'bottom_anchor_pos', 'item1', 'item2', 'plate'

        # === Oracle Plan Execution ===
        # 1) Rotate gripper to 90 degrees about Z axis for handle alignment
        print("[Plan] Step 1: rotate gripper to ninety_deg orientation")
        # quaternion for 90° about Z: [x, y, z, w]
        target_quat = np.array([0.0, 0.0, np.sin(np.pi/4), np.cos(np.pi/4)])
        obs, reward, done = rotate(env, task, target_quat)
        if done:
            print("[Plan] Task ended after rotate. Reward:", reward)
            return

        # 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, side_pos)
        if done:
            print("[Plan] Task ended after move to side. Reward:", reward)
            return

        # 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, anchor_pos)
        if done:
            print("[Plan] Task ended after move to anchor. Reward:", reward)
            return

        # 4) Pull drawer open
        print("[Plan] Step 4: pull drawer open")
        # pull distance and axis may need tuning; assume x-axis pull
        obs, reward, done = pull(env, task, pull_distance=0.1, pull_axis='x')
        if done:
            print("[Plan] Task ended after pull. Reward:", reward)
            return

        # 5) Move to first tomato (item1)
        print("[Plan] Step 5: move to item1")
        item1_pos = positions['item1']
        obs, reward, done = move(env, task, item1_pos)
        if done:
            print("[Plan] Task ended after move to item1. Reward:", reward)
            return

        # 6) Pick up tomato1
        print("[Plan] Step 6: pick item1")
        obs, reward, done = pick(env, task, target_pos=item1_pos)
        if done:
            print("[Plan] Task ended after pick item1. Reward:", reward)
            return

        # 7) Move to plate
        print("[Plan] Step 7: move to plate")
        plate_pos = positions['plate']
        obs, reward, done = move(env, task, plate_pos)
        if done:
            print("[Plan] Task ended after move to plate. Reward:", reward)
            return

        # 8) Place tomato1 on plate
        print("[Plan] Step 8: place item1 on plate")
        obs, reward, done = place(env, task, target_pos=plate_pos)
        if done:
            print("[Plan] Task ended after place item1. Reward:", reward)
            return

        # 9) Move to second tomato (item2)
        print("[Plan] Step 9: move to item2")
        item2_pos = positions['item2']
        obs, reward, done = move(env, task, item2_pos)
        if done:
            print("[Plan] Task ended after move to item2. Reward:", reward)
            return

        # 10) Pick up tomato2
        print("[Plan] Step 10: pick item2")
        obs, reward, done = pick(env, task, target_pos=item2_pos)
        if done:
            print("[Plan] Task ended after pick item2. Reward:", reward)
            return

        # 11) Move to plate again
        print("[Plan] Step 11: move to plate for item2")
        obs, reward, done = move(env, task, plate_pos)
        if done:
            print("[Plan] Task ended after second move to plate. Reward:", reward)
            return

        # 12) Place tomato2 on plate
        print("[Plan] Step 12: place item2 on plate")
        obs, reward, done = place(env, task, target_pos=plate_pos)
        if done:
            print("[Plan] Task ended after place item2. Reward:", reward)
            return

        # === Plan Finished ===
        if not done:
            print("[Plan] Completed all steps. Final reward:", reward)
        else:
            print("[Plan] Task reported done status at end. Reward:", reward)

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

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


if __name__ == "__main__":
    run_skeleton_task()