"""Pancake printer: one simple window.

Puts the team's code together, unchanged:
  * Aaron Zeng: SVG -> toolpath -> motor steps (team/software: pipeline, toolpath, motion, ufp_driver)
  * Tudor Mocioi: gantry and homing (xy_stage_wrapper), syringes (syringe_wrapper), simulators
  * Hector Astrom: syringe measurements and limit switch back off, board search by MOTOR_ID
  * Quentin Bolsee: UFP library and board firmware (third_party/ufp)
Glue (app/backend.py) and this window: written by Claude (Anthropic) for Andrin Schmid.

Start with run_gui.bat. All values live in app/pancake_config.yaml (button "Settings file").
"""
from __future__ import annotations

import copy
import os
import queue
import sys
import threading
import traceback
from pathlib import Path

import tkinter as tk
from tkinter import filedialog, messagebox, ttk

if sys.platform == "win32":
    try:
        import ctypes
        ctypes.windll.shcore.SetProcessDpiAwareness(1)
    except Exception:
        pass

import backend as be  # noqa: E402  (sets up the paths to the team code)
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg  # noqa: E402
from matplotlib.figure import Figure  # noqa: E402

APP = Path(__file__).resolve().parent
ROLES = ["not used", "gantry A", "gantry B", "syringe 0", "syringe 1", "syringe 2"]
ROLE_KEY = {"gantry A": "a", "gantry B": "b", "syringe 0": "e0", "syringe 1": "e1", "syringe 2": "e2"}
KEY_ROLE = {v: k for k, v in ROLE_KEY.items()}
IMAGES = (".png", ".jpg", ".jpeg", ".bmp", ".webp", ".gif", ".tif", ".tiff")
CREDITS = ("Team code: Aaron Zeng (SVG to motor steps), Tudor Mocioi (gantry, homing, syringes), "
           "Hector Astrom (syringes, board search), Quentin Bolsee (UFP). "
           "This window and app/backend.py: Claude for Andrin Schmid. Details in CREDITS.md")


class SimpleApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Pancake printer")
        self.raw = be.load_raw()
        self.ctl = be.Controller(log=self.log)
        self.boards: list[be.Board] = []
        self.role_vars: dict[str, tk.StringVar] = {}
        self.plan = None
        self.busy = False
        self.q: queue.Queue = queue.Queue()

        k = self.winfo_fpixels("1i") / 96
        self.geometry(f"{int(1280 * k)}x{int(800 * k)}")
        style = ttk.Style(self)
        if "vista" in style.theme_names():
            style.theme_use("vista")
        style.configure("Big.TButton", font=("Segoe UI", 11, "bold"), padding=6)
        style.configure("Head.TLabel", font=("Segoe UI", 11, "bold"))

        self._build()
        self.bind("<Escape>", lambda e: self.stop())
        self.protocol("WM_DELETE_WINDOW", self.on_close)
        self.after(50, self._pump)
        self.after(500, self._poll)

    # ------------------------------------------------------------------ layout

    def _build(self):
        top = ttk.Frame(self, padding=(10, 8))
        top.pack(fill="x")
        ttk.Label(top, text="Pancake printer", font=("Segoe UI", 15, "bold")).pack(side="left")
        tk.Button(top, text="STOP  (Esc)", bg="#dc2626", fg="white", activebackground="#b91c1c",
                  font=("Segoe UI", 13, "bold"), padx=18, command=self.stop).pack(side="right")
        self.status = ttk.Label(top, text="not connected", font=("Segoe UI", 10))
        self.status.pack(side="right", padx=16)

        bottom = ttk.Frame(self, padding=(10, 0, 10, 6))
        bottom.pack(side="bottom", fill="x")
        row = ttk.Frame(bottom)
        row.pack(fill="x")
        ttk.Button(row, text="Settings file", command=lambda: self._open(APP / "pancake_config.yaml")).pack(side="left")
        ttk.Button(row, text="Reload settings", command=self.reload).pack(side="left", padx=4)
        ttk.Button(row, text="Wiring picture", command=lambda: self._open(APP / "wiring.png")).pack(side="left")
        ttk.Label(row, text=CREDITS, foreground="#666", wraplength=900).pack(side="left", padx=12)
        self.logbox = tk.Text(bottom, height=4, font=("Consolas", 9), bg="#f8fafc")
        self.logbox.pack(fill="x", pady=(4, 0))

        body = ttk.Frame(self, padding=(10, 0))
        body.pack(fill="both", expand=True)
        left = ttk.Frame(body, width=440)
        left.pack(side="left", fill="y", padx=(0, 12))
        right = ttk.Frame(body)
        right.pack(side="left", fill="both", expand=True)
        self._build_machine(left)
        self._build_print(right)

    def _build_machine(self, f):
        ttk.Label(f, text="1  Boards", style="Head.TLabel").pack(anchor="w")
        r = ttk.Frame(f)
        r.pack(fill="x", pady=2)
        ttk.Button(r, text="Find boards", command=self.find_boards).pack(side="left")
        ttk.Label(r, text="plug in all USB-C cables first", foreground="#666").pack(side="left", padx=8)
        self.board_box = ttk.Frame(f)
        self.board_box.pack(fill="x", pady=(2, 8))
        ttk.Label(self.board_box, text="no boards yet", foreground="#666").pack(anchor="w")

        ttk.Label(f, text="2  Connect and home", style="Head.TLabel").pack(anchor="w")
        r = ttk.Frame(f)
        r.pack(fill="x", pady=(2, 2))
        ttk.Button(r, text="Connect", style="Big.TButton", command=self.connect).pack(side="left")
        ttk.Button(r, text="Home", style="Big.TButton", command=self.home).pack(side="left", padx=6)
        ttk.Button(r, text="Motors off", command=self.disconnect).pack(side="left")
        cur = be.motor_currents(self.raw)
        self.cur_vars = {}
        r = ttk.Frame(f)
        r.pack(fill="x", pady=(0, 2))
        ttk.Label(r, text="current   gantry A").pack(side="left")
        r2 = ttk.Frame(f)
        r2.pack(fill="x", pady=(0, 8))
        ttk.Label(r2, text="syringe 0").pack(side="left", padx=(56, 0))
        for m, row, label in (("a", r, None), ("b", r, "B"), ("e0", r2, None), ("e1", r2, "1"), ("e2", r2, "2")):
            if label:
                ttk.Label(row, text=label).pack(side="left", padx=(8, 0))
            v = tk.StringVar(value=f"{cur[m]:g}")
            self._num(row, v, 5, self._current_changed).pack(side="left", padx=(3, 0))
            self.cur_vars[m] = v
        ttk.Label(r, text="0 to 0.99, Enter (USB: 0.2)", foreground="#666").pack(side="left", padx=8)

        ttk.Label(f, text="3  Move", style="Head.TLabel").pack(anchor="w")
        r = ttk.Frame(f)
        r.pack(fill="x", pady=2)
        ttk.Label(r, text="gantry step mm").pack(side="left")
        self.jog_mm = tk.StringVar(value="10")
        self._num(r, self.jog_mm, 6).pack(side="left", padx=4)
        pad = ttk.Frame(f)
        pad.pack(pady=4)
        for txt, rr, cc, dx, dy in (("Y+", 0, 1, 0, 1), ("X-", 1, 0, -1, 0), ("X+", 1, 2, 1, 0), ("Y-", 2, 1, 0, -1)):
            ttk.Button(pad, text=txt, width=6, command=lambda dx=dx, dy=dy: self.jog(dx, dy)).grid(row=rr, column=cc, padx=2, pady=2)
        r = ttk.Frame(f)
        r.pack(fill="x", pady=(6, 2))
        ttk.Label(r, text="syringe steps").pack(side="left")
        self.syr_steps = tk.StringVar(value="50")
        self._num(r, self.syr_steps, 6).pack(side="left", padx=4)
        ttk.Label(r, text="(200 = one turn = 8 mm)", foreground="#666").pack(side="left")
        self.syr_box = ttk.Frame(f)
        self.syr_box.pack(fill="x")
        for n in range(3):
            rr = ttk.Frame(self.syr_box)
            rr.pack(fill="x", pady=1)
            ttk.Label(rr, text=f"syringe {n}", width=10).pack(side="left")
            ttk.Button(rr, text="pull back", command=lambda n=n: self.jog_syr(n, -1)).pack(side="left")
            ttk.Button(rr, text="push out", command=lambda n=n: self.jog_syr(n, 1)).pack(side="left", padx=4)
            ttk.Button(rr, text="refilled: zero", command=lambda n=n: self.zero_syr(n)).pack(side="left")

    def _build_print(self, f):
        r = ttk.Frame(f)
        r.pack(fill="x")
        ttk.Label(r, text="4  Print", style="Head.TLabel").pack(side="left")
        ttk.Button(r, text="Open picture or SVG ...", command=self.open_design).pack(side="left", padx=(10, 2))
        ttk.Button(r, text="Draw ...", command=self.free_draw).pack(side="left", padx=(2, 6))
        ttk.Label(r, text="all with syringe").pack(side="left")
        ds = self.raw["app"].get("design_syringe")
        self.design_syr = tk.StringVar(value="" if ds is None else str(ds))
        self._num(r, self.design_syr, 3, self.set_design_syringe).pack(side="left", padx=(2, 12))
        ttk.Button(r, text="Test square", command=self.test_square).pack(side="left")
        self.sq_size = tk.StringVar(value="40")
        self._num(r, self.sq_size, 5).pack(side="left", padx=2)
        ttk.Label(r, text="mm, syringe").pack(side="left")
        self.sq_syr = tk.StringVar(value="0")
        self._num(r, self.sq_syr, 3).pack(side="left", padx=2)
        r = ttk.Frame(f)
        r.pack(fill="x", pady=(6, 0))
        ttk.Button(r, text="Offset test (3 squares)", command=self.offset_test).pack(side="left")
        ttk.Label(r, text="nozzle offset x, y mm:").pack(side="left", padx=(10, 2))
        self.off_vars = {}
        for z in sorted(self.raw["nozzles"], key=lambda n: int(n["id"]))[1:3]:
            ttk.Label(r, text=f"syringe {z['id']}").pack(side="left", padx=(6, 2))
            v = tk.StringVar(value=f"{float(z['offset'][0]):g}, {float(z['offset'][1]):g}")
            ent = ttk.Entry(r, textvariable=v, width=9)
            ent.pack(side="left")
            ent.bind("<Return>", lambda ev: self.set_offsets())
            self.off_vars[int(z["id"])] = v
        ttk.Button(r, text="Set", command=self.set_offsets).pack(side="left", padx=4)
        ttk.Label(r, text="(0 = reference)", foreground="#666").pack(side="left")
        r = ttk.Frame(f)
        r.pack(fill="x", pady=(4, 0))
        ttk.Label(r, text="measure offsets with the arrows: nozzle over the same mark, then").pack(side="left")
        self._mark0 = None
        for n in range(3):
            ttk.Button(r, text=f"syringe {n} is on it", command=lambda n=n: self.mark_nozzle(n)).pack(side="left", padx=3)
        r = ttk.Frame(f)
        r.pack(fill="x", pady=(6, 0))
        ttk.Label(r, text="syringe push").pack(side="left")
        self.push_var = tk.StringVar(value=f"{float(self.raw['ufp']['plunger_steps_per_mm']):g}")
        e = ttk.Entry(r, textvariable=self.push_var, width=8)
        e.pack(side="left", padx=4)
        e.bind("<Return>", lambda ev: self.set_push())
        ttk.Label(r, text="steps per mm").pack(side="left")
        a = self.raw["app"]
        self.retract_var = tk.StringVar(value=f"{float(a.get('retract', self.raw['ufp']['retract_steps'])):g}")
        self.backlash_var = tk.StringVar(value=f"{float(a.get('backlash', 0)):g}")
        for text, var in (("retract", self.retract_var), ("backlash", self.backlash_var)):
            ttk.Label(r, text=text).pack(side="left", padx=(10, 2))
            e = ttk.Entry(r, textvariable=var, width=5)
            e.pack(side="left")
            e.bind("<Return>", lambda ev: self.set_push())
        ttk.Label(r, text="steps").pack(side="left", padx=(2, 0))
        ttk.Button(r, text="Set", command=self.set_push).pack(side="left", padx=4)
        self.push_info = ttk.Label(r, foreground="#666")
        self.push_info.pack(side="left", padx=6)
        self._push_info()
        r = ttk.Frame(f)
        r.pack(fill="x", pady=(6, 0))
        ttk.Label(r, text="speed").pack(side="left")
        self.speed_var = tk.StringVar(value=f"{be.speed_pct(self.raw):g}")
        self._num(r, self.speed_var, 6, self.set_speed).pack(side="left", padx=4)
        ttk.Label(r, text="%").pack(side="left")
        self.speed_info = ttk.Label(r, foreground="#666")
        self.speed_info.pack(side="left", padx=(6, 14))
        self._speed_info()
        r = ttk.Frame(f)
        r.pack(fill="x", pady=(6, 0))
        ttk.Button(r, text="Dry run (simulated)", command=self.dry_run).pack(side="left")
        ttk.Button(r, text="PRINT HERE (no homing)", style="Big.TButton", command=self.print_here).pack(side="left", padx=10)
        ttk.Button(r, text="PRINT (after Home)", command=self.print_now).pack(side="left")
        self.progress = ttk.Progressbar(r, length=200, maximum=1.0)
        self.progress.pack(side="left", padx=10)
        self.summary = ttk.Label(f, text="open a picture (made into 3 colours) or an SVG", foreground="#444")
        self.summary.pack(anchor="w", pady=4)
        self.fig = Figure(figsize=(6, 4), dpi=100)
        self.ax = self.fig.add_subplot(111)
        self.canvas = FigureCanvasTkAgg(self.fig, master=f)
        self.canvas.get_tk_widget().pack(fill="both", expand=True)
        self._draw_empty()

    def _num(self, parent, var, width, on_set=None):
        """A typed number field. With on_set: applied on Enter and when leaving the field."""
        e = ttk.Entry(parent, textvariable=var, width=width, justify="right")
        if on_set:
            e.bind("<Return>", lambda ev: on_set())
            e.bind("<FocusOut>", lambda ev: on_set())
        return e

    @staticmethod
    def _f(var, default, lo=None, hi=None):
        """Number from a field; `default` when empty or not a number; clamped to lo..hi."""
        try:
            v = float(str(var.get()).replace(",", ".").strip())
        except ValueError:
            v = float(default)
        if lo is not None:
            v = max(lo, v)
        if hi is not None:
            v = min(hi, v)
        return v

    # ------------------------------------------------------------------ plumbing

    def log(self, msg):
        self.q.put(("log", str(msg)))

    def ui(self, fn):
        self.q.put(("call", fn))

    def _pump(self):
        try:
            while True:
                kind, x = self.q.get_nowait()
                if kind == "log":
                    self.logbox.insert("end", x + "\n")
                    self.logbox.see("end")
                else:
                    x()
        except queue.Empty:
            pass
        self.after(50, self._pump)

    def run_bg(self, title, fn, done=None):
        if self.busy:
            messagebox.showinfo("Busy", "Wait until the current action is finished (or press STOP).")
            return
        self.busy = True
        self.status.configure(text=title + " ...")

        def work():
            try:
                res = fn()
            except BaseException as e:
                err, tb = e, traceback.format_exc()
                self.ui(lambda err=err, tb=tb: self._done(title, done, None, err, tb))
            else:
                self.ui(lambda res=res: self._done(title, done, res, None, None))
        threading.Thread(target=work, daemon=True).start()

    def _done(self, title, done, res, err, tb):
        self.busy = False
        self._update_status()
        if err is None:
            if done:
                done(res)
            return
        if isinstance(err, be.Aborted):
            self.log(f"{title}: stopped")
            return
        if be.lost_board(err):                    # the board reset or was unplugged: drop the dead connection
            try:
                self.ctl.disconnect()
            except Exception:
                pass
            self.boards = []
            self._update_status()
        self.log(tb.strip().splitlines()[-1])
        print(tb, file=sys.stderr)
        messagebox.showerror(title, be.friendly_error(err))

    def _update_status(self, pos=None, lim=None):
        if not self.ctl.connected:
            self.status.configure(text="not connected")
            return
        t = "connected" + (", homed" if self.ctl.homed else ", NOT homed")
        if pos:
            t += f"   x {pos[0]:.1f}  y {pos[1]:.1f}"
        if lim:
            sw_x = self.raw.get("app", {}).get("switches", {}).get("x", {}).get("board", "b").lower()
            sw_y = self.raw.get("app", {}).get("switches", {}).get("y", {}).get("board", "a").lower()
            t += f"   switch X ({sw_x.upper()}) " + ("PRESSED" if lim.get(sw_x) else "open")
            t += f", Y ({sw_y.upper()}) " + ("PRESSED" if lim.get(sw_y) else "open")
        self.status.configure(text=t)

    def _poll(self):
        if self.ctl.connected and not self.busy and not self.ctl.simulated:
            try:
                x, y, _, _ = self.ctl.position()
                self._update_status((x, y), self.ctl.limit_states())
            except Exception:
                pass
        self.after(500, self._poll)

    def _open(self, path):
        try:
            os.startfile(str(path))          # Windows
        except AttributeError:
            import subprocess
            subprocess.Popen(["xdg-open" if sys.platform.startswith("linux") else "open", str(path)])

    def reload(self):
        try:
            raw = be.load_raw()
            be.build_config(raw)
        except Exception as e:
            messagebox.showerror("Settings", f"The settings file has an error:\n{e}")
            return
        self.raw = raw
        self.log("settings reloaded (press Connect again to use new motor values)")

    def save(self):
        be.save_raw(self.raw)

    # ------------------------------------------------------------------ boards

    def _role_of(self, b: be.Board) -> str:
        a = self.raw["app"]
        by_port = a.get("role_by_port") or {}
        if b.port in by_port:
            return KEY_ROLE.get(by_port[b.port], "not used")
        ids = [x.motor_id for x in self.boards]
        if b.motor_id is not None and ids.count(b.motor_id) == 1:
            r = (a.get("scan_role_by_id") or {}).get(b.motor_id)
            return KEY_ROLE.get(r, "not used")
        return "not used"

    def find_boards(self):
        if self.ctl.connected and not self.ctl.simulated:
            self.ctl.disconnect()
        self.run_bg("Finding boards", lambda: be.scan_boards(log=self.log), self._show_boards)

    def _show_boards(self, boards):
        self.boards = boards
        for w in self.board_box.winfo_children():
            w.destroy()
        self.role_vars = {}
        ufp_boards = [b for b in boards if b.motor_id is not None]
        if not ufp_boards:
            ttk.Label(self.board_box, wraplength=420, foreground="#b91c1c",
                      text="No board answered. USB ports seen: "
                           + (", ".join(f"{b.port} ({b.error})" for b in boards) or "none")
                           + ". Close every other program that uses the boards (Arduino IDE, serial "
                             "monitor, a second window of this app, Hector's or Tudor's scripts), "
                             "replug the boards and press Find boards again.").pack(anchor="w")
            return
        hdr = ttk.Frame(self.board_box)
        hdr.pack(fill="x")
        for t, w in (("port", 10), ("MOTOR_ID", 9), ("", 7), ("is", 12)):
            ttk.Label(hdr, text=t, width=w, foreground="#666").pack(side="left")
        for b in ufp_boards:
            r = ttk.Frame(self.board_box)
            r.pack(fill="x", pady=1)
            ttk.Label(r, text=b.port, width=10).pack(side="left")
            ttk.Label(r, text=str(b.motor_id), width=9).pack(side="left")
            ttk.Button(r, text="turn", width=6, command=lambda b=b: self.turn(b)).pack(side="left")
            v = tk.StringVar(value=self._role_of(b))
            cb = ttk.Combobox(r, textvariable=v, values=ROLES, width=12, state="readonly")
            cb.pack(side="left", padx=4)
            cb.bind("<<ComboboxSelected>>", lambda e, b=b: self._role_changed(b))
            self.role_vars[b.port] = v
        ttk.Label(self.board_box, foreground="#666",
                  text="'turn' shows which motor it is. Saved by MOTOR_ID.").pack(anchor="w")
        self._save_roles()

    def _role_changed(self, b):
        v = self.role_vars[b.port].get()
        if v != "not used":                       # one board per role
            for port, other in self.role_vars.items():
                if port != b.port and other.get() == v:
                    other.set("not used")
        self._save_roles()

    def _save_roles(self):
        a = self.raw["app"]
        by_id = {int(k): v for k, v in (a.get("scan_role_by_id") or {}).items()}
        by_port = {}
        ids = [x.motor_id for x in self.boards]
        for b in self.boards:
            if b.port not in self.role_vars:
                continue
            key = ROLE_KEY.get(self.role_vars[b.port].get())
            if ids.count(b.motor_id) > 1:         # two boards with the same MOTOR_ID: remember by port
                if key:
                    by_port[b.port] = key
                continue
            for i in [i for i, r in by_id.items() if r == key or i == b.motor_id]:
                by_id.pop(i)
            if key:
                by_id[b.motor_id] = key
        a["scan_role_by_id"] = by_id
        a["role_by_port"] = by_port
        self.save()

    def turn(self, b):
        if self.ctl.connected and not self.ctl.simulated:
            self.log("disconnecting motors so the port is free for 'turn'…")
            self.ctl.disconnect()
            self.ctl.abort.clear()
            self._update_status()
        role = ROLE_KEY.get(self.role_vars[b.port].get()) if b.port in self.role_vars else None
        cur = be.motor_currents(self.raw)
        c = cur.get(role, min(cur.values()))
        import time as _time
        def _wiggle():
            _time.sleep(0.5)          # let macOS release the serial port after disconnect
            be.wiggle_port(b.port, current=c, steps=50)
        self.run_bg(f"Turning {b.port}", _wiggle)

    def _assigned(self):
        """{role key: Board} from the board list."""
        out = {}
        for b in self.boards:
            v = self.role_vars.get(b.port)
            key = ROLE_KEY.get(v.get()) if v else None
            if key:
                out[key] = b
        return out

    # ------------------------------------------------------------------ connect, home, move

    def connect(self):
        if not self.boards:                       # first time: find the boards, then connect
            def found(boards):
                self._show_boards(boards)
                if {"a", "b"} <= set(self._assigned()):
                    self.after(100, self.connect)
                elif boards:
                    messagebox.showinfo("Boards", "Choose which board is gantry A and gantry B (and the "
                                                  "syringes) in the list on the left, then press Connect.")
            self.run_bg("Finding boards", lambda: be.scan_boards(log=self.log), found)
            return
        got = self._assigned()                    # read the choices here, in the window's thread
        if not {"a", "b"} <= set(got):
            messagebox.showinfo("Boards", "Choose which board is gantry A and which is gantry B in the board "
                                          "list first ('turn' shows which motor it is).")
            return
        raw = copy.deepcopy(self.raw)
        u = raw["ufp"]
        for key, b in got.items():
            if key in ("a", "b"):
                u["xy_motors"][key] = {"port": b.port, "id": b.motor_id}
            else:
                u["plungers"][int(key[1:])] = {"port": b.port, "id": b.motor_id}
        syringes = [k for k in got if k.startswith("e")]
        for n in list(u["plungers"]):             # syringes without a board: a port name that is never opened
            if f"e{n}" not in syringes:
                u["plungers"][n] = {"port": f"none-{n}", "id": None}

        def done(_):
            self.raw["ufp"]["xy_motors"], self.raw["ufp"]["plungers"] = u["xy_motors"], u["plungers"]
            self.save()
            if syringes:
                self.sq_syr.set(sorted(syringes)[0][1:])
            self.log(f"connected: gantry A {got['a'].port}, B {got['b'].port}, syringes "
                     f"{', '.join(s[1:] for s in syringes) or 'none'}")
        self.run_bg("Connecting", lambda: self.ctl.connect(raw, simulated=False, syringes=syringes), done)

    def _current_changed(self):
        a = self.raw["app"]
        old = be.motor_currents(self.raw)
        new = {m: be.safe_current(self._f(v, old[m], 0.0, be.MAX_CURRENT)) for m, v in self.cur_vars.items()}
        for m, v in self.cur_vars.items():
            v.set(f"{new[m]:g}")                      # show the value really used (0.99 at most)
        if new == old and not a.get("usb_power_only"):
            return
        a["usb_power_only"] = False
        a["motor_currents"] = new
        self.save()
        if self.ctl.connected and not self.ctl.simulated and not self.busy:
            try:
                self.ctl.apply_currents(self.raw)      # at once, no reconnect
                return
            except Exception as e:
                self.log(f"could not set the currents now ({e}); they are used at the next Connect")
        self.log("currents: " + ", ".join(f"{m} {c:g}" for m, c in a["motor_currents"].items()))

    def disconnect(self):
        self.ctl.stop()
        self.ctl.disconnect()
        self._update_status()

    def _need_conn(self):
        if not self.ctl.connected or self.ctl.simulated:
            messagebox.showinfo("Not connected", "Press Connect first.")
            return False
        return True

    def home(self):
        if not self._need_conn():
            return
        t = self.raw["machine"]["travel_limits"]
        if not messagebox.askyesno("Home", f"Tudor's homing: +X until the X switch (= x {t['x_max']:g}), back to "
                                           f"x {t['x_min']:g}, then -Y until the Y switch (= y {t['y_min']:g}).\n\n"
                                           "STOP or Esc stops it. Start?"):
            return
        self.run_bg("Homing", lambda: self.ctl.home(self.ctl.raw))

    def jog(self, dx, dy):
        if not self._need_conn():
            return
        d = self._f(self.jog_mm, 10, 0.0, 500.0)
        v = 20.0 * be.speed_pct(self.raw) / 100
        self.run_bg("Moving", lambda: self.ctl.jog_xy(dx * d, dy * d, v))

    def jog_syr(self, n, sign):
        if not self._need_conn():
            return
        name = f"e{n}"
        if name not in dict(self.ctl.machine.syringes.items()):
            messagebox.showinfo("Syringe", f"Syringe {n} is not connected (choose its board in the list).")
            return
        steps = sign * self._f(self.syr_steps, 50, 0.0, 5000.0)
        backlash = float(self.raw["app"].get("backlash", 0) or 0)
        self.run_bg(f"Syringe {n}", lambda: self.ctl.jog_syringe(name, steps, backlash))

    def zero_syr(self, n):
        if not self._need_conn():
            return
        name = f"e{n}"
        if name in dict(self.ctl.machine.syringes.items()):
            self.ctl.zero_syringe(name)

    def stop(self):
        self.ctl.stop()
        self.log("STOP")

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

    def open_design(self):
        path = filedialog.askopenfilename(title="Picture or SVG", filetypes=[
            ("Picture or SVG", "*.svg *.png *.jpg *.jpeg *.bmp *.webp *.gif *.tif *.tiff"), ("All files", "*.*")])
        if not path:
            return
        raw = copy.deepcopy(self.raw)
        syr = self._syringe_for(path)

        def work():
            svg = Path(path)
            if svg.suffix.lower() in IMAGES:
                self.log(f"making 3 colours from {svg.name} ...")
                svg, _, _ = be.convert_photo(svg, raw)
            return self._plan(svg, raw, syr)
        self.run_bg("Planning", work, self._show_plan)

    def free_draw(self):
        DrawWindow(self)

    def use_drawing(self, svg):
        raw = copy.deepcopy(self.raw)
        syr = self._syringe_for(svg)
        self.log(f"drawing saved as {svg}")
        self.run_bg("Planning", lambda: self._plan(svg, raw, syr), self._show_plan)

    def _syringe_for(self, svg):
        """Which syringe prints this file: test squares their own, the offset test all three,
        everything else the 'all with syringe' field (empty = by colour, Aaron's colors.py)."""
        name = Path(svg).name
        if name.startswith("offset_test"):
            return None
        if name.startswith("test_square"):
            return int(self._f(self.sq_syr, 0, 0, 2))
        ds = self.raw["app"].get("design_syringe")
        return None if ds is None else int(ds)

    @staticmethod
    def _plan(svg, raw, syringe, park_at="park"):
        """Runs in the worker thread: no Tk variables here (read them before, in the window's thread)."""
        return be.plan_design(svg, raw, park_at=be.park_point(raw) if park_at == "park" else park_at,
                              syringe=syringe)

    def _replan(self):
        """Plan the open design again with the current settings."""
        if self.plan is None:
            return
        raw, svg = copy.deepcopy(self.raw), self.plan.svg
        syr = self._syringe_for(svg)
        self.run_bg("Planning", lambda: self._plan(svg, raw, syr), self._show_plan)

    def set_design_syringe(self):
        txt = self.design_syr.get().strip()
        old = self.raw["app"].get("design_syringe")
        new = None if txt == "" else int(self._f(self.design_syr, 0, 0, 2))
        self.design_syr.set("" if new is None else str(new))
        if new == old:
            return
        self.raw["app"]["design_syringe"] = new
        self.save()
        self.log("designs: " + ("every colour to its own syringe (by colour)" if new is None
                                else f"everything printed with syringe {new}"))
        self._replan()

    def _speed_info(self):
        f = be.speed_pct(self.raw) / 100
        pr = self.raw["print"]
        self.speed_info.configure(text=f"print {float(pr['print_speed']) * f:g}, travel {float(pr['travel_speed']) * f:g}, "
                                       f"arrows {20 * f:g} mm/s")

    def set_speed(self):
        """Overall speed in %: print and travel speed of every design and the arrow moves. Homing keeps
        Tudor's 20 mm/s."""
        v = self._f(self.speed_var, be.speed_pct(self.raw), 5.0, 300.0)
        self.speed_var.set(f"{v:g}")
        if v == be.speed_pct(self.raw) and "speed_pct" in self.raw["app"]:
            return
        self.raw["app"]["speed_pct"] = v
        self.save()
        self._speed_info()
        self.log(f"speed {v:g} %")
        self._replan()

    def _push_info(self):
        est = be.estimates.syringe_estimates(be.syringe_inputs(self.raw))
        v = float(self.raw["ufp"]["plunger_steps_per_mm"])
        self.push_info.configure(text=f"= {v * 100 * est['ml_per_step']:.2f} ml / 100 mm")

    def set_push(self):
        """Syringe numbers. push: steps per mm the gantry draws (ufp.plunger_steps_per_mm, Aaron's
        motion.py: plunger steps = line length x push). retract: steps pulled back after every line
        (anti drip). backlash: slack of nut and plunger that is lost at every change of direction.
        Tudor's syringe cycle pushes `retract_steps` before a line (prime) and pulls them back after
        it, so retract + backlash goes into ufp.retract_steps: the effective pull back stays `retract`
        and the prime takes up the slack before batter comes out."""
        try:
            v, r, b = (float(x.get().replace(",", ".")) for x in (self.push_var, self.retract_var, self.backlash_var))
            if min(v, r, b) < 0:
                raise ValueError
        except ValueError:
            messagebox.showerror("Syringe", "Enter numbers >= 0 (push in steps per mm, retract and backlash in steps).")
            return
        u, a = self.raw["ufp"], self.raw["app"]
        u["plunger_steps_per_mm"] = round(v, 5)
        a["retract"], a["backlash"] = r, b
        u["retract_steps"] = float(round(r + b))          # whole steps (Hector)
        try:
            be.build_config(self.raw)
        except Exception as e:
            messagebox.showerror("Syringe", str(e))
            return
        self.save()
        self._push_info()
        if self.ctl.connected:                    # takes effect at once on the connected syringes (Tudor's Syringe)
            for _, syr in self.ctl.machine.syringes.items():
                syr.retract_steps = u["retract_steps"]
        self.log(f"syringe: push {v:g} steps per mm, retract {r:g} + backlash {b:g} = {u['retract_steps']:g} steps "
                 "pulled back after every line and pushed before the next")
        self._replan()

    def offset_test(self):
        raw = copy.deepcopy(self.raw)

        def work():
            svg = be.make_offset_test_svg(raw)
            self.log("offset test: syringe 0 outer square 50 mm, syringe 1 40 mm, syringe 2 30 mm, same centre. "
                     "Measure from the outer square: gaps should be 5 mm (syringe 1) and 10 mm (syringe 2) on all "
                     "sides. x error = (left gap - right gap) / 2, y error = (front gap - back gap) / 2: add the "
                     "error to that syringe's offset and press Set.")
            return self._plan(svg, raw, None)
        self.run_bg("Planning", work, self._show_plan)

    def mark_nozzle(self, n):
        """Offset by eye: put the tip of syringe 0 over a mark (a dot, a cross on the griddle), press
        'syringe 0 is on it', then move until syringe 1 (or 2) is over the same mark and press its
        button. Same bed point: gantry0 + offset0 = gantryN + offsetN (Aaron's to_machine)."""
        if not self._need_conn():
            return
        x, y, _, _ = self.ctl.position()
        if n == 0:
            self._mark0 = (x, y)
            self.log(f"syringe 0 on the mark at gantry ({x:.2f}, {y:.2f}). Now move syringe 1 or 2 over the same mark.")
            return
        if self._mark0 is None:
            messagebox.showinfo("Offsets", "First put syringe 0 over the mark and press 'syringe 0 is on it'.")
            return
        o0 = next(z["offset"] for z in self.raw["nozzles"] if int(z["id"]) == 0)
        ox = float(o0[0]) + self._mark0[0] - x
        oy = float(o0[1]) + self._mark0[1] - y
        self.off_vars[n].set(f"{ox:.2f}, {oy:.2f}")
        self.log(f"syringe {n}: offset {ox:.2f}, {oy:.2f} mm (gantry moved {x - self._mark0[0]:+.2f}, "
                 f"{y - self._mark0[1]:+.2f} from syringe 0)")
        self.set_offsets()

    def set_offsets(self):
        """Nozzle offsets of syringes 1 and 2 relative to syringe 0 (nozzles[].offset, used by Aaron's
        config.to_machine: gantry = bed point - offset)."""
        try:
            new = {}
            for n, v in self.off_vars.items():
                x, y = (float(t) for t in v.get().replace(";", ",").split(","))
                new[n] = [round(x, 2), round(y, 2)]
        except ValueError:
            messagebox.showerror("Offsets", "Write each offset as x, y in mm, e.g. 15, 0")
            return
        for z in self.raw["nozzles"]:
            if int(z["id"]) in new:
                z["offset"] = new[int(z["id"])]
        try:
            be.build_config(self.raw)
        except Exception as e:
            messagebox.showerror("Offsets", str(e))
            return
        self.save()
        self.log("nozzle offsets: " + ", ".join(f"syringe {n}: {o[0]:g}, {o[1]:g}" for n, o in new.items()))
        self._replan()

    def test_square(self):
        n = int(self._f(self.sq_syr, 0, 0, 2))
        size = self._f(self.sq_size, 40, 2.0, 300.0)
        raw = copy.deepcopy(self.raw)
        color = next(z["color"] for z in raw["nozzles"] if int(z["id"]) == n)

        def work():
            svg = be.make_square_svg(size, color)
            self.log(f"test square {size:g} mm for syringe {n}: {svg.name}")
            return self._plan(svg, raw, n)
        self.run_bg("Planning", work, self._show_plan)

    def print_here(self):
        if self.plan is None:
            messagebox.showinfo("Print here", "Open a picture or SVG, or make a test square, first.")
            return
        if not self._need_conn() or not self._syringes_ok():
            return
        plan, raw = self.plan, copy.deepcopy(self.raw)
        n = be.first_nozzle(plan)
        sx, sy = be.here_point(plan)
        xs = [st.x - sx for st in plan.steps if isinstance(st, be.XYMove)][:-1] or [0.0]   # without the park move
        ys = [st.y - sy for st in plan.steps if isinstance(st, be.XYMove)][:-1] or [0.0]
        left, right, front, back = max(0, -min(xs)), max(0, max(xs)), max(0, -min(ys)), max(0, max(ys))
        if not messagebox.askyesno("Print here", f"No homing: the nozzle of syringe {n} must stand over the MIDDLE "
                                   f"of where the design goes (move it there with the arrows first).\n\n"
                                   f"From this spot the gantry moves up to {left:.0f} mm left, {right:.0f} mm right, "
                                   f"{front:.0f} mm to the front and {back:.0f} mm to the back (design plus nozzle "
                                   "offsets). It comes back to this spot at the end. STOP or Esc stops it.\n\nStart?"):
            return
        self.ctl.raw["app"]["colour_change"] = "button"
        on_progress, on_pause = self._callbacks()
        syr = self._syringe_for(plan.svg)

        def work():
            start = be.here_point(plan)
            plan2 = self._plan(plan.svg, raw, syr, park_at=start)   # end where it started
            self.ctl.print_here(plan2, start, on_progress, on_pause)
        self.run_bg("Printing here", work, lambda r: self.log("print finished, back at the start spot"))

    def _syringes_ok(self):
        need = sorted({s.motor for s in self.plan.steps if isinstance(s, be.Extrude)})
        have = set(dict(self.ctl.machine.syringes.items()))
        missing = [m for m in need if m not in have]
        if missing and len(have) == 1 and not self.plan.svg.name.startswith("offset_test"):
            one = sorted(have)[0][1:]
            if messagebox.askyesno("Print", "This design uses syringe(s) " + ", ".join(m[1:] for m in need)
                                   + f" by its colours, but only syringe {one} is connected.\n\n"
                                   f"Print everything with syringe {one}? (Then press Print again.)"):
                self.design_syr.set(one)
                self.set_design_syringe()
            return False
        if missing:
            messagebox.showerror("Print", "This design needs syringe(s) " + ", ".join(m[1:] for m in missing)
                                 + ", which are not connected. Choose their boards in the list and Connect again"
                                 + (", or pick the connected syringe for the test square." if "test_square" in
                                    self.plan.svg.name else "."))
            return False
        return True

    def _draw_empty(self):
        cfg = be.build_config(self.raw)
        self._draw_bed(cfg)
        self.canvas.draw_idle()

    def _draw_bed(self, cfg):
        ax = self.ax
        ax.clear()
        t, p = cfg.travel_limits, cfg.print_area
        ax.add_patch(__import__("matplotlib.patches", fromlist=["Rectangle"]).Rectangle(
            (t.x_min, t.y_min), t.x_max - t.x_min, t.y_max - t.y_min, fill=False, ec="#94a3b8", ls="--"))
        ax.add_patch(__import__("matplotlib.patches", fromlist=["Rectangle"]).Rectangle(
            (p.x_min, p.y_min), p.x_max - p.x_min, p.y_max - p.y_min, fc="#fef3c7", ec="#d97706"))
        ax.set_xlim(t.x_min - 10, t.x_max + 10)
        ax.set_ylim(t.y_min - 10, t.y_max + 10)
        ax.set_aspect("equal")
        ax.set_xlabel("X mm")
        ax.set_ylabel("Y mm")

    def _show_plan(self, plan):
        self.plan = plan
        cfg = plan.cfg
        self._draw_bed(cfg)
        for n, s in plan.strokes:
            self.ax.plot(s[:, 0], s[:, 1], color=cfg.nozzles[n].color, lw=2.5, solid_capstyle="round")
        for _, t in plan.travels:
            self.ax.plot(t[:, 0], t[:, 1], color="#60a5fa", lw=0.6, ls="--")
        if plan.strokes:                          # zoom to the design, so small tests are readable
            import numpy as np
            a = np.vstack([s for _, s in plan.strokes])
            x0, x1, y0, y1 = a[:, 0].min(), a[:, 0].max(), a[:, 1].min(), a[:, 1].max()
            half = max(x1 - x0, y1 - y0) / 2 + 15
            cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
            self.ax.set_xlim(cx - half, cx + half)
            self.ax.set_ylim(cy - half, cy + half)
        self.ax.set_title(plan.svg.name + "  (on the griddle, seen from above)")
        self.canvas.draw_idle()
        s = plan.summary
        ml = ", ".join(f"syringe {k[1:]}: {v:.1f} ml" for k, v in sorted(s["batter_ml"].items()))
        self.summary.configure(text=f"{s['strokes']} lines, {s['print_mm']:.0f} mm, about {s['time_s'] / 60:.1f} min.  "
                                    f"Batter: {ml}")
        self.log(f"planned {plan.svg.name}")

    def _callbacks(self):
        def on_progress(i, n, step):
            self.ui(lambda: self.progress.configure(value=i / max(n, 1)))
            if isinstance(step, be.Extrude):           # so you can see which syringe should move, and how much
                self.log(f"line: syringe {step.motor[1:]} pushes {step.steps:g} steps over {step.duration:.1f} s")

        def on_pause(message, mode, wait_s):
            def ask():
                if messagebox.askokcancel("Colour change", f"{message}\n\nOK = continue, Cancel = stop the print."):
                    self.ctl.resume.set()
                else:
                    self.stop()
            self.ui(ask)
        return on_progress, on_pause

    def dry_run(self):
        if self.plan is None:
            messagebox.showinfo("Dry run", "Open a picture or SVG first.")
            return
        plan, raw = self.plan, copy.deepcopy(self.raw)
        on_progress, _ = self._callbacks()

        def work():
            sim = be.Controller(log=self.log)
            sim.connect(raw, simulated=True)
            try:
                sim.run(plan, on_progress=on_progress, on_pause=lambda *a: sim.resume.set())
            finally:
                sim.disconnect()
        self.run_bg("Dry run", work, lambda r: self.log("dry run finished without errors"))

    def print_now(self):
        if self.plan is None:
            messagebox.showinfo("Print", "Open a picture or SVG first.")
            return
        if not self._need_conn():
            return
        if not self.ctl.homed:
            messagebox.showinfo("Print", "Press Home first.")
            return
        if not self._syringes_ok():
            return
        if not messagebox.askyesno("Print", f"Print {self.plan.svg.name} now? STOP or Esc stops it."):
            return
        self.ctl.raw["app"]["colour_change"] = "button"
        on_progress, on_pause = self._callbacks()
        self.run_bg("Printing", lambda: self.ctl.run(self.plan, on_progress, on_pause),
                    lambda r: self.log("print finished"))

    def on_close(self):
        try:
            self.ctl.stop()
            self.ctl.disconnect()
        finally:
            self.destroy()


class DrawWindow(tk.Toplevel):
    """Free drawing with the mouse on the print area, one colour (= syringe) per line. 'Use drawing'
    saves it as an SVG (in mm) and sends it through the same pipeline as a picture or SVG; like every
    design it is centred in the print area (PRINT HERE: around the nozzle)."""

    def __init__(self, app: SimpleApp):
        super().__init__(app)
        self.app = app
        self.title("Draw")
        cfg = be.build_config(app.raw)
        pa = cfg.print_area
        self.w_mm, self.h_mm = pa.x_max - pa.x_min, pa.y_max - pa.y_min
        k = app.winfo_fpixels("1i") / 96
        self.k = min(900 * k / self.w_mm, 560 * k / self.h_mm)        # px per mm
        self.noz = {int(z["id"]): z["color"] for z in app.raw["nozzles"]}
        self.lw = max(2.0, float(app.raw["print"]["line_width"]) * self.k)
        self.strokes: list[tuple[int, list[tuple[float, float]]]] = []   # (syringe, points in mm, y down)
        self.items: list[list[int]] = []
        self.syr = tk.IntVar(value=int(app._f(app.sq_syr, 0, 0, 2)))

        bar = ttk.Frame(self, padding=6)
        bar.pack(fill="x")
        ttk.Label(bar, text="draw with").pack(side="left")
        for n, c in sorted(self.noz.items()):
            tk.Radiobutton(bar, text=f"syringe {n}", variable=self.syr, value=n, indicatoron=False,
                           bg=c, selectcolor=c, fg="white" if n == 0 else "black", padx=8, pady=2,
                           font=("Segoe UI", 10, "bold")).pack(side="left", padx=3)
        ttk.Button(bar, text="Undo", command=self.undo).pack(side="left", padx=(16, 3))
        ttk.Button(bar, text="Clear", command=self.clear).pack(side="left")
        ttk.Button(bar, text="Use drawing", style="Big.TButton", command=self.use).pack(side="right")
        self.info = ttk.Label(bar, foreground="#666")
        self.info.pack(side="right", padx=10)
        self.cv = tk.Canvas(self, width=int(self.w_mm * self.k), height=int(self.h_mm * self.k), bg="#fef3c7",
                            highlightthickness=1, highlightbackground="#d97706", cursor="pencil")
        self.cv.pack(padx=8, pady=(0, 8))
        for x in range(0, int(self.w_mm) + 1, 10):                       # 10 mm grid
            self.cv.create_line(x * self.k, 0, x * self.k, self.h_mm * self.k, fill="#fde68a")
        for y in range(0, int(self.h_mm) + 1, 10):
            self.cv.create_line(0, y * self.k, self.w_mm * self.k, y * self.k, fill="#fde68a")
        self.cv.bind("<ButtonPress-1>", self.down)
        self.cv.bind("<B1-Motion>", self.move)
        self.cv.bind("<ButtonRelease-1>", self.up)
        self.bind("<Control-z>", lambda e: self.undo())
        self._update_info()

    def down(self, e):
        n = self.syr.get()
        self.strokes.append((n, [(e.x / self.k, e.y / self.k)]))
        self.items.append([])

    def move(self, e):
        if not self.strokes:
            return
        n, pts = self.strokes[-1]
        x, y = e.x / self.k, e.y / self.k
        x, y = min(max(x, 0.0), self.w_mm), min(max(y, 0.0), self.h_mm)
        if (x - pts[-1][0]) ** 2 + (y - pts[-1][1]) ** 2 < 1.0:       # keep points 1 mm apart
            return
        x0, y0 = pts[-1]
        self.items[-1].append(self.cv.create_line(x0 * self.k, y0 * self.k, x * self.k, y * self.k,
                                                  fill=self.noz[n], width=self.lw, capstyle="round"))
        pts.append((x, y))

    def up(self, e):
        if self.strokes and len(self.strokes[-1][1]) < 2:          # a click without a line
            self.strokes.pop()
            self.items.pop()
        self._update_info()

    def undo(self):
        if self.strokes:
            self.strokes.pop()
            for i in self.items.pop():
                self.cv.delete(i)
        self._update_info()

    def clear(self):
        while self.strokes:
            self.undo()

    def _update_info(self):
        mm = sum(sum(((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2) ** 0.5 for a, b in zip(p, p[1:])) for _, p in self.strokes)
        self.info.configure(text=f"{len(self.strokes)} lines, {mm:.0f} mm  (grid 10 mm, Ctrl+Z = undo)")

    def use(self):
        if not self.strokes:
            messagebox.showinfo("Draw", "Draw something first (hold the left mouse button).", parent=self)
            return
        import time
        be.OUT_DIR.mkdir(parents=True, exist_ok=True)
        path = be.OUT_DIR / f"drawing_{time.strftime('%H%M%S')}.svg"
        lines = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{self.w_mm:g}mm" height="{self.h_mm:g}mm" '
                 f'viewBox="0 0 {self.w_mm:g} {self.h_mm:g}">']
        for n, pts in self.strokes:
            pp = " ".join(f"{x:.2f},{y:.2f}" for x, y in pts)
            lines.append(f'  <polyline points="{pp}" stroke="{self.noz[n]}" fill="none"/>')
        lines.append("</svg>")
        path.write_text("\n".join(lines) + "\n", encoding="utf-8")
        self.destroy()
        self.app.use_drawing(path)


if __name__ == "__main__":
    SimpleApp().mainloop()
