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 (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()

        # Helper to map PDDL names like 'side-pos-bottom' to keys like 'bottom_side_pos'
        def pddl_to_key(name):
            parts = name.split('-')
            if len(parts) == 3:
                a, b, c = parts
                return f"{c}_{a}_{b}"
            return name.replace('-', '_')

        # === Execute Oracle Plan ===

        # Step 1: Rotate gripper from zero_deg to ninety_deg
        try:
            shape_ninety = Shape('ninety_deg')
            ninety_quat = normalize_quaternion(shape_ninety.get_quaternion())
            obs, reward, done = rotate(env, task, ninety_quat)
            if done:
                print("[Task] Terminated during rotate.")
                return
        except Exception as e:
            print("[Error] rotate:", e)
            return

        # Step 2: Move to side-pos-bottom
        try:
            key = pddl_to_key('side-pos-bottom')
            target_pos = positions[key]
            obs, reward, done = move(env, task, np.array(target_pos))
            if done:
                print("[Task] Terminated during move to side-pos-bottom.")
                return
        except Exception as e:
            print("[Error] move to side-pos-bottom:", e)
            return

        # Step 3: Move to anchor-pos-bottom
        try:
            key = pddl_to_key('anchor-pos-bottom')
            target_pos = positions[key]
            obs, reward, done = move(env, task, np.array(target_pos))
            if done:
                print("[Task] Terminated during move to anchor-pos-bottom.")
                return
        except Exception as e:
            print("[Error] move to anchor-pos-bottom:", e)
            return

        # Step 4: Pick the bottom drawer handle
        try:
            # We already have target_pos = anchor-pos-bottom
            obs, reward, done = pick(env, task, np.array(target_pos))
            if done:
                print("[Task] Terminated during pick-drawer.")
                return
        except Exception as e:
            print("[Error] pick-drawer:", e)
            return

        # Step 5: Pull the bottom drawer
        try:
            pull_distance = 0.1  # adjust as needed
            obs, reward, done = pull(env, task, pull_distance)
            if done:
                print("[Task] Terminated during pull.")
                return
        except Exception as e:
            print("[Error] pull:", e)
            return

        # Step 6: Pick up the rubbish
        try:
            # Determine which key refers to the trash object
            if 'rubbish' in positions:
                trash_key = 'rubbish'
            elif 'item3' in positions:
                trash_key = 'item3'
            else:
                raise KeyError("Trash object not found")
            target_pos = positions[trash_key]
            obs, reward, done = pick(env, task, np.array(target_pos))
            if done:
                print("[Task] Terminated during pick-trash.")
                return
        except Exception as e:
            print("[Error] pick-trash:", e)
            return

        # Step 7: Place the rubbish into the bin
        try:
            if 'bin' not in positions:
                raise KeyError("Bin not found")
            target_pos = positions['bin']
            obs, reward, done = place(env, task, np.array(target_pos))
            if done:
                print("[Task] Terminated during place-trash.")
                return
            print("[Task] Completed successfully. Reward:", reward)
        except Exception as e:
            print("[Error] place-trash:", e)
            return

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

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


if __name__ == "__main__":
    run_skeleton_task()