# run_skeleton_task.py (Fully Generic Skeleton)
#
# Description:
#  - This code is a skeleton that shows how to set up an environment, retrieve
#    object positions, and execute a plan without being tied to a specific skill
#    like pick or place.
#  - Use this as a base for creating your own task logic.
#  - The sections that are task-dependent (e.g., manipulation steps) are marked
#    with TODO or placeholders.

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

# This module is assumed to provide object positions or other info about the environment
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 ===
        # Assume get_object_positions returns a dict mapping object names to 3D positions
        positions = get_object_positions()
        # Extract positions for relevant objects and locations
        table_pos = positions['table']
        bin_pos = positions['bin']
        item1_pos = positions['item1']
        item2_pos = positions['item2']
        item3_pos = positions['item3']

        # === Oracle Plan Execution ===

        # Step 1: pick item1 from table
        print("[Task] Step 1: Picking up item1 at:", item1_pos)
        obs, reward, done = pick(
            env,
            task,
            target_pos=np.array(item1_pos),
            approach_distance=0.15,
            max_steps=100,
            threshold=0.01,
            approach_axis='z',
            timeout=10.0
        )
        if done:
            print("[Task] Terminated after picking item1. Reward:", reward)
            return

        # Step 2: place item1 into bin
        print("[Task] Step 2: Placing item1 into bin at:", bin_pos)
        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] Terminated after placing item1. Reward:", reward)
            return

        # Step 3: pick item2 from table
        print("[Task] Step 3: Picking up item2 at:", item2_pos)
        obs, reward, done = pick(
            env,
            task,
            target_pos=np.array(item2_pos),
            approach_distance=0.15,
            max_steps=100,
            threshold=0.01,
            approach_axis='z',
            timeout=10.0
        )
    [Frozen Code Start]
        obs, reward, done = pick(
                env,
                task,
                target_pos=np.array(item1_pos)
    obs, reward, done = place(
                env,
                task,
                target_pos=np.array(bin_pos)
    obs, reward, done = pick(
                env,
                task,
                target_pos=np.array(item2_pos)
    [Frozen Code End]

        # Continue plan after frozen region

        if done:
            print("[Task] Terminated after picking item2. Reward:", reward)
            return

        # Step 4: place item2 into bin
        print("[Task] Step 4: Placing item2 into bin at:", bin_pos)
        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] Terminated after placing item2. Reward:", reward)
            return

        # Step 5: pick item3 from table
        print("[Task] Step 5: Picking up item3 at:", item3_pos)
        obs, reward, done = pick(
            env,
            task,
            target_pos=np.array(item3_pos),
            approach_distance=0.15,
            max_steps=100,
            threshold=0.01,
            approach_axis='z',
            timeout=10.0
        )
        if done:
            print("[Task] Terminated after picking item3. Reward:", reward)
            return

        # Step 6: place item3 into bin
        print("[Task] Step 6: Placing item3 into bin at:", bin_pos)
        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] Terminated after placing item3. Reward:", reward)
            return

        # If all steps complete without done==True, report success
        print("[Task] All items have been moved to the bin. Final reward:", reward)

    except Exception as e:
        print("[Task] Exception during plan execution:", str(e))
        raise

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

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


if __name__ == "__main__":
    run_skeleton_task()