from env import setup_environment, shutdown_environment
import numpy as np
from pyrep.objects.shape import Shape
from pyrep.objects.proximity_sensor import ProximitySensor
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():
    print("===== Starting Skeleton Task =====")
    env, task = setup_environment()
    try:
        descriptions, obs = task.reset()
        init_video_writers(obs)
        # wrap step and get_observation 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()
        side_pos_bottom   = positions['side-pos-bottom']
        anchor_pos_bottom = positions['anchor-pos-bottom']
        tomato1_pos       = positions['tomato1']
        tomato2_pos       = positions['tomato2']
        plate_pos         = positions['plate']
        # compute target orientation for rotate
        current_obs = task.get_observation()
        current_quat = normalize_quaternion(current_obs.gripper_pose[3:7])
        target_quat = current_quat

        # === Execute Oracle Plan ===
        # (The following lines are a frozen region and must remain unchanged)
        # [Frozen Code Start]
        obs, reward, done = move(env, task, side_pos_bottom)
        obs, reward, done = rotate(env, task, target_quat)
        obs, reward, done = move(env, task, anchor_pos_bottom)
        obs, reward, done = pull(env, task, pull_distance=0.1, pull_axis='x')
        obs, reward, done = move(env, task, tomato1_pos)
        obs, reward, done = pick(env, task, tomato1_pos)
        obs, reward, done = move(env, task, plate_pos)
        obs, reward, done = place(env, task, plate_pos)
        # [Frozen Code End]

        if done:
            print("[Task] Early termination after first tomato.")
            return

        # pick and place second tomato
        print("[Task] Moving to tomato2 at:", tomato2_pos)
        obs, reward, done = move(env, task, tomato2_pos)
        if done:
            print("[Task] Early termination after move to tomato2.")
            return

        print("[Task] Picking tomato2")
        obs, reward, done = pick(env, task, tomato2_pos)
        if done:
            print("[Task] Early termination after picking tomato2.")
            return

        print("[Task] Moving to plate at:", plate_pos)
        obs, reward, done = move(env, task, plate_pos)
        if done:
            print("[Task] Early termination after move to plate second time.")
            return

        print("[Task] Placing tomato2 on plate")
        obs, reward, done = place(env, task, plate_pos)
        if done:
            print("[Task] Early termination after placing tomato2.")
            return

        print("[Task] Completed all plan steps. Final reward:", reward)

    except Exception as e:
        print(f"[Task] Exception encountered: {e}")
    finally:
        shutdown_environment(env)
    print("===== End of Skeleton Task =====")

if __name__ == "__main__":
    run_skeleton_task()