"""Run absolute-joint ACT chunks inside Ringfour guarded arm control.

Install ringfour, numpy, torch, and lerobot==0.4.3 in the application environment.
Use a commissioned Agent arm with trajectory control, a camera, and fresh
battery feedback. The checkpoint must include saved pre/postprocessors.

Supported checkpoint contract:
  * one RGB camera and observation.state containing only this arm's joint values;
  * state and absolute actions in the given --joints order, radians/metres;
  * no relative actions or temporal ensembling;
  * --step-duration matches the training data's action period.
Other contracts need task-specific observation/action adapters.

Example:
  python learned-policy.py --checkpoint ./act-checkpoint \
    --joints shoulder elbow wrist --image-key observation.images.base \
    --step-duration 0.1 --chunks 5

Application helpers below implement preprocessing, action decoding, sampled
self-collision checks, and a finite task limit. Sampling covers modeled robot
geometry, not obstacles or continuous collision checking. Commission trajectory
interpolation, timing, and guard thresholds for the actual hardware.

LeRobot API references:
https://github.com/huggingface/lerobot/tree/v0.4.3/src/lerobot/policies/act
https://huggingface.co/docs/lerobot/v0.4.3/en/backwardcomp
"""
import argparse
import math

import numpy as np
import torch
import torch.nn.functional as functional
from lerobot.policies.act.modeling_act import ACTPolicy
from lerobot.policies.factory import make_pre_post_processors
from ringfour import JointTrajectory, Robot
from ringfour import kinematics as kin


def sample_joint_path(arm, waypoints, samples=50):
    """Application helper sampling the linear path, including both endpoints."""
    for start, end in zip(waypoints, waypoints[1:]):
        for fraction in np.linspace(0, 1, samples + 1):
            yield arm.configuration({
                name: start.positions[name] + float(fraction) * (
                    end.positions[name] - start.positions[name]
                )
                for name in arm.joint_names
            })


def observe(camera, arm, names, image_key, image_shape, preprocessor):
    """Application adapter for this checkpoint's single-camera native-unit schema."""
    frame = camera.get_frame()
    positions = arm.get_joint_positions()
    image = torch.from_numpy(frame.image.copy()).permute(2, 0, 1).float() / 255
    if tuple(image.shape) != image_shape:
        image = functional.interpolate(
            image.unsqueeze(0), size=image_shape[1:],
            mode="bilinear", align_corners=False,
        ).squeeze(0)
    state = torch.tensor([positions[name] for name in names], dtype=torch.float32)
    # Saved processors supply batching, device placement, and normalization.
    return preprocessor({"observation.state": state, image_key: image})


def decode_actions(chunk, names, postprocessor, action_steps):
    """Application adapter undoing normalization and binding native-unit actions."""
    if chunk.ndim != 3 or chunk.shape[0] != 1 or chunk.shape[2] != len(names):
        raise ValueError("Expected one action chunk with this arm's joint count")
    for action in chunk[0, :action_steps]:
        values = postprocessor(action.unsqueeze(0)).detach().cpu().reshape(-1)
        if len(values) != len(names) or not torch.isfinite(values).all():
            raise ValueError("Invalid action vector")
        yield dict(zip(names, values.tolist()))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--robot", default="ws://127.0.0.1:10101")
    parser.add_argument("--camera", default="base")
    parser.add_argument("--arm", default="arm")
    parser.add_argument("--checkpoint", required=True)
    parser.add_argument("--joints", nargs="+", required=True)
    parser.add_argument("--image-key", default="observation.images.base")
    parser.add_argument("--step-duration", type=float, required=True)
    parser.add_argument("--chunks", type=int, default=5)
    args = parser.parse_args()
    if args.chunks <= 0:
        parser.error("Chunks must be positive")
    if not math.isfinite(args.step_duration) or args.step_duration <= 0:
        parser.error("Step duration must be positive")

    policy = ACTPolicy.from_pretrained(args.checkpoint).to("cpu")
    policy.config.device = "cpu"
    if policy.config.temporal_ensemble_coeff is not None:
        raise ValueError("This example requires a checkpoint without temporal ensembling")
    expected_inputs = {"observation.state", args.image_key}
    if set(policy.config.input_features) != expected_inputs:
        raise ValueError("Checkpoint must have observation.state and the selected camera")
    joint_count = len(args.joints)
    if tuple(policy.config.input_features["observation.state"].shape) != (joint_count,):
        raise ValueError("State features must match the supplied joint order")
    if tuple(policy.config.output_features["action"].shape) != (joint_count,):
        raise ValueError("Actions must match the supplied joint order")
    image_shape = tuple(policy.config.input_features[args.image_key].shape)
    if len(image_shape) != 3 or image_shape[0] != 3:
        raise ValueError("Expected a channel-first RGB image feature")
    preprocessor, postprocessor = make_pre_post_processors(
        policy.config,
        pretrained_path=args.checkpoint,
        preprocessor_overrides={"device_processor": {"device": "cpu"}},
    )
    policy.eval()
    policy.reset()

    with Robot(args.robot) as robot:
        camera = robot.cameras[args.camera]
        arm = robot.arms[args.arm]
        if len(set(args.joints)) != joint_count or set(args.joints) != set(arm.joint_names):
            raise ValueError("Supply each arm joint exactly once in training order")
        battery = robot.signals.battery.level
        with robot.guard(battery.below(10., max_age=1.)):
            with arm.control() as control:
                for _ in range(args.chunks):
                    observation = observe(
                        camera, arm, args.joints, args.image_key,
                        image_shape, preprocessor,
                    )
                    with torch.inference_mode():
                        chunk = policy.predict_action_chunk(observation)
                    waypoints = [arm.configuration(arm.get_joint_positions())]
                    waypoints += [
                        arm.configuration(values)
                        for values in decode_actions(
                            chunk, args.joints, postprocessor,
                            policy.config.n_action_steps,
                        )
                    ]
                    if len(waypoints) < 2:
                        raise ValueError("Policy returned no action targets")
                    for q in sample_joint_path(arm, waypoints):
                        if kin.collisions(arm, q=q):
                            raise RuntimeError("Chunk intersects the robot")
                    path = JointTrajectory.from_waypoints(
                        waypoints, step_duration=args.step_duration,
                    )
                    print(control.run(path))


if __name__ == "__main__":
    main()
