"""Ground a Gemma image-space answer in map coordinates.

Install ringfour, numpy, pillow, and ollama in the application environment.
Run Ollama >=0.6 and fetch the model with: ollama pull gemma3:4b
The Agent profile must provide an RGB-D camera with aligned depth, intrinsics,
and a camera-to-map transform. Set frame_ttl to cover inference latency.

Run: python visual-grounding.py --robot ws://127.0.0.1:10101

The returned point locates the model's chosen pixel. Check semantic accuracy
for your task. This example only reads sensors and prints map coordinates.
"""
import argparse
from io import BytesIO
import json
import math

import numpy as np
from ollama import chat
from PIL import Image
from ringfour import Robot


def image_to_jpeg(image):
    """Application helper encoding the RGB array as JPEG bytes for Ollama."""
    buffer = BytesIO()
    Image.fromarray(image).save(buffer, format="JPEG")
    return buffer.getvalue()


def parse_pixel(content, image, depth):
    """Application helper validating JSON, integer image coordinates, and depth."""
    pixel = json.loads(content)
    if not isinstance(pixel, dict) or set(pixel) != {"x", "y"}:
        raise ValueError("Expected a JSON object containing only x and y")
    if type(pixel["x"]) is not int or type(pixel["y"]) is not int:
        raise ValueError("Pixel coordinates must be integers")
    u, v = pixel["x"], pixel["y"]
    height, width = image.shape[:2]
    if not (0 <= u < width and 0 <= v < height):
        raise ValueError("Model coordinates are outside the original image")
    if depth.shape != (height, width):
        raise ValueError("This adapter requires aligned RGB and depth")
    distance = float(depth[v, u])
    if not math.isfinite(distance) or distance <= 0:
        raise ValueError("The chosen pixel has no valid depth")
    return u, v


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("--model", default="gemma3:4b")
    args = parser.parse_args()
    with Robot(args.robot) as robot:
        camera = robot.cameras[args.camera]
        frame, depth = camera.get_synced()
        reply = chat(model=args.model, format="json", messages=[{
            "role": "user",
            "content": 'Find the door centre. Return {"x": int, "y": int} in pixels.',
            "images": [image_to_jpeg(frame.image)],
        }])
        if not reply.message.content:
            raise ValueError("Model returned an empty response")
        pixel = parse_pixel(reply.message.content, frame.image, depth.depth)
        door = camera.deproject(pixel, frame, in_frame="@map")
        if not all(np.isfinite(value) for value in (door.x, door.y, door.z)):
            raise ValueError("Deprojection returned invalid map coordinates")
        print(door)


if __name__ == "__main__":
    main()
