from env import setup_environment, shutdown_environment
from video import init_video_writers, recording_step, recording_get_observation
from object_positions import get_object_positions
from pyrep.objects.shape import Shape
from skill_code import rotate, move, pull, pick, place
import numpy as np

def run_skeleton_task():
    print("===== Starting Skeleton Task =====")
    env, task = setup_environment()
    try:
        # Reset and prepare for recording
        descriptions, obs = task.reset()
        init_video_writers(obs)
        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()
        side_bottom_pos   = positions['bottom_side_pos']
        anchor_bottom_pos = positions['bottom_anchor_pos']
        rubbish_pos       = positions.get('item3', positions.get('rubbish'))
        bin_pos           = positions['bin']

        # Step 1: Rotate gripper to ninety_deg
        print("[Task] Step 1: Rotate gripper to ninety_deg")
        zero_frame    = Shape('zero_deg')
        ninety_frame  = Shape('ninety_deg')
        target_quat   = ninety_frame.get_quaternion()

        # === Frozen Plan Steps ===
        obs, reward, done = rotate(env, task, target_quat=target_quat)
obs, reward, done = move(env, task, target_pos=np.array(side_bottom_pos)
obs, reward, done = move(env, task, target_pos=np.array(anchor_bottom_pos)
obs, reward, done = pull(env, task, pull_distance=0.1, pull_axis='x')
        # =========================

        if done:
            print("[Task] Terminated early after opening drawer.")
            return

        # Step 5: Pick up the rubbish
        print("[Task] Step 5: Pick up rubbish")
        obs, reward, done = pick(
            env,
            task,
            target_pos=np.array(rubbish_pos),
            approach_distance=0.15,
            max_steps=100,
            threshold=0.01,
            approach_axis='z',
            timeout=10.0
        )
        if done:
            print("[Task] Terminated early after pick.")
            return

        # Step 6: Place the rubbish in the bin
        print("[Task] Step 6: Place rubbish in bin")
        obs, reward, done = place(
            env,
            task,
            target_pos=np.array(bin_pos),
            approach_distance=0.15,
            max_steps=100,
            threshold=0.01,
            approach_axis='z',
            timeout=10.0
        )
        if done:
            print("[Task] Completed after place. Reward:", reward)
        else:
            print("[Task] Plan executed but task not marked done. Reward:", reward)

    except Exception as e:
        print(f"[Task] Exception occurred: {e}")
    finally:
        shutdown_environment(env)

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

if __name__ == "__main__":
    run_skeleton_task()