"""Reference controller for the Inside AI two-button lab. Requires adb, ollama and pyserial."""
import argparse
import base64
from contextlib import closing
import json
import math
from pathlib import Path
import subprocess
import time
import urllib.request


def capture(device):
    data = subprocess.check_output(
        ["adb", "-s", device, "exec-out", "screencap", "-p"], timeout=15
    )
    if not data.startswith(b"\x89PNG\r\n\x1a\n"):
        raise ValueError("Expected a PNG from the selected Android device")
    return data


def inspect_frame(png, label):
    prompt = (
        f"Read the Android button test. Locate the button labeled {label}, ignoring status text. "
        "Return JSON: title (page heading), round (integer), status (exact visible result text), "
        "label (target button text), box [left,top,right,bottom], dot [x,y] (outlined mouse marker). "
        "Use full-image coordinates 0 to 1000. Use null for anything missing or ambiguous."
    )
    payload = {
        "model": "qwen3-vl:8b", "stream": False, "format": "json",
        "options": {"temperature": 0},
        "messages": [{"role": "user", "content": prompt,
                      "images": [base64.b64encode(png).decode("ascii")]}],
    }
    request = urllib.request.Request(
        "http://127.0.0.1:11434/api/chat", data=json.dumps(payload).encode(),
        headers={"Content-Type": "application/json"},
    )
    with urllib.request.urlopen(request, timeout=120) as response:
        return json.loads(json.load(response)["message"]["content"])


def coords(value, size):
    if not isinstance(value, list) or len(value) != size or not all(
        type(n) in (int, float) and math.isfinite(n) and 0 <= n <= 1000 for n in value
    ):
        raise ValueError("Missing or invalid target box or pointer marker")
    return value


def choose_action(reading, label, round_number, width, height):
    if (reading.get("title") != "Android button test" or reading.get("round") != round_number
            or reading.get("label") != label or reading.get("status") != "Waiting for a click."):
        raise ValueError("Page, round, target or starting state could not be confirmed")
    left, top, right, bottom = coords(reading.get("box"), 4)
    x, y = coords(reading.get("dot"), 2)
    if left >= right or top >= bottom:
        raise ValueError("Inverted or empty box")
    dx, dy = (left + right) / 2 - x, (top + bottom) / 2 - y
    if abs(dx) <= (right-left)/4 and abs(dy) <= (bottom-top)/4:
        return b"q"
    if abs(dx) * width >= abs(dy) * height:
        return b"d" if dx > 0 else b"a"
    return b"s" if dy > 0 else b"w"


def run():
    import serial
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--device", required=True, help="Android serial from adb devices")
    parser.add_argument("--port", required=True, help="ESP32 USB-to-UART port")
    parser.add_argument("--round", required=True, type=int)
    parser.add_argument("--label", choices=["Amber", "Violet"], required=True)
    parser.add_argument("--output", type=Path, required=True, help="New trial directory")
    args = parser.parse_args()
    args.output.mkdir(parents=True, exist_ok=False)
    # Set control lines before opening the port to avoid an intentional board reset.
    with closing(serial.Serial(port=None, baudrate=115200, write_timeout=2)) as board:
        board.dtr = board.rts = False
        board.port = args.port
        board.open()
        for step in range(21):
            png = capture(args.device)
            (args.output / f"frame-{step:02}.png").write_bytes(png)
            reading = inspect_frame(png, args.label)
            (args.output / f"reading-{step:02}.json").write_text(json.dumps(reading, indent=2))
            width = int.from_bytes(png[16:20], "big")
            height = int.from_bytes(png[20:24], "big")
            action = choose_action(reading, args.label, args.round, width, height)
            if step == 20 and action != b"q":
                raise ValueError("Move budget exhausted")
            board.write(action)
            board.flush()
            time.sleep(0.4)
            if action == b"q":
                after = capture(args.device)
                (args.output / "after.png").write_bytes(after)
                result = inspect_frame(after, args.label)
                expected = f"Round {args.round} · Clicked {args.label}"
                print("Model readback:", result.get("status"))
                if result.get("round") != args.round or result.get("status") != expected:
                    raise ValueError("Inconclusive click; inspect after.png before another trial")
                print("Check after.png against:", expected)
                return


if __name__ == "__main__":
    run()
