import numpy as np
from env import setup_environment, shutdown_environment
from skill_code import 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()

        # Plan: pull open any drawer that is not locked.
        # We iterate through known drawers in order: bottom, middle, top.
        drawers = ['bottom', 'middle', 'top']
        for drawer in drawers:
            side_key = f"{drawer}_side_pos"
            anchor_key = f"{drawer}_anchor_pos"
            if side_key not in positions or anchor_key not in positions:
                print(f"[Task] Missing position info for '{drawer}' drawer, skipping.")
                continue
            side_pos = np.array(positions[side_key])
            anchor_pos = np.array(positions[anchor_key])
            print(f"[Task] Attempting to open '{drawer}' drawer")

            try:
                # Step 1: rotate gripper (noop rotation to satisfy precondition)
                print("[Task] Step 1: rotate gripper to current orientation")
                obs = task.get_observation()
                quat = obs.gripper_pose[3:7]
                quat = quat / np.linalg.norm(quat)
                obs, reward, done = rotate(env, task, quat)
                if done:
                    print("[Task] Environment signaled done after rotate")
                    break

                # Step 2: move to side position
                print(f"[Task] Step 2: move to side position {side_pos}")
                obs, reward, done = move(env, task, side_pos)
                if done:
                    print("[Task] Environment signaled done after move-to-side")
                    break

                # Step 3: move to anchor position
                print(f"[Task] Step 3: move to anchor position {anchor_pos}")
                obs, reward, done = move(env, task, anchor_pos)
                if done:
                    print("[Task] Environment signaled done after move-to-anchor")
                    break

                # Step 4: pick the drawer handle
                print(f"[Task] Step 4: pick at anchor position {anchor_pos}")
                obs, reward, done = pick(env, task, anchor_pos)
                if done:
                    print("[Task] Environment signaled done after pick")
                    break

                # Step 5: pull to open the drawer
                print("[Task] Step 5: pull to open drawer")
                obs, reward, done = pull(env, task, pull_distance=0.1, pull_axis='x')
                if done:
                    print("[Task] Environment signaled done after pull")
                print(f"[Task] Successfully opened '{drawer}' drawer.")
                
                # Goal achieved for one drawer; exit loop
                break

            except Exception as e:
                print(f"[Task] Failed to open '{drawer}' drawer: {e}")
                continue

        print("[Task] Plan execution completed.")

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

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

if __name__ == "__main__":
    run_skeleton_task()