"""Glue between the GUI and the team's code. Written by Claude (AI) for Andrin Schmid.

The team's files in ../team are imported exactly as they are; nothing in them is changed:
  * planning: svg_input, geometry, colors, toolpath, pipeline, preview (Aaron Zeng),
    motion, config, ufp_driver (Aaron Zeng, reconciled with the firmware by Tudor Mocioi)
  * hardware: xy_stage_wrapper, single_stepper_wrapper, syringe_wrapper, xy_geometry,
    simulated_* (Tudor Mocioi), board discovery idea from find_devices.py (Hector Astrom)
  * the boards speak UFP (Quentin Bolsee, ../third_party/ufp)

Homing is Tudor's XYStage.home() (17 Nov, tested on the machine): +X until a switch closes,
that is x = x_max; back to x = x_min; -Y until a switch closes, that is y = y_min.

What this file adds:
  * PANCAKE_FIRMWARE_DIR points at team/firmware/scripts. firmware_link.py looks in
    team/firmware, but the wrappers live in team/firmware/scripts, so without this nothing imports.
  * separate coil currents for the gantry and the syringes (the team's open_machine uses one)
  * x_home_pos passed to XYStage = the box's x max (ufp_driver leaves Tudor's default 500 mm, which
    breaks every box narrower than 500 mm), STOP that also ends a running homing
  * syringe strokes that run while the gantry moves again (see AppMachine)
  * "manual" homing: declare where the gantry stands instead of driving to switches
  * USB scan that works on Windows COM ports (find_devices.py only matches "usbmodem", macOS)
  * jogging, syringe purge / zero, XY calibration, stop flag for the GUI
"""
from __future__ import annotations

import copy
import math
import os
import sys
import threading
import time
import types
from dataclasses import dataclass, field
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
APP = ROOT / "app"
TEAM_SW = ROOT / "team" / "software" / "scripts"
TEAM_FW = ROOT / "team" / "firmware" / "scripts"
UFP_PY = ROOT / "third_party" / "ufp" / "Python"   # Quentin's ufp library, used in place (not pip installed)
CONFIG_PATH = APP / "pancake_config.yaml"
OUT_DIR = ROOT / "out"

os.environ.setdefault("PANCAKE_FIRMWARE_DIR", str(TEAM_FW))
sys.dont_write_bytecode = True   # keep team/ and third_party/ exactly as downloaded (no __pycache__)
for p in (APP, UFP_PY, TEAM_FW, TEAM_SW):
    if str(p) not in sys.path:
        sys.path.insert(0, str(p))

import yaml  # noqa: E402

from config import MachineConfig, config_from_dict  # noqa: E402  (Aaron, Tudor)
from motion import Extrude, Pause, Prime, Retract, Wait, XYMove, motion_stats, plan_motor_moves  # noqa: E402
from motion_profile import trapezoid_time  # noqa: E402  (Tudor)
from pipeline import svg_to_job  # noqa: E402  (Aaron)
from preview import trace  # noqa: E402  (Aaron)
import ufp_driver  # noqa: E402  (Aaron, Tudor)
from xy_geometry import ab_to_xy, xy_to_ab  # noqa: E402  (Tudor)

HOMING_MODES = ("tudor", "switches", "manual")

import estimates  # noqa: E402


class Aborted(Exception):
    """Raised inside a run when STOP was pressed."""


class HomingFailed(RuntimeError):
    """A limit switch was not found, or answered on an unexpected board."""


# --------------------------------------------------------------------------- config


CONFIG_VERSION = 3   # 3: softer motion (18 Nov) and Hector's syringe speed / acceleration


def load_raw(path: Path = CONFIG_PATH) -> dict:
    raw = yaml.safe_load(Path(path).read_text(encoding="utf-8"))
    a = raw.setdefault("app", {})
    if int(a.get("config_version", 0)) < CONFIG_VERSION:
        # settings from an older version of this app (or written by a window that was still open
        # during an update): bring the motion values to the current defaults once
        u, pr = raw.get("ufp") or {}, raw.get("print") or {}
        if u:
            u["plunger_speed"], u["plunger_accel"] = 200, 1000          # Hector's values
            u["accel"] = min(float(u.get("accel", 100.0)), 100.0)
            u["emergency_decel"] = min(float(u.get("emergency_decel", 1000.0)), 1000.0)
        if pr:
            pr["travel_speed"] = min(float(pr.get("travel_speed", 30.0)), 30.0)
        a["config_version"] = CONFIG_VERSION
    if raw.get("ufp") and ("travel_a" in raw["ufp"] or "travel_b" in raw["ufp"]):
        # config from before 17 Nov: Tudor replaced travel_a / travel_b by the x / y box and homes
        # +X then -Y. Convert once (the file is rewritten at the next Save).
        fit_workspace(raw)
        app_settings(raw)["homing"] = "tudor"
    return raw


def save_raw(raw: dict, path: Path = CONFIG_PATH) -> None:
    build_config(raw)  # validate with the team's loader first
    Path(path).write_text(yaml.safe_dump(raw, sort_keys=False, allow_unicode=True), encoding="utf-8")


def build_config(raw: dict) -> MachineConfig:
    """The team's config loader (config.py) on our YAML; it ignores the 'app' section."""
    team_part = {k: copy.deepcopy(v) for k, v in raw.items() if k != "app"}
    return config_from_dict(team_part)


def app_settings(raw: dict) -> dict:
    return raw.setdefault("app", {})


# Highest current that really works. The board firmware (ufp_stepper/stepperDriver.cpp,
# stepper_point) keeps only 10 bits of the amplitude: 1.0 -> 1024 -> 1024 & 0x3FF = 0, so at
# exactly 1.0 the coils get NO current and nothing moves. 0.99 -> 1013 (Hector runs 0.99).
MAX_CURRENT = 0.99


def safe_current(c: float) -> float:
    return max(0.0, min(float(c), MAX_CURRENT))


def currents(raw: dict) -> tuple[float, float]:
    a = app_settings(raw)
    xy, pl = float(a.get("xy_current", MAX_CURRENT)), float(a.get("plunger_current", MAX_CURRENT))
    if a.get("usb_power_only", False):
        xy, pl = min(xy, 0.2), min(pl, 0.2)
    return safe_current(xy), safe_current(pl)


MOTORS = ("a", "b", "e0", "e1", "e2")


def motor_currents(raw: dict) -> dict:
    """Current of every motor (app.motor_currents {a, b, e0, e1, e2}); missing ones fall back to
    app.xy_current (a, b) and app.plunger_current (syringes). Capped at 0.99 (see MAX_CURRENT)."""
    xy, pl = currents(raw)
    a = app_settings(raw)
    per = a.get("motor_currents") or {}
    out = {}
    for m in MOTORS:
        c = float(per.get(m, xy if m in ("a", "b") else pl))
        if a.get("usb_power_only", False):
            c = min(c, 0.2)
        out[m] = safe_current(c)
    return out


def syringe_inputs(raw: dict) -> estimates.SyringeInputs:
    s = app_settings(raw).get("syringe", {})
    photo = app_settings(raw).get("photo", {})
    return estimates.SyringeInputs(
        lead_mm_per_turn=float(s.get("lead_mm_per_turn", 8.0)),
        ml_per_cm=float(s.get("ml_per_cm", 15.81)),
        syringe_ml=float(s.get("syringe_ml", 150.0)),
        usable_fraction=float(s.get("usable_fraction", 0.9)),
        line_width_mm=float(raw["print"]["line_width"]),
        line_height_mm=float(photo.get("line_height_mm", 1.5)))


# --------------------------------------------------------------------------- design -> plan


def convert_photo(image_path, raw: dict, out_dir: Path = OUT_DIR):
    """Photo -> 3 colour SVG with image_to_pancake.py. Bead = print.line_width, batter colours =
    nozzle colours, so the team's colors.py maps every colour to its own syringe exactly."""
    import image_to_pancake as ip
    ph = app_settings(raw).get("photo", {})
    noz = sorted(raw["nozzles"], key=lambda n: n["id"])
    args = ip.build_parser().parse_args([str(image_path), "-o", str(out_dir)])
    args.width = float(ph.get("width_mm", 100))
    args.shape = ph.get("shape", "rect")
    args.style = ph.get("style", "lineart")
    args.background = ph.get("background", "remove")
    args.match = ph.get("match", "lightness")
    args.min_feature = float(ph.get("min_feature_mm", 3.0))
    args.bead_height = float(ph.get("line_height_mm", 1.5))
    args.bead = float(raw["print"]["line_width"])
    args.speed = float(raw["print"]["print_speed"])
    args.batter = ",".join(n["color"] for n in noz[:3])
    args.order = ",".join(str(i) for i in raw["print"].get("color_order", [0, 1, 2]))
    args.syringe_mm3_per_mm = float(app_settings(raw).get("syringe", {}).get("ml_per_cm", 15.81)) * 100
    out_dir.mkdir(parents=True, exist_ok=True)
    svg, layers, stats = ip.make_pancake(args)
    return Path(svg), out_dir / f"{Path(image_path).stem}_preview.png", stats


@dataclass
class Plan:
    svg: Path
    cfg: MachineConfig
    job: object                      # pipeline.Job
    steps: list
    strokes: list                    # (nozzle, (N,2) array) from preview.trace
    travels: list
    summary: dict = field(default_factory=dict)


def homing_mode(raw: dict) -> str:
    m = str(app_settings(raw).get("homing", "tudor")).lower()
    return m if m in HOMING_MODES else "tudor"


def park_point(raw: dict):
    """Where a print ends. With Tudor's homing that is the homed corner (ufp.home_offset), as in the
    team's motion.py."""
    a = app_settings(raw)
    mode = homing_mode(raw)
    if mode == "tudor":
        return tuple(float(v) for v in raw["ufp"]["home_offset"])
    if mode == "manual":
        return tuple(a.get("manual_origin", [0.0, 0.0]))
    sw = a.get("switches", {})
    back = 2 * float(sw.get("backoff_mm", 3.0))
    x = float(sw["x"]["position"]) - _sign(sw["x"]["toward"]) * back
    y = float(sw["y"]["position"]) - _sign(sw["y"]["toward"]) * back
    return x, y


def _sign(toward: str) -> int:
    return -1 if str(toward).strip().startswith("-") else 1


def speed_pct(raw: dict) -> float:
    return max(5.0, float(app_settings(raw).get("speed_pct", 100)))


def speed_scaled(raw: dict) -> dict:
    """Copy of the settings with print and travel speed times app.speed_pct / 100 (overall speed)."""
    raw = copy.deepcopy(raw)
    f = speed_pct(raw) / 100.0
    pr = raw["print"]
    pr["print_speed"] = round(float(pr["print_speed"]) * f, 3)
    pr["travel_speed"] = round(float(pr["travel_speed"]) * f, 3)
    return raw


def only_syringe(raw: dict, n: int) -> dict:
    """Copy of the settings with only nozzle / syringe n: Aaron's colors.py then maps EVERY colour of
    the design to it (one colour print with whichever syringe is mounted)."""
    raw = copy.deepcopy(raw)
    raw["nozzles"] = [z for z in raw["nozzles"] if int(z["id"]) == n]
    if not raw["nozzles"]:
        raise ValueError(f"there is no nozzle {n} in the settings")
    raw["print"]["color_order"] = [n]
    raw["ufp"]["plungers"] = {k: v for k, v in raw["ufp"]["plungers"].items() if int(k) == n}
    return raw


def plan_design(svg_path, raw: dict, park_at=None, syringe=None) -> Plan:
    """SVG -> events (pipeline.py) -> motor steps (motion.py). park_at: replace the final park move
    to the switch corner (cfg.home) with this machine point (used with manual homing).
    Print and travel speed are scaled by the overall speed (app.speed_pct); the syringe flow follows,
    because Aaron's motion.py times every stroke from its length and speed."""
    if syringe is not None:
        raw = only_syringe(raw, int(syringe))
    raw = speed_scaled(raw)
    cfg = build_config(raw)
    job = svg_to_job(str(svg_path), cfg)
    steps = plan_motor_moves(job.events, cfg)
    if park_at is not None and steps and isinstance(steps[-1], XYMove):
        last = steps[-1]
        prev = next((s for s in reversed(steps[:-1]) if isinstance(s, XYMove)), None)
        x0, y0 = (prev.x, prev.y) if prev else cfg.home
        d = math.hypot(park_at[0] - x0, park_at[1] - y0)
        steps[-1] = XYMove(float(park_at[0]), float(park_at[1]), last.v, last.a,
                           trapezoid_time(d, last.v, last.a) if d > 0 else 0.0)
    flow = app_settings(raw).get("flow") or {}          # per syringe flow factor (Setup step 8, flow test)
    carry = {}
    for st in steps:
        if isinstance(st, Extrude):
            want = st.steps * float(flow.get(int(st.motor[1:]), 1.0)) + carry.get(st.motor, 0.0)
            # whole steps only: Hector found that fractional targets leave the motor in a weak
            # "half hold" (commit 99f2489a73). The remainder is carried to the next stroke.
            st.steps = float(round(want))
            carry[st.motor] = want - st.steps
    strokes, travels = trace(job.events, cfg)
    m = motion_stats(steps)
    est = estimates.syringe_estimates(syringe_inputs(raw))
    per = {}
    for s in steps:
        if isinstance(s, Extrude):
            per[s.motor] = per.get(s.motor, 0.0) + s.steps
    summary = {
        "strokes": job.stats["strokes"],
        "print_mm": job.stats["print_length"],
        "travel_mm": job.stats["travel_length"],
        "by_nozzle_mm": dict(job.stats["print_length_by_nozzle"]),
        "color_map": dict(job.color_map),
        "moves": m["moves"],
        "time_s": m["time"],
        "pauses": m["pauses"],
        "plunger_steps": per,
        "batter_ml": {k: v * est["ml_per_step"] for k, v in per.items()},
        "plunger_mm": {k: v * est["plunger_mm_per_step"] for k, v in per.items()},
        "motors": m["motors"],
    }
    return Plan(Path(svg_path), cfg, job, steps, strokes, travels, summary)


def make_square_svg(size_mm: float, color: str, out_dir: Path = OUT_DIR) -> Path:
    """Print test: one square outline of `size_mm` in the batter colour of one syringe. It goes through
    the same pipeline as a picture (SVG -> Aaron's pipeline -> motor steps)."""
    out_dir.mkdir(parents=True, exist_ok=True)
    m, size = 5.0, float(size_mm)
    w = size + 2 * m
    path = out_dir / f"test_square_{size:g}mm.svg"
    path.write_text(f'<svg xmlns="http://www.w3.org/2000/svg" width="{w:g}mm" height="{w:g}mm" '
                    f'viewBox="0 0 {w:g} {w:g}">\n  <rect x="{m:g}" y="{m:g}" width="{size:g}" height="{size:g}" '
                    f'stroke="{color}" fill="none"/>\n</svg>\n', encoding="utf-8")
    return path


def make_offset_test_svg(raw: dict, outer: float = 50.0, gap: float = 5.0, out_dir: Path = OUT_DIR) -> Path:
    """Nozzle offset test: three squares around the same centre, one per syringe (0 outside, 1 in the
    middle, 2 inside), `gap` mm apart. With correct nozzle offsets all gaps are equal. Measured from the
    outer square (syringe 0): x error = (left gap - right gap) / 2, y error = (front gap - back gap) / 2;
    add the error to that syringe's offset (gantry = bed - offset, so a too small offset shifts its
    square to +x / +y)."""
    out_dir.mkdir(parents=True, exist_ok=True)
    noz = sorted(raw["nozzles"], key=lambda n: int(n["id"]))[:3]
    m = 5.0
    w = outer + 2 * m
    c = w / 2
    rects = []
    for i, n in enumerate(noz):
        size = outer - 2 * gap * i
        rects.append(f'  <rect x="{c - size / 2:g}" y="{c - size / 2:g}" width="{size:g}" height="{size:g}" '
                     f'stroke="{n["color"]}" fill="none"/>  <!-- syringe {n["id"]} -->')
    path = out_dir / f"offset_test_{outer:g}mm.svg"
    path.write_text(f'<svg xmlns="http://www.w3.org/2000/svg" width="{w:g}mm" height="{w:g}mm" viewBox="0 0 {w:g} {w:g}">\n'
                    + "\n".join(rects) + "\n</svg>\n", encoding="utf-8")
    return path


def first_nozzle(plan: "Plan") -> int:
    """Nozzle (= syringe number) of the first stroke of a plan."""
    for st in plan.steps:
        if isinstance(st, Extrude):
            return int(st.motor[1:])
    return 0


def here_point(plan: "Plan") -> tuple[float, float]:
    """Gantry position at which the nozzle of the first colour is over the middle of the design."""
    cfg = plan.cfg
    pts = [s for _, s in plan.strokes]
    if pts:
        import numpy as np
        allp = np.vstack(pts)
        cx, cy = (allp[:, 0].min() + allp[:, 0].max()) / 2, (allp[:, 1].min() + allp[:, 1].max()) / 2
    else:
        pa = cfg.print_area
        cx, cy = (pa.x_min + pa.x_max) / 2, (pa.y_min + pa.y_max) / 2
    return cfg.to_machine(first_nozzle(plan), float(cx), float(cy))


# --------------------------------------------------------------------------- setup helpers


def fit_workspace(raw: dict) -> None:
    """Tudor's frame (17 Nov): the X switch closes at x = x_max, the Y switch at y = y_min, and
    after homing the gantry stands at (x_min, y_min). So ufp.home_offset = (x_min, y_min) and the
    switch positions follow from machine.travel_limits. travel_a / travel_b no longer exist."""
    t = raw["machine"]["travel_limits"]
    u = raw["ufp"]
    u.pop("travel_a", None)
    u.pop("travel_b", None)
    u["home_offset"] = [float(t["x_min"]), float(t["y_min"])]
    sw = app_settings(raw).setdefault("switches", {})
    sw.setdefault("x", {})["position"] = float(t["x_max"])
    sw.setdefault("y", {})["position"] = float(t["y_min"])


def switch_motor(raw: dict, axis: str):
    """Index (0 = A, 1 = B) of the XY board the switch of `axis` is wired to, for Tudor's XYStage
    (switch_x_motor / switch_y_motor). 'auto' gives wiring: X on B, Y on A."""
    b = str(app_settings(raw).get("switches", {}).get(axis, {}).get("board", "auto")).lower()
    return {"a": 0, "b": 1}.get(b, 1 if axis == "x" else 0)


class AppMachine(ufp_driver.Machine):
    """The team's Machine, with syringe strokes that run while the gantry moves.

    Since commit a32cc4e771 (Hector, 17 Nov) Syringe.extrude() waits until the plunger stands
    still, polling its limit switch. ufp_driver.run calls extrude() and then the stroke's XY
    moves, so the batter would all come out first and the gantry would then draw the line
    without it. Here the push is started exactly like in Syringe.extrude() but without the final
    wait; during and after every XY move the active syringe is polled through the wrapper
    (Syringe.is_moving -> _guard), so a limit switch hit still stops it, backs off one turn and
    raises SyringeError, as Hector made it."""

    def extrude(self, m) -> None:
        from motion_profile import flow_profile
        from syringe_wrapper import SyringeError
        s = self.syringes._use(m.motor)            # one syringe at a time (team rule)
        if not s.primed:
            raise SyringeError("not primed: prime() first, so the plunger has taken up the slack")
        if m.steps < 0:
            raise ValueError(f"steps must be >= 0, got {m.steps}")
        if m.steps < 1e-9:
            return
        s.wait()
        v, a = (s.speed, s.accel) if m.duration is None else flow_profile(m.steps, m.duration, s.accel)
        s._push(m.steps, v, a)                      # starts the move and returns

    def move_xy(self, m) -> None:
        ox, oy = self.u.home_offset
        active = self.syringes.active
        syr = self.syringes.syringes[active] if active else None
        x0, y0 = self.xy
        est = math.hypot(m.x - x0, m.y - y0) / max(m.v, 1e-6) + m.v / max(m.a, 1e-6)
        self.stage.move_to(m.x - ox, m.y - oy, v=m.v, a=m.a, wait=False)
        deadline = time.monotonic() + 2 * max(m.duration or 0.0, est) + 5.0
        try:
            while True:
                if syr is not None:
                    syr.is_moving()                 # raises SyringeError if its limit switch was hit
                st = self.stage.get_states()
                if not st.is_moving:
                    break
                if math.hypot(st.x + ox - m.x, st.y + oy - m.y) < 0.3 and time.monotonic() > deadline - 5.0 - est:
                    self.stage.stop()               # arrived but the boards keep reporting "moving"
                    break
                if time.monotonic() > deadline:
                    raise TimeoutError("gantry move did not finish in time")
                time.sleep(0.01)
            self.stage.wait(timeout=5.0)
        except BaseException:
            self.stop()
            raise


def wiggle_port(port: str, current: float = 0.2, steps: float = 25.0) -> None:
    """Turn the motor on `port` a little back and forth (1/8 turn) so you can see which one it is.
    Only while the machine is not connected (the port must be free)."""
    import ufp
    dev = ufp.connect(port, timeout=1.0)
    try:
        dev.set_current(safe_current(current))
        dev.set_position(0)
        for target in (steps, 0, steps, 0):
            dev.set_target_position(target, 200, 2000)
            time.sleep(0.35)
    finally:
        try:
            dev.set_current(0)
        finally:
            dev.close()


def lost_board(e: BaseException) -> bool:
    """True if a board stopped talking (reset by a brownout, or unplugged)."""
    low = f"{type(e).__name__} {e}".lower()
    return any(k in low for k in ("write timeout", "serialtimeout", "serialexception", "clearcommerror",
                                  "device reports readiness", "permissionerror(13", "closed"))


def friendly_error(e: BaseException) -> str:
    """Turn common hardware errors into a hint what to do."""
    name, msg = type(e).__name__, str(e)
    low = msg.lower()
    if "write timeout" in low or name == "SerialTimeoutException":
        return (f"{msg}\n\nA board stopped taking data while its motor had current: on USB power this means "
                "the current is too high and the board reset (team firmware README: at most 0.2 on USB). "
                "Choose a lower motor current, then Find boards and Connect again. For more current, "
                "power the boards with 5 to 12 V and remove the USB power jumper.")
    if name == "WrongBoardError":
        return f"{msg}\n\nA board sits on a different port than before: press Find boards, then Connect."
    if "could not open port" in low or "filenotfound" in low or "no such file" in low or "cannot find" in low:
        return f"{msg}\n\nThat USB port does not exist now: plug the board in, press Find boards, then Connect."
    if "access is denied" in low or "permissionerror" in low or "busy" in low:
        return (f"{msg}\n\nThe port is used by another program (Arduino IDE, a second GUI, "
                "a serial monitor). Close it and try again.")
    if "does not fit print area" in low or "nozzle offsets" in low:
        return (f"{msg}\n\nThe design has to fit where EVERY syringe it uses can reach: print_area minus the nozzle "
                "offsets. Use 'all with syringe' (one syringe, no offsets), make the design smaller, or make "
                "print_area bigger in the settings file (it may be as big as machine.travel_limits).")
    if "still moving" in low or "did not arrive" in low:
        return (f"{msg}\n\nThe board did not report that the move finished. If the motor really did not turn: "
                "current too low for the load, or the board lost power. If it did turn: press the button again, "
                "the app now accepts a motor that stands within a step of its target.")
    if name in ("TimeoutError", "SerialTimeoutException") or "timeout" in low:
        return f"{msg}\n\nA board did not answer in time: check its USB cable and that it runs the UFP firmware."
    if name == "HomingFailed":
        return (f"{msg}\n\nCheck that the switches are wired (status line: both 'open' when free) and that "
                "X+ moves the carriage toward the X switch.")
    if "not homed" in low:
        return f"{msg}\n\nPress Home first."
    return f"{name}: {msg}"


# --------------------------------------------------------------------------- USB scan


@dataclass
class Board:
    port: str
    description: str
    motor_id: int | None = None
    name: str = ""
    error: str = ""
    usb: bool = False


def _probe(p, timeout: float, tries: int = 2) -> Board:
    """Hector's find_devices for one port: open it with ufp, ask get_id, close it again."""
    import ufp
    b = Board(p.device, p.description or "", usb=p.vid is not None)
    for attempt in range(tries):
        try:
            dev = ufp.connect(p.device, timeout=timeout)
        except Exception as e:  # not UFP, busy, or no answer yet
            b.error = f"no UFP answer ({type(e).__name__}: {str(e)[:60]})"
            time.sleep(0.4)
            continue
        try:
            b.name = getattr(getattr(dev, "info", None), "name", "") or ""
            if "get_id" in dev.functions:
                b.motor_id, b.error = int(dev.get_id()), ""
            else:
                b.error = "UFP device without get_id"
        except Exception as e:
            b.error = f"get_id failed ({e})"
        finally:
            try:
                dev.close()
            except Exception:
                pass
        if b.motor_id is not None:
            break
        time.sleep(0.4)
    return b


def scan_boards(timeout: float = 1.5, log=print) -> list[Board]:
    """Ask every USB serial port for its MOTOR_ID (get_id), like Hector's find_devices.py.
    His version only looks at macOS "usbmodem" ports; this one takes every USB port (Windows COM
    ports too), skips Bluetooth and other non USB ports (opening those can hang on Windows), asks
    all ports at the same time and tries each twice."""
    from concurrent.futures import ThreadPoolExecutor
    from serial.tools import list_ports
    ports = sorted(list_ports.comports(), key=lambda p: p.device)
    usb = [p for p in ports if p.vid is not None]
    if not usb:
        usb = ports                     # no USB information on this system: try them all
    log(f"asking {len(usb)} USB port(s) for their MOTOR_ID: " + ", ".join(p.device for p in usb))
    if not usb:
        return []
    with ThreadPoolExecutor(max_workers=len(usb)) as ex:
        found = list(ex.map(lambda p: _probe(p, timeout), usb))
    for b in found:
        log(f"  {b.port}: " + (f"MOTOR_ID {b.motor_id}" if b.motor_id is not None else b.error)
            + (f"   ({b.description})" if b.description else ""))
    time.sleep(0.5)                     # let Windows release the ports before they are opened again
    return found


def apply_scan(raw: dict, boards: list[Board]) -> list[str]:
    """Write the ports of the scanned boards into the config, by MOTOR_ID -> role (app.scan_role_by_id)."""
    roles = {int(k): v for k, v in app_settings(raw).get("scan_role_by_id", {}).items()}
    u = raw["ufp"]
    done = []
    for b in boards:
        role = roles.get(b.motor_id) if b.motor_id is not None else None
        if role in ("a", "b"):
            u["xy_motors"][role] = {"port": b.port, "id": b.motor_id}
        elif role and role.startswith("e"):
            u["plungers"][int(role[1:])] = {"port": b.port, "id": b.motor_id}
        else:
            continue
        done.append(f"{role} = {b.port} (MOTOR_ID {b.motor_id})")
    return done


# --------------------------------------------------------------------------- machine


class Controller:
    """Owns the connection. One operation at a time (the GUI runs them in a worker thread)."""

    def __init__(self, log=print):
        self.log = log
        self.machine: ufp_driver.Machine | None = None
        self.simulated = False
        self.raw: dict | None = None
        self.cfg: MachineConfig | None = None
        self.abort = threading.Event()
        self.resume = threading.Event()

    # ---- connect ----------------------------------------------------------

    @property
    def connected(self) -> bool:
        return self.machine is not None

    def plunger_names(self, cfg) -> list[str]:
        return sorted({f"e{min(n for n, bb in cfg.ufp.plungers.items() if bb.port == b.port)}"
                       for b in cfg.ufp.plungers.values()})

    def connect(self, raw: dict, simulated: bool = False, syringes=None) -> None:
        """syringes: names (e0, e1, e2) of the syringe boards to open; None = all in the config.
        The simulated machine always has all of them."""
        self.disconnect()
        cfg = build_config(raw)
        u = cfg.ufp
        names = self.plunger_names(cfg)
        if syringes is not None and not simulated:
            names = [n for n in names if n in syringes]
        a = app_settings(raw)
        from syringe_wrapper import SyringeBank
        from xy_stage_wrapper import XYStage
        x_lim, y_lim = cfg.stage_limits
        stage_args = dict(mm_per_step=u.mm_per_step_pair, x_limits=x_lim, y_limits=y_lim,
                          x_home_pos=x_lim[1],                     # the X switch closes at x_max
                          switch_x_motor=switch_motor(raw, "x"), switch_y_motor=switch_motor(raw, "y"),
                          homing_timeout=u.homing_timeout, motor_v_max=u.motor_v_max,
                          motor_a_max=u.motor_a_max, invert_a=u.invert_a, invert_b=u.invert_b,
                          expected_ids=(u.xy_motors["a"].id, u.xy_motors["b"].id))
        if simulated:
            # like ufp_driver.simulated_machine (Aaron, Tudor), but with x_home_pos and the simulated
            # switches where this box has them (Tudor's SimulatedXYStage: X at limit_x, Y at limit_y)
            from simulated_stepper import SimulatedStepper
            from simulated_xy_stage import SimulatedXYStage, fast_clock
            speed = float(a.get("dry_run_speed", 20))
            ids = {n: ufp_driver.board_spec(u, n).id for n in ("a", "b")}
            xy = SimulatedXYStage(mm_per_step=u.mm_per_step_pair, time_scale=speed,
                                  reversed_a=u.invert_a, reversed_b=u.invert_b,
                                  limit_x=x_lim[1], limit_y=0.0,
                                  start_x=x_lim[1] - min(10.0, x_lim[1] / 2), start_y=min(10.0, y_lim[1] / 2),
                                  id_a=ids["a"] or 1, id_b=ids["b"] or 2)
            clock = fast_clock(speed)
            sims = {n: SimulatedStepper(start_position=0.0, motor_id=ufp_driver.board_spec(u, n).id or 0,
                                        clock=clock) for n in names}
            syringes = SyringeBank.connect({n: sims[n].device for n in names},
                                           expected_ids={n: ufp_driver.board_spec(u, n).id for n in names},
                                           retract_steps=u.retract_steps, speed=u.plunger_speed,
                                           accel=u.plunger_accel, travel=u.plunger_travel,
                                           coil_current=safe_current(u.current))
            stage = XYStage(xy.device_a, xy.device_b, coil_current=safe_current(u.current), home_on_connect=False,
                            **stage_args)
            self.machine = AppMachine(u, stage, syringes)
            self.machine.sim = types.SimpleNamespace(xy=xy, syringes=sims)
            self._soften(stage, raw)
            self._guard_homing(stage)
            stage.home()
            self.log(f"simulated boards connected (Tudor's simulators, {speed:g}x real time), "
                     "homed with Tudor's sequence")
        else:
            cur = motor_currents(raw)
            xy_i = min(cur["a"], cur["b"])                  # start low, then each motor its own value
            pl_i = min([cur[n] for n in names] or [0.2])
            board = lambda n: ufp_driver.board_spec(u, n)  # noqa: E731
            self.log(f"connecting syringes {', '.join(names)} ...")
            syringes = SyringeBank.connect({n: board(n).port for n in names},
                                           expected_ids={n: board(n).id for n in names},
                                           retract_steps=u.retract_steps, speed=u.plunger_speed,
                                           accel=u.plunger_accel, travel=u.plunger_travel,
                                           coil_current=pl_i)
            for n, flag in (a.get("plunger_invert") or {}).items():   # syringe direction (Setup, step 8)
                name = f"e{int(n)}"
                if name in syringes.syringes and flag:
                    syringes[name].motor.invert = True
            manual = homing_mode(raw) == "manual"
            self.log(f"connecting gantry A {board('a').port}, B {board('b').port} at current {xy_i:g}")
            try:
                stage = XYStage(board("a").port, board("b").port, coil_current=xy_i,
                                home_on_connect=False, **stage_args)
            except BaseException:
                syringes.close()
                raise
            self.machine = AppMachine(u, stage, syringes)
            self._soften(stage, raw)
            self._guard_homing(stage)
            self.apply_currents(raw)
            if manual:
                x, y = a.get("manual_origin", [0.0, 0.0])
                self._declare_position(float(x), float(y), cfg)
                self.log(f"manual homing: the gantry is declared to stand at machine ({x:g}, {y:g}) mm")
            else:
                self.log("connected, not homed yet: press Home")
        self.simulated, self.raw, self.cfg = simulated, raw, cfg

    @staticmethod
    def _conn_view(raw: dict) -> dict:
        """The settings a connection is built from (ports, directions, frame, currents ...)."""
        a = app_settings(raw)
        return copy.deepcopy({"ufp": raw.get("ufp"), "plunger_invert": a.get("plunger_invert"),
                              "currents": currents(raw), "travel": raw.get("machine")})

    def needs_reconnect(self, raw: dict) -> bool:
        return (self.machine is not None and not self.simulated and self.raw is not None
                and self._conn_view(raw) != self._conn_view(self.raw))

    def ensure_current(self, raw: dict) -> None:
        """Reconnect (no motion) when settings changed since connecting. Homing is lost then."""
        if self.needs_reconnect(raw):
            self.log("settings changed since connecting: reconnecting with the new settings")
            self.connect(raw, simulated=False)

    def invalidate_home(self) -> None:
        if self.machine is not None:
            self.machine.stage.homed = False

    def disconnect(self) -> None:
        if self.machine is not None:
            try:
                self.machine.close()  # stop, coils off, ports closed (team code)
            finally:
                self.machine = None
                self.log("motors off, disconnected")

    def _declare_position(self, x: float, y: float, cfg=None) -> None:
        """Tell both XY motors where they are, as if homed: machine (x, y) -> stage -> motor a, b.
        Uses StepperMotor.assume_homed (Tudor), made for axes without a switch."""
        cfg = cfg or self.cfg
        u = cfg.ufp
        if not cfg.travel_limits.contains(x, y):
            t = cfg.travel_limits
            raise ValueError(f"machine ({x:g}, {y:g}) is outside machine.travel_limits "
                             f"(x {t.x_min:g}..{t.x_max:g}, y {t.y_min:g}..{t.y_max:g})")
        a, b = xy_to_ab(x - u.home_offset[0], y - u.home_offset[1])
        stage = self.machine.stage
        ma, mb = stage._motors  # XYStage keeps its two StepperMotor objects here
        ma.assume_homed(a)
        mb.assume_homed(b)
        stage.homed = True

    def apply_currents(self, raw: dict) -> dict:
        """Set every connected motor to its own current (works at once, no reconnect)."""
        if self.machine is None or self.simulated:
            return {}
        cur = motor_currents(raw)
        ma, mb = self.machine.stage._motors
        done = {}
        for name, m in (("a", ma), ("b", mb)):
            m.set_current(cur[name])
            done[name] = cur[name]
        for name, syr in self.machine.syringes.items():
            syr.motor.set_current(cur[name])
            done[name] = cur[name]
        self.log("currents: " + ", ".join(f"{k} {v:g}" for k, v in done.items()))
        return done

    @staticmethod
    def _soften(stage, raw) -> None:
        """Gentler ramps on Tudor's XYStage object (attributes he exposes; his file is unchanged):
        a_normal is used by homing and default moves, a_fast by stop() at a limit switch.
        Less acceleration = smaller current peaks (this machine runs on USB power)."""
        a = app_settings(raw)
        stage.v_normal = float(a.get("homing_speed", stage.v_normal))
        stage.a_normal = float(a.get("homing_accel", 200.0))
        stage.a_fast = float(a.get("stop_accel", 1000.0))

    def _guard_homing(self, stage) -> None:
        """STOP during Tudor's XYStage.home(): his loops poll _any_limit_hit() until a switch closes or
        the timeout runs out (up to two minutes). Wrapped on this object only (his file is unchanged)
        so that a pressed STOP raises Aborted at the next poll; home() then stops both motors."""
        orig = stage._any_limit_hit

        def guarded():
            if self.abort.is_set():
                raise Aborted()
            return orig()
        stage._any_limit_hit = guarded

    def set_origin_here(self, x: float, y: float) -> None:
        self._need()
        if self.simulated:
            raise RuntimeError("not available on the simulated machine")
        self._declare_position(x, y)
        self.log(f"position set: the gantry now stands at machine ({x:g}, {y:g}) mm")

    # ---- limit switches of this gantry -------------------------------------
    # Photo of 17 Nov: one switch on the front frame rail (the gantry touches it at the front,
    # y min) and one under the right end of the gantry (the carriage touches it, x max).
    # Default homing is Tudor's XYStage.home() (same switches, tested on the machine on 17 Nov).
    # The app's own search (find_switch, homing mode "switches") stays for the switch tests in
    # switch tests: straight moves with XYStage.set_velocity, both XY boards polled.

    @property
    def homed(self) -> bool:
        return bool(self.machine is not None and getattr(self.machine.stage, "homed", False))

    def limit_states(self) -> dict:
        """{'a': bool, 'b': bool}: True = switch pressed (or not wired), per XY board."""
        self._need()
        ma, mb = self.machine.stage._motors
        return {"a": ma.get_states().limit, "b": mb.get_states().limit}

    def _xy_motor_states(self):
        ma, mb = self.machine.stage._motors
        sa, sb = ma.get_states(), mb.get_states()
        return ab_to_xy(sa.z, sb.z), {"a": sa.limit, "b": sb.limit}

    def _drive_until(self, vx, vy, until, max_mm, accel=None, ok_at_max=False):
        """Drive at (vx, vy) mm/s until until(limits) is true. After max_mm: raises HomingFailed,
        or just stops when ok_at_max (used for plain relative moves: then it ramps down gently with
        `accel` and starts braking early, so it still ends at max_mm)."""
        stage = self.machine.stage
        accel = float(accel or (self.cfg.ufp.accel if self.cfg else 100.0))
        brake = math.hypot(vx, vy) ** 2 / (2 * accel) if ok_at_max else 0.0
        (x0, y0), lim = self._xy_motor_states()
        if until(lim):
            return lim
        stage.set_velocity(vx, vy, a=accel)
        try:
            while True:
                if self.abort.is_set():
                    raise Aborted()
                (x, y), lim = self._xy_motor_states()
                if until(lim):
                    return lim
                if math.hypot(x - x0, y - y0) >= max_mm - brake:
                    if ok_at_max:
                        return lim
                    raise HomingFailed(f"no limit switch within {max_mm:.0f} mm")
                time.sleep(0.003)
        finally:
            stage.stop(a=accel if ok_at_max else None)   # gentle for moves, stage.a_fast at a switch
            stage.wait(timeout=10.0)

    def _move_rel(self, dx, dy, speed):
        """Exact relative XY move without homing: each motor gets a position target relative to where it
        is (raw UFP set_target_position on Tudor's StepperMotor.motor, his unit conversion), with speed
        and acceleration split so both motors arrive together on a straight line."""
        d = math.hypot(dx, dy)
        if d <= 0:
            return
        accel = float(self.cfg.ufp.accel)
        da, db = xy_to_ab(dx, dy)                  # CoreXY: a = x + y, b = x - y (Tudor)
        stage = self.machine.stage
        jobs = []
        for m, dm in zip(stage._motors, (da, db)):
            z0 = m.get_states().z
            if abs(dm) > 1e-9:
                f = abs(dm) / d                    # this motor's share of the path
                raw = m.motor.get_states().position
                m.motor.set_target_position(raw + m._to_steps(dm, signed=True),
                                            m._to_steps(speed * f), m._to_steps(accel * f))
            jobs.append((m, z0 + dm))
        expected = trapezoid_time(d, speed, accel)
        try:
            for m, target in jobs:
                self._settle(m, target, expected, "gantry", tol=0.2)
        except BaseException:
            stage.stop()
            raise

    def _drive_by(self, dx, dy, speed):
        """Relative move without needing a homed stage (velocity for the right time)."""
        d = math.hypot(dx, dy)
        if d <= 0:
            return
        self._drive_until(dx / d * speed, dy / d * speed, lambda lim: False, max_mm=d, ok_at_max=True)

    def _switch_cfg(self, raw=None):
        sw = app_settings(raw or self.raw).get("switches", {})
        return (sw, float(sw.get("fast_mm_s", 10)), float(sw.get("slow_mm_s", 2)),
                float(sw.get("backoff_mm", 3)), float(sw.get("max_search_mm", 600)))

    def find_switch(self, axis: str, raw: dict | None = None):
        """Drive to the switch of `axis`, touch it twice (fast, then slow), back off.
        Returns (board, motor_xy_at_touch). Works without homing."""
        self._need()
        if self.simulated:
            raise RuntimeError("not on the simulated machine (Tudor's simulator homes per motor)")
        sw, fast, slow, back, search = self._switch_cfg(raw)
        c = sw[axis]
        d = _sign(c["toward"])
        ux, uy = (d, 0.0) if axis == "x" else (0.0, d)
        want = str(c.get("board", "auto")).lower()
        start = self.limit_states()
        if want in ("a", "b") and start[want]:      # sitting on it: move off first
            self.log(f"{axis} switch already pressed on board {want.upper()}: backing off")
            self._drive_until(-ux * slow * 2, -uy * slow * 2, lambda lim: not lim[want], max_mm=20)
            self._drive_by(-ux * back, -uy * back, slow * 2)
            start = self.limit_states()
        free = [k for k in "ab" if not start[k]]
        if not free:
            raise HomingFailed("both XY boards read their switch as open (pressed or not wired); "
                               "check the switch wiring (Setup, step 2)")
        self.log(f"{axis}: moving {c['toward']} at {fast:g} mm/s until a switch closes ...")
        lim = self._drive_until(ux * fast, uy * fast, lambda l: any(l[k] for k in free), search)
        hit = [k for k in free if lim[k]]
        if want in ("a", "b") and want not in hit:
            raise HomingFailed(f"the {axis} switch answered on board {'/'.join(hit).upper()}, "
                               f"Settings say board {want.upper()}: change it (or set auto)")
        board = hit[0]
        self._drive_until(-ux * slow * 2, -uy * slow * 2, lambda l: not l[board], max_mm=20)
        self._drive_by(-ux * back, -uy * back, slow * 2)
        self._drive_until(ux * slow, uy * slow, lambda l: l[board], max_mm=back * 3 + 5)
        (xm, ym), _ = self._xy_motor_states()
        self._drive_until(-ux * slow * 2, -uy * slow * 2, lambda l: not l[board], max_mm=20)
        self._drive_by(-ux * back, -uy * back, slow * 2)   # leave the switch free
        self.log(f"  {axis} switch found on board {board.upper()}")
        return board, (xm, ym)

    def home(self, raw: dict | None = None) -> tuple[float, float]:
        """Home with the mode from the settings. Returns the machine (x, y) afterwards."""
        raw = raw or self.raw
        mode = homing_mode(raw)
        if mode == "tudor":
            return self.home_tudor(raw)
        if mode == "switches":
            return self.home_switches(raw)
        x, y = app_settings(raw).get("manual_origin", [0.0, 0.0])
        self.set_origin_here(float(x), float(y))
        return float(x), float(y)

    def home_tudor(self, raw: dict | None = None) -> tuple[float, float]:
        """Tudor's XYStage.home(): +X until a switch closes (x = x_max), back to x_min, -Y until a
        switch closes (y = y_min). The gantry ends at (x_min, y_min) = ufp.home_offset."""
        self._need()
        self.abort.clear()
        stage = self.machine.stage
        t = self.cfg.travel_limits
        self.log(f"homing (Tudor): +X to the switch at x {t.x_max:g} at {stage.v_normal:g} mm/s, "
                 f"back to x {t.x_min:g}, then -Y to the switch at y {t.y_min:g}")
        try:
            stage.home()
        except Aborted:
            raise
        except Exception as e:
            raise HomingFailed(str(e)) from e
        x, y = self.machine.xy
        self.log(f"homed: gantry at ({x:.1f}, {y:.1f}) mm")
        return x, y

    def home_switches(self, raw: dict | None = None) -> tuple[float, float]:
        """Home on the two axis switches, then declare the position. Returns the machine (x, y)."""
        self._need()
        if self.simulated:
            raise RuntimeError("the simulated machine is homed by Tudor's simulator on connect")
        raw = raw or self.raw
        sw, fast, *_ = self._switch_cfg(raw)
        self.abort.clear()
        stage = self.machine.stage
        stage.homed = False
        trig = {}
        for axis in sw.get("order", ["y", "x"]):
            _, trig[axis] = self.find_switch(axis, raw)
        # position from the motor counters: distance since each switch closed
        (xn, yn), _ = self._xy_motor_states()
        x = float(sw["x"]["position"]) + (xn - trig["x"][0])
        y = float(sw["y"]["position"]) + (yn - trig["y"][1])
        self._declare_position(x, y)
        px, py = park_point(raw)
        stage.move_to(px - self.cfg.ufp.home_offset[0], py - self.cfg.ufp.home_offset[1],
                      v=fast, wait=True)
        self.log(f"homed: switches at x {sw['x']['position']:g}, y {sw['y']['position']:g}; "
                 f"gantry now at ({px:g}, {py:g}) mm")
        return px, py

    def homing_repeatability(self, runs: int = 3, raw: dict | None = None) -> dict:
        """Home, then touch each switch `runs` more times slowly, from 30 mm away, and read where it
        closes in the homed frame (X should read x_max, Y should read y_min). Returns the spread
        of the touch points (mm). Below about 0.2 mm is good."""
        raw = raw or self.raw
        self.home(raw)
        sw, fast, slow, back, _ = self._switch_cfg(raw)
        t = self.cfg.travel_limits
        ox, oy = self.cfg.ufp.home_offset
        stage = self.machine.stage
        pts = {"x": [], "y": []}
        for i in range(runs):
            for axis in sw.get("order", ["y", "x"]):
                if self.abort.is_set():
                    raise Aborted()
                d = _sign(sw[axis]["toward"])
                if axis == "x":
                    sx = (t.x_max if d > 0 else t.x_min) - d * 30
                    sy = min(max(t.y_min + 30, t.y_min), t.y_max)
                    ux, uy = d, 0.0
                else:
                    sx = min(max(t.x_min + 30, t.x_min), t.x_max)
                    sy = (t.y_min if d < 0 else t.y_max) - d * 30
                    ux, uy = 0.0, d
                stage.move_to(sx - ox, sy - oy, v=fast, wait=True)
                self._drive_until(ux * slow, uy * slow, lambda l: l["a"] or l["b"], max_mm=45)
                (xm, ym), _ = self._xy_motor_states()
                pts[axis].append(xm + ox if axis == "x" else ym + oy)
                self._drive_until(-ux * slow * 2, -uy * slow * 2, lambda l: not (l["a"] or l["b"]), max_mm=20)
                self._drive_by(-ux * back, -uy * back, slow * 2)
        px, py = park_point(raw)                   # back to where homing left it (x min, y min)
        stage.move_to(px - ox, py - oy, v=fast, wait=True)
        spread = {k: (max(v) - min(v)) if v else 0.0 for k, v in pts.items()}
        self.log(f"repeatability over {runs} touches: x spread {spread['x']:.3f} mm, "
                 f"y spread {spread['y']:.3f} mm")
        return {"points": pts, "spread": spread}

    def drive_test(self, axis: str, dist: float, speed: float = 10.0) -> None:
        """Move +dist along one axis without homing (direction test)."""
        self._need()
        if axis == "x":
            self._drive_by(dist, 0.0, speed)
        else:
            self._drive_by(0.0, dist, speed)

    def invert_xy(self, which: str, raw: dict) -> None:
        """Flip the direction of XY motor 'a' or 'b' now (and in the config). Homing is lost."""
        self._need()
        idx = 0 if which == "a" else 1
        m = self.machine.stage._motors[idx]
        m.invert = not m.invert
        raw["ufp"][f"invert_{which}"] = bool(m.invert)
        if self.raw is not None:
            self.raw["ufp"][f"invert_{which}"] = bool(m.invert)   # the connection now has it too
        self.machine.stage.homed = False
        self.log(f"motor {which.upper()}: direction flipped (invert_{which} = {m.invert})")

    def invert_syringe(self, name: str, raw: dict) -> None:
        self._need()
        s = self.machine.syringes[name]
        s.motor.invert = not s.motor.invert
        s.primed = False
        s.motor.redefine_z(0.0)
        s._target = 0.0
        for r in (raw, self.raw):                                 # config and live connection
            if r is not None:
                inv = app_settings(r).setdefault("plunger_invert", {})
                inv[int(name[1:])] = bool(s.motor.invert)
        self.log(f"syringe {name}: direction flipped, position set to 0")

    def wait_switch_change(self, timeout: float = 20.0):
        """Switch test: wait until both switches are free (closed), then for one to be pressed.
        Returns ('a' | 'b', True), or (board, 'stuck') if a board stays open with nothing pressed,
        or (None, None) after the timeout."""
        self._need()
        t0 = time.monotonic()
        while True:                                   # 1. everything released
            now = self.limit_states()
            if not any(now.values()):
                break
            if time.monotonic() - t0 > 3.0:
                k = next(k for k, v in now.items() if v)
                return k, "stuck"
            time.sleep(0.02)
        while time.monotonic() - t0 < timeout:        # 2. one switch pressed
            if self.abort.is_set():
                raise Aborted()
            now = self.limit_states()
            for k in "ab":
                if now[k]:
                    return k, True
            time.sleep(0.02)
        return None, None

    def _need(self):
        if self.machine is None:
            raise RuntimeError("not connected: press Connect")

    # ---- jog --------------------------------------------------------------

    def position(self):
        self._need()
        st = self.machine.stage.get_states()
        ox, oy = self.cfg.ufp.home_offset
        return st.x + ox, st.y + oy, st.is_moving, st.limit

    def jog_xy(self, dx: float, dy: float, speed: float = 20.0) -> None:
        """Relative move. Before homing there are no coordinates: it moves without range checks."""
        self._need()
        if not self.homed and not self.simulated:
            self._move_rel(dx, dy, min(speed, 60.0))
            return
        x, y, _, _ = self.position()
        self.goto_xy(x + dx, y + dy, speed)

    def goto_xy(self, x: float, y: float, speed: float = 30.0) -> None:
        self._need()
        lim = self.cfg.travel_limits
        if not lim.contains(x, y):
            raise ValueError(f"({x:.1f}, {y:.1f}) is outside machine.travel_limits")
        self.machine.move_xy(XYMove(x, y, speed, self.cfg.ufp.accel, 0.0))

    def jog_syringe(self, name: str, steps: float, backlash: float = 0.0) -> None:
        """Turn one plunger by `steps` (+ = push batter out). Pulling back below 0 moves the zero.
        When the direction reverses, `backlash` steps are added first (slack of nut and plunger).
        Afterwards the syringe cycle bookkeeping is set to where the plunger really is."""
        self._need()
        s = self.machine.syringes[name]
        d = 1 if steps > 0 else -1
        last = getattr(self, "_syr_dir", {}).get(name)
        if backlash > 0 and last is not None and last != d:
            steps += d * backlash
            self.log(f"syringe {name}: {backlash:g} steps added for backlash (direction changed)")
        self._syr_dir = {**getattr(self, "_syr_dir", {}), name: d}
        if s.primed:
            s.retract()
        m = s.motor
        z = m.get_z()
        if z + steps < 0:
            m.redefine_z(z - (z + steps))  # make room below
            z = m.get_z()
        target = float(round(min(z + steps, s.travel)))   # whole steps (Hector: no "half holds")
        m.set_z(target, vz=s.speed, az=s.accel)
        self._settle(m, target, trapezoid_time(abs(target - z), s.speed, s.accel), f"syringe {name}")
        s._target = m.get_z()  # Syringe keeps its commanded position here
        self.log(f"syringe {name}: {steps:+g} steps, now at {s._target:.1f} of {s.travel:g}")

    def _settle(self, m, target, expected, label, tol=0.6):
        """Wait for one StepperMotor (Tudor) to arrive. Done when the board says it stands still, or
        when it is within `tol` (motor units) of the target and slow: some board firmware versions keep
        reporting is_moving while they dither around the target, then it is stopped here."""
        deadline = time.monotonic() + 2 * expected + 2.0
        while True:
            if self.abort.is_set():
                m.stop()
                raise Aborted()
            st = m.get_states()
            if not st.is_moving:
                return
            if abs(st.z - target) <= tol and time.monotonic() > deadline - expected - 2.0:
                m.stop()                                   # velocity 0: ends the dithering
                return
            if time.monotonic() > deadline:
                m.stop()
                raise TimeoutError(f"{label} did not arrive: at {st.z:.1f}, target {target:.1f}, still "
                                   f"moving at {st.vz:.1f}/s after {2 * expected + 2.0:.1f} s")
            time.sleep(0.01)

    def zero_syringe(self, name: str) -> None:
        """After refilling: the plunger position becomes 0 (full stroke available again)."""
        self._need()
        s = self.machine.syringes[name]
        s.primed = False
        s.motor.redefine_z(0.0)
        s._target = 0.0
        self.log(f"syringe {name}: position set to 0 (refilled)")

    def syringe_positions(self) -> dict:
        self._need()
        return {n: s.position for n, s in self.machine.syringes.items()}

    def stop(self) -> None:
        """STOP: from any thread. Sets the abort flag and ramps every motor down (team's Machine.stop)."""
        self.abort.set()
        self.resume.set()
        if self.machine is not None:
            self.machine.stop()

    def reset_after_stop(self) -> None:
        if self.machine is None:
            return
        for _, s in self.machine.syringes.items():
            try:
                s.primed = False
                s._target = s.motor.get_z()
            except Exception:
                pass

    # ---- print ------------------------------------------------------------

    def run(self, plan: Plan, on_progress=None, on_pause=None) -> None:
        """Run the planned steps with the team's ufp_driver.run. STOP raises Aborted at the next step."""
        self._need()
        self.abort.clear()
        steps = plan.steps

        def progress(i, n):
            if self.abort.is_set():
                raise Aborted()
            if on_progress:
                on_progress(i, n, steps[i - 1])

        a = app_settings(self.raw or {})
        mode, wait_s = a.get("colour_change", "countdown"), float(a.get("colour_wait_s", 20))

        def pause(message):
            """Colour change (motion.Pause): countdown or wait for the Continue button."""
            if self.abort.is_set():
                raise Aborted()
            self.resume.clear()
            if on_pause:
                on_pause(message, mode, wait_s)
            if mode == "countdown":
                scale = float(a.get("dry_run_speed", 20)) if self.simulated else 1.0
                self.resume.wait(wait_s / scale)
            else:
                self.resume.wait()
            if self.abort.is_set():
                raise Aborted()

        # Tudor's cycle: every stroke starts with Prime (push retract_steps) that undoes the previous
        # stroke's Retract. Before the FIRST stroke nothing was pulled back, so that first Prime would
        # push a whole retract + backlash of extra batter (a blob at the start). So each syringe of
        # this print is pulled back once first, unless its last move was already backwards.
        used = sorted({st.motor for st in steps if isinstance(st, (Prime, Extrude))})
        syrs = dict(self.machine.syringes.items())
        for name in used:
            r = float(syrs[name].retract_steps) if name in syrs else 0.0
            if r > 0 and getattr(self, "_syr_dir", {}).get(name) != -1:
                self.jog_syringe(name, -r)
                self.log(f"syringe {name}: pulled back {r:g} steps before the first line (the first prime "
                         "pushes them again)")
        try:
            ufp_driver.run(steps, self.machine, on_progress=progress, on_pause=pause)
            # every stroke ends with Retract: the plungers last moved backwards
            self._syr_dir = {n: -1 for n, _ in self.machine.syringes.items()}
        except BaseException:
            try:
                self.machine.stop()
                time.sleep(0.3)
            finally:
                self.reset_after_stop()
            raise

    def print_here(self, plan: Plan, start, on_progress=None, on_pause=None) -> None:
        """Print without homing: the spot where the gantry stands now becomes `start` (the middle of
        the design under the first colour's nozzle, see here_point), and the print ends there again.
        Afterwards the gantry counts as not homed (the coordinates were only for this print)."""
        self._need()
        if self.simulated:
            raise RuntimeError("not on the simulated machine: use Dry run")
        self._declare_position(*start)
        self.log(f"print here: this spot is the middle of the design; it ends here again")
        try:
            self.run(plan, on_progress, on_pause)
        finally:
            self.invalidate_home()

    def xy_calibration(self, commanded_mm: float, measured_mm: float) -> float:
        """New mm_per_step from a jog of `commanded_mm` that really moved `measured_mm`."""
        m = self.cfg.ufp.mm_per_step_pair[0] if self.cfg else 0.31416
        return m * measured_mm / commanded_mm
