"""Run planned steps (motion.py) on the machine, through the firmware wrappers.

    XY gantry -> firmware/xy_stage_wrapper.XYStage     (homing, workspace checks, mm units, CoreXY transform)
    syringes  -> firmware/syringe_wrapper.SyringeBank   (one board per colour, one used at a time, prime / extrude / retract)

This file only maps `Step`s onto wrapper calls and owns the lifecycle (connect, home, stop, close).
It never talks to `ufp` or to a board directly. The wrapper modules are imported inside the
functions, so planning and the tests that do not touch a machine work without `ufp` installed.

Coordinates: the planner works in MACHINE coordinates. The wrapper's (0, 0) is where the homed
stage sits, which is machine position `ufp.home_offset`: stage = machine - home_offset.
"""
import time
from types import SimpleNamespace

import firmware_link  # noqa: F401  (puts ../firmware on sys.path)
from config import MachineConfig, MotorBoard, UfpSettings
from motion import Extrude, Pause, Prime, Retract, Step, Wait, XYMove


def board_spec(u: UfpSettings, name: str) -> MotorBoard: # 'a' / 'b' -> CoreXY motor, 'e<N>' -> plunger of nozzle N.
    return u.xy_motors[name] if name in ("a", "b") else u.plungers[int(name[1:])]


def plungers_used(steps: list[Step]) -> list[str]: # names of the syringe motors the steps need
    return sorted({s.motor for s in steps if isinstance(s, (Prime, Extrude, Retract))})


def motors_used(steps: list[Step]) -> list[str]: # all motors the steps need
    return ["a", "b"] + plungers_used(steps)


class Machine:
    """The gantry and the syringes, connected. Use `open_machine`, and close() when done."""

    def __init__(self, u: UfpSettings, stage, syringes):
        self.u, self.stage, self.syringes = u, stage, syringes
        self.sim = None         # set by simulated_machine

    @property
    def xy(self) -> tuple[float, float]:
        """Gantry position in MACHINE coordinates."""
        x, y = self.stage.get_xy()
        return x + self.u.home_offset[0], y + self.u.home_offset[1]

    def move_xy(self, m: XYMove) -> None:
        ox, oy = self.u.home_offset
        self.stage.move_to(m.x - ox, m.y - oy, v=m.v, a=m.a, wait=True)

    def prime(self, m: Prime) -> None:
        self.syringes.prime(m.motor)

    def extrude(self, m: Extrude) -> None:
        self.syringes.extrude(m.motor, m.steps, m.duration)    # returns at once, the stroke's XY moves run meanwhile

    def retract(self, m: Retract) -> None:
        self.syringes.retract(m.motor)                         # waits for the extrusion, then pulls back

    def stop(self) -> None:
        """Emergency stop: ramp every motor to zero speed. Best effort, never raises."""
        try:
            self.stage.stop(a=self.u.emergency_decel)
        except Exception:
            pass
        self.syringes.stop()

    def close(self) -> None:
        """Stop, cut the coil current (no heat / power waste) and close the ports. Best effort."""
        try:
            self.stage.close()
        except Exception:
            pass
        self.syringes.close()

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self.close()


def open_machine(cfg: MachineConfig, plunger_names=(), target=None) -> Machine:
    """Connect, check every MOTOR_ID, then home the XY stage (it MOVES: both carriages run to their
    limit switches). A syringe has no switch: its position at connect is 0 (retracted).
    The stage may use the whole of machine.travel_limits (`cfg.stage_limits`).

    target: optional function motor name ('a', 'b', 'e0', ...) -> address (port, "tcp://...", or a
    ufp.Device); default is the port from the config.
    """
    from syringe_wrapper import SyringeBank
    from xy_stage_wrapper import XYStage

    u = cfg.ufp
    x_limits, y_limits = cfg.stage_limits
    target = target or (lambda name: board_spec(u, name).port)
    # syringes first: a wrong board is found before anything moves
    syringes = SyringeBank.connect({n: target(n) for n in plunger_names},
                                   expected_ids={n: board_spec(u, n).id for n in plunger_names},
                                   retract_steps=u.retract_steps, speed=u.plunger_speed, accel=u.plunger_accel,
                                   travel=u.plunger_travel, coil_current=u.current)
    try:
        stage = XYStage(target("a"), target("b"), mm_per_step=u.mm_per_step_pair,
                        x_limits=x_limits, y_limits=y_limits, coil_current=u.current,
                        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))
    except BaseException:
        syringes.close()
        raise
    return Machine(u, stage, syringes)


def simulated_machine(cfg: MachineConfig, plunger_names=(), time_scale: float = 50.0) -> Machine:
    """A Machine over the firmware's simulated boards, for --dry-run and the tests. Runs
    `time_scale` times faster than real time, so a dry run does not take as long as the print.
    `machine.sim.xy` / `machine.sim.syringes` give access to the simulators."""
    from simulated_stepper import SimulatedStepper
    from simulated_xy_stage import SimulatedXYStage, fast_clock

    u = cfg.ufp
    ids = {n: board_spec(u, n).id for n in ("a", "b")}
    xy = SimulatedXYStage(mm_per_step=u.mm_per_step_pair, time_scale=time_scale,
                          reversed_a=u.invert_a, reversed_b=u.invert_b,
                          id_a=ids["a"] if ids["a"] is not None else 1, id_b=ids["b"] if ids["b"] is not None else 2)
    clock = fast_clock(time_scale)
    sims = {n: SimulatedStepper(start_position=0.0, motor_id=board_spec(u, n).id or 0, clock=clock)
            for n in plunger_names}
    devices = {"a": xy.device_a, "b": xy.device_b, **{n: s.device for n, s in sims.items()}}
    machine = open_machine(cfg, plunger_names, target=devices.__getitem__)
    machine.sim = SimpleNamespace(xy=xy, syringes=sims)
    return machine


def run(steps: list[Step], machine: Machine, on_progress=None, on_pause=None) -> None:
    for i, s in enumerate(steps): # iterate through the steps and send them to the machine
        if isinstance(s, XYMove):
            machine.move_xy(s)
        elif isinstance(s, Prime):
            machine.prime(s)
        elif isinstance(s, Extrude):
            machine.extrude(s)
        elif isinstance(s, Retract):
            machine.retract(s)
        elif isinstance(s, Wait):
            time.sleep(s.seconds)
        elif isinstance(s, Pause):
            if on_pause: # if on_pause is provided, call it with the pause message
                on_pause(s.message)
        if on_progress:
            on_progress(i + 1, len(steps))
    machine.syringes.wait()
