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
import numpy as np
from scipy.spatial.transform import Rotation as R

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)
        task.step = recording_step(task.step)
        task.get_observation = recording_get_observation(task.get_observation)

        # === Retrieve Object Positions ===
        positions = get_object_positions()
        # Map PDDL objects to positions in the simulation
        bottom_side_pos = positions.get('bottom_side_pos')
        bottom_anchor_pos = positions.get('bottom_anchor_pos')
        item3_pos = positions.get('item3')
        bin_pos = positions.get('bin')

        # === Execute Oracle Plan ===

        # Step 1: Rotate gripper from zero_deg to ninety_deg
        print("[Task] Rotating gripper to 90 degrees around y-axis")
        target_quat = R.from_euler('y', 90, degrees=True).as_quat()
[Frozen Code Start]
        obs, reward, done = rotate(env, task, target_quat)
        obs, reward, done = move(env, task, np.array(bottom_side_pos)
        obs, reward, done = move(env, task, np.array(bottom_anchor_pos)
        obs, reward, done = pull(env, task, pull_distance=0.2, pull_axis='x')
[Frozen Code End]

        # Step 5: Pick up the rubbish (item3) from the table
        print(f"[Task] Picking up rubbish at: {item3_pos}")
        obs, reward, done = pick(env, task, np.array(item3_pos))
        if done:
            print("[Task] Finished early during pick.")
            return

        # Step 6: Move gripper to the trash bin
        print(f"[Task] Moving gripper to bin at: {bin_pos}")
        obs, reward, done = move(env, task, np.array(bin_pos))
        if done:
            print("[Task] Finished early during move to bin.")
            return

        # Step 7: Place the rubbish into the trash bin
        print("[Task] Placing rubbish into bin")
        obs, reward, done = place(env, task, np.array(bin_pos))
        if done:
            print("[Task] Finished after place. Reward:", reward)
        else:
            print("[Task] Task not completed, done flag is False. Reward:", reward)

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

if __name__ == "__main__":
    run_skeleton_task()