"""Single-axis wrapper around a UFP stepper board (arduino/UFP/examples/ufp_stepper).

Units: the public API is in millimetres (z in mm, vz in mm/s, az in mm/s^2).
The board speaks full steps. The conversion is `mm_per_step`, applied in
exactly two places (`_to_steps` and `_to_mm`), so nothing else in this file
deals with steps. `self.motor` is the raw UFP client (steps); the rest of the
class goes through the methods below instead of calling it directly.

    with StepperMotor("/dev/cu.usbmodem101", mm_per_step=0.04) as m:   # homes on connect
        m.set_z(20, wait=True)
        m.set_vz(5)
        ...
        m.stop()

An axis without a limit switch (a syringe plunger) is created with
`home_on_connect=False` and declared with `assume_homed()`.

Try it without hardware: `python single_stepper_selftest.py`.
"""

import time
from typing import NamedTuple

import ufp


class HomingError(RuntimeError):
    """The limit switch was not reached while homing."""


class WrongBoardError(RuntimeError):
    """The board on this port reports another MOTOR_ID than the one expected."""


class State(NamedTuple):
    z: float          # mm
    vz: float         # mm/s
    az: float         # mm/s^2
    is_moving: bool
    limit: bool       # True when the limit switch is open (see StepperMotor)


class StepperMotor:
    """One stepper axis. Homes towards the limit switch (negative direction) on connect.

    The limit switch is wired normally closed to GND with a pull-up, so the
    board reports `limit=True` when the switch is clicked *or* when nothing is
    connected to the pin. Without a switch, homing therefore ends immediately.

    The board does not stop at the limit switch by itself, and `set_vz` does not
    check z_min / z_max. Only `set_z` enforces the range.

    Args:
        target: serial port name, "tcp://host:port", or a ufp.Device (simulation).
        mm_per_step: millimetres of travel per full step (must be > 0).
        coil_current: fraction of full scale, 0..1 (no torque at 0).
        z_min, z_max: travel range in mm, enforced by `set_z`.
        z_switch: the z of the limit switch, where homing defines the position (default z_min).
            Give a z_min below it when the axis may travel past the switch.
        home_on_connect: run `home()` in the constructor.
        homing_timeout: seconds before homing gives up (default: derived from the range).
        timeout: UFP response timeout in seconds.
        invert: True if positive steps move the carriage *towards* the limit switch
            (the motor is wired the other way round). All public values stay in the
            z direction, away from the switch.
        expected_id: MOTOR_ID the board must report (checked before anything else is
            sent to it); WrongBoardError otherwise. None skips the check.
    """

    STOP_TIMEOUT = 3.0   # s, to come to a standstill after stop()

    def __init__(self, target, *, mm_per_step=1.0, coil_current=0.2, z_min=0.0, z_max=100.0,
                 home_on_connect=True, homing_timeout=None, timeout=1.0,
                 invert=False, expected_id=None, z_switch=None):
        if mm_per_step <= 0:
            raise ValueError(f"mm_per_step must be > 0, got {mm_per_step}")
        if z_max <= z_min:
            raise ValueError(f"z_max ({z_max}) must be greater than z_min ({z_min})")
        z_switch = z_min if z_switch is None else z_switch
        if not z_min <= z_switch <= z_max:
            raise ValueError(f"z_switch ({z_switch}) must lie within [{z_min}, {z_max}]")
        self._check_current(coil_current)

        self.mm_per_step = mm_per_step
        self.invert = bool(invert)
        self.z_min, self.z_max, self.z_switch = z_min, z_max, z_switch
        # presets, all in mm units
        self.a_slow, self.a_normal, self.a_fast = 200.0, 1000.0, 5000.0   # mm/s^2
        self.v_slow, self.v_normal, self.v_fast = 50.0, 200.0, 800.0      # mm/s
        self.poll_interval = 0.01   # s between get_states while waiting
        self.homing_timeout = (homing_timeout if homing_timeout is not None
                               else 1.5 * (z_max - z_switch) / self.v_normal + 2.0)
        self.coil_current = 0.0
        self.homed = False
        self._closed = False

        self.motor = ufp.connect(target, timeout=timeout)
        if expected_id is not None:
            self._verify_id(expected_id)
        try:
            self.set_current(coil_current)
            if home_on_connect:
                self.home()
        except BaseException:
            self.close()    # never leave the coils energized after a failed start
            raise

    # ---- units ------------------------------------------------------------

    def _to_steps(self, mm, *, signed=False):
        """mm -> steps. `signed` for positions and velocities, which follow the direction
        (flipped when `invert`); speed and acceleration limits are magnitudes."""
        steps = mm / self.mm_per_step
        return -steps if signed and self.invert else steps

    def _to_mm(self, steps):
        """steps -> mm, for readings (position, velocity, acceleration: all signed)."""
        mm = steps * self.mm_per_step
        return -mm if self.invert else mm

    def _verify_id(self, expected):
        try:
            found = self.motor.get_id()
        except BaseException:
            self._disconnect()
            raise
        if found != expected:
            self._disconnect()      # not the board we meant: do not send it anything else
            raise WrongBoardError(f"expected MOTOR_ID {expected}, the board reports {found}")

    def _disconnect(self):
        self._closed = True
        self.motor.close()

    @staticmethod
    def _check_current(current):
        if not 0 <= current <= 1:
            raise ValueError(f"current must be in 0..1, got {current}")

    # ---- lifecycle --------------------------------------------------------

    def close(self):
        """Stop, switch the coils off and disconnect. Safe to call twice."""
        if self._closed:
            return
        self._closed = True
        try:
            self.stop()
            self.wait(timeout=self.STOP_TIMEOUT)
        except (ufp.UfpError, OSError):   # includes ufp.Timeout and TimeoutError
            pass
        try:
            self.set_current(0)
        except (ufp.UfpError, OSError):
            pass
        self.motor.close()

    def __enter__(self):
        return self

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

    # ---- commands ---------------------------------------------------------

    def set_current(self, current):
        """Coil current as a fraction of full scale (0..1)."""
        self._check_current(current)
        self.motor.set_current(current)
        self.coil_current = current

    def set_vz(self, vz, az=None):
        """Ramp to a velocity (mm/s, sign = direction) and hold it. Does not check z limits."""
        az = self.a_normal if az is None else az
        if az <= 0:
            raise ValueError(f"az must be > 0, got {az}")
        self.motor.set_target_velocity(self._to_steps(vz, signed=True), self._to_steps(az))

    def set_z(self, z, vz=None, az=None, wait=False):
        """Move to z (mm) with a speed limit vz (mm/s) and acceleration az (mm/s^2).

        Raises ValueError for z outside [z_min, z_max] or non-positive vz/az,
        and RuntimeError if the axis has not been homed. With wait=True,
        returns once the move has finished.
        """
        vz = self.v_normal if vz is None else vz
        az = self.a_normal if az is None else az
        if not self.homed:
            raise RuntimeError("axis is not homed: call home() first")
        if not self.z_min <= z <= self.z_max:
            raise ValueError(f"z={z} is outside [{self.z_min}, {self.z_max}]")
        if vz <= 0 or az <= 0:
            raise ValueError(f"vz and az must be > 0, got vz={vz}, az={az}")
        z_start = self.get_z() if wait else None
        self.motor.set_target_position(self._to_steps(z, signed=True), self._to_steps(vz), self._to_steps(az))
        if wait:
            expected = abs(z - z_start) / vz + vz / az    # cruise + ramps, upper bound
            self.wait(timeout=2 * expected + 1.0)

    def stop(self):
        """Decelerate to a standstill as fast as the preset allows."""
        self.set_vz(0, self.a_fast)

    def redefine_z(self, z):
        """Declare the current position to be z (mm). Does not move."""
        self.motor.set_position(self._to_steps(z, signed=True))

    def assume_homed(self, z=0.0):
        """For an axis without a limit switch: declare the current position to be z (mm)
        and treat the axis as homed. Does not move. Use with `home_on_connect=False`."""
        if not self.z_min <= z <= self.z_max:
            raise ValueError(f"z={z} is outside [{self.z_min}, {self.z_max}]")
        self.redefine_z(z)
        self.homed = True

    def home(self):
        """Drive towards the limit switch, stop, and define that spot as z_switch.

        Raises HomingError (after stopping the motor) if the switch is not
        reached within `homing_timeout`.
        """
        self.homed = False
        if not self.limit():                     # already on the switch: nothing to do
            deadline = time.monotonic() + self.homing_timeout
            self.set_vz(-self.v_normal, self.a_normal)
            try:
                while not self.limit():
                    if time.monotonic() > deadline:
                        raise HomingError(f"limit switch not reached within {self.homing_timeout:.1f} s")
                    time.sleep(self.poll_interval)
            except BaseException:
                self.stop()
                raise
        self.stop()
        self.wait(timeout=self.STOP_TIMEOUT)     # only zero once we really stand still
        self.redefine_z(self.z_switch)
        self.homed = True

    def wait(self, timeout=None):
        """Block until the motor stands still; returns the final State.

        Raises TimeoutError after `timeout` seconds. Never returns while a
        velocity move (`set_vz` with vz != 0) is running, so pass a timeout or call stop().
        """
        deadline = None if timeout is None else time.monotonic() + timeout
        while True:
            state = self.get_states()
            if not state.is_moving:
                return state
            if deadline is not None and time.monotonic() >= deadline:
                raise TimeoutError(f"motor still moving after {timeout} s")
            time.sleep(self.poll_interval)

    # ---- readings ---------------------------------------------------------

    def get_states(self):
        """One consistent snapshot of the axis, in mm units."""
        s = self.motor.get_states()
        return State(self._to_mm(s.position), self._to_mm(s.velocity), self._to_mm(s.acceleration),
                     s.is_moving, s.limit)

    def is_moving(self):
        return self.get_states().is_moving

    def limit(self):
        return self.get_states().limit

    def get_z(self):
        return self.get_states().z

    def get_vz(self):
        return self.get_states().vz

    def get_az(self):
        return self.get_states().az
