"""Detect a cup, locate it in 3D, and execute a configured wrist approach.

Install ringfour, numpy, and ultralytics>=8.3,<9 in the robot application
environment. Provide YOLO11 weights and an Agent with an RGB-D camera, arm
kinematics/collision model, and commissioned trajectory control.

Example (replace the offset/orientation with your tool's commissioned values):
  python detect-locate-move.py --offset 0 0 0.15 --quaternion 0 0 0 1

The offset is in the model root frame, in metres. Quaternion order is x y z w.
Sampling checks self-collision against modeled robot geometry. The application
must account for obstacles and validate the controller's interpolated path and
timing for its robot. This example does not close a gripper.
"""
import argparse
import math

import numpy as np
from ringfour import JointTrajectory, Pose, Quaternion, Robot
from ringfour import kinematics as kin
from ultralytics import YOLO


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


def detect_pixel(detector, image, label):
    """Application helper selecting the highest confidence matching box centre."""
    result = detector.predict(image[:, :, ::-1].copy(), verbose=False)[0]
    matches = [
        box for box in result.boxes
        if result.names[int(box.cls.item())] == label
    ]
    if not matches:
        raise ValueError(f"No detection for {label!r}")
    box = max(matches, key=lambda item: float(item.conf.item()))
    left, top, right, bottom = box.xyxy[0].tolist()
    return int((left + right) / 2), int((top + bottom) / 2)


def wrist_approach(point, offset, orientation):
    """Application helper supplying the task's root-frame tool offset and pose."""
    return Pose(
        x=point.x + offset[0],
        y=point.y + offset[1],
        z=point.z + offset[2],
        frame=point.frame,
        q=orientation,
    )


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("--weights", default="yolo11n.pt")
    parser.add_argument("--label", default="cup")
    parser.add_argument("--offset", type=float, nargs=3, required=True)
    parser.add_argument("--quaternion", type=float, nargs=4, required=True)
    parser.add_argument("--duration", type=float, default=2.0)
    args = parser.parse_args()
    if not all(math.isfinite(value) for value in args.offset + args.quaternion):
        parser.error("Offset and quaternion must be finite")
    if not math.isclose(sum(value * value for value in args.quaternion), 1, abs_tol=1e-4):
        parser.error("Quaternion must have unit length")
    if not math.isfinite(args.duration) or args.duration <= 0:
        parser.error("Duration must be positive")
    orientation = Quaternion(
        x=args.quaternion[0], y=args.quaternion[1],
        z=args.quaternion[2], w=args.quaternion[3],
    )
    detector = YOLO(args.weights)
    with Robot(args.robot) as robot:
        camera = robot.cameras[args.camera]
        arm = robot.arms[args.arm]
        frame, depth = camera.get_synced()
        pixel = detect_pixel(detector, frame.image, args.label)
        u, v = pixel
        height, width = frame.image.shape[:2]
        if not (0 <= u < width and 0 <= v < height):
            raise ValueError("Detection is outside the image")
        if depth.depth.shape != (height, width):
            raise ValueError("This adapter requires aligned RGB and depth")
        if not np.isfinite(depth.depth[v, u]) or depth.depth[v, u] <= 0:
            raise ValueError("Detection has no valid depth")
        point = camera.deproject(pixel, frame, in_frame=kin.fk(arm).frame)
        start = arm.configuration(arm.get_joint_positions())
        target = kin.ik(arm, wrist_approach(point, args.offset, orientation))
        waypoints = [start, target]
        for q in sample_joint_path(arm, waypoints):
            if kin.collisions(arm, q=q):
                raise RuntimeError("Approach intersects the robot")
        path = JointTrajectory.from_waypoints(waypoints, step_duration=args.duration)
        with arm.control() as control:
            print(control.run(path))


if __name__ == "__main__":
    main()
