"""Syringe plungers: one stepper board per syringe (one per colour), used one at a time.

A syringe rests *retracted*. Every stroke is the same three calls:

    prime()      push forward by `retract_steps`, taking up the slack the last retraction made
    extrude(n)   push n more steps, optionally spread over a given time: the batter flows
    retract()    pull back by `retract_steps` (anti-drip)

so every stroke begins by pushing exactly the amount the previous one pulled back, and the plunger
rests at (start + everything extruded). The calls are checked against that cycle: extruding before
priming, priming twice, or leaving the syringe's stroke raises `SyringeError` *before* the board is
sent anything.

    bank = SyringeBank.connect({"e0": "COM12", "e1": "COM13", "e2": "COM14"},
                               expected_ids={"e0": 3, "e1": 4, "e2": 5}, retract_steps=40)
    bank.prime("e1")                         # colour 1 only; e0 and e2 stay put
    bank.extrude("e1", 120, duration=3.0)    # returns at once; wait() or retract() waits for it
    bank.retract("e1")
    bank.close()

Units: plunger steps (full steps of the board; 200 per lead-screw turn). The limit switch sits at the
*forward* end of the stroke. Pushing into it stops the plunger, backs it off by `limit_backoff` steps
(one turn) and raises SyringeError; retreating from the switch is
always allowed, so the cycle can go on. Every call that moves the plunger blocks, polling the switch,
until the move is done. Only one syringe of a `SyringeBank` can be primed
at a time: priming another one before the first has retracted raises SyringeError.

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

import time

from motion_profile import flow_profile, trapezoid_time
from single_stepper_wrapper import StepperMotor, WrongBoardError

__all__ = ["Syringe", "SyringeBank", "SyringeError", "WrongBoardError"]

EPS = 1e-9   # steps


class SyringeError(RuntimeError):
    """A syringe command that is not allowed in the syringe's current state."""


class Syringe:
    """One syringe plunger.

    Args:
        target: serial port, "tcp://host:port", or a ufp.Device (simulation).
        retract_steps: how far to pull back after a stroke, and push before the next one.
        speed, accel: steps/s and steps/s^2 for prime and retract (and the limit of a flow move).
        travel: usable plunger stroke in steps; position 0 is where the plunger was at connect.
        coil_current: fraction of full scale, 0..1.
        limit_backoff: steps to pull back after the limit switch is hit (so the switch is released).
        expected_id: MOTOR_ID the board must report (WrongBoardError otherwise); None skips the check.
        timeout: UFP response timeout in seconds.
    """

    def __init__(self, target, *, retract_steps=200.0, speed=200.0, accel=1000.0, travel=100000.0,
                 coil_current=0.6, expected_id=None, timeout=1.0, limit_backoff=200.0):
        for name, value in (("speed", speed), ("accel", accel), ("travel", travel)):
            if value <= 0:
                raise ValueError(f"{name} must be > 0, got {value}")
        if not 0 <= retract_steps <= travel:
            raise ValueError(f"retract_steps must be in 0..travel ({travel}), got {retract_steps}")
        self.retract_steps = float(retract_steps)
        self.speed, self.accel, self.travel = float(speed), float(accel), float(travel)
        self.primed = False        # True from prime() to retract()
        self._target = 0.0         # commanded position, steps
        self.limit_backoff = float(limit_backoff)
        self._dir = 0              # direction of the running move: +1 towards the limit switch, -1 away
        self._busy = 0.0           # planned duration of the move that may still be running, s
        self.motor = StepperMotor(target, mm_per_step=1.0, coil_current=coil_current, z_min=0.0,
                                  z_max=self.travel, home_on_connect=False, timeout=timeout,
                                  expected_id=expected_id)
        try:
            self.motor.assume_homed(0.0)     # no limit switch: where the plunger is now is 0, retracted
        except BaseException:
            self.motor.close()
            raise

    # ---- the cycle --------------------------------------------------------

    def prime(self):
        """Push forward by `retract_steps`; returns when done."""
        if self.primed:
            raise SyringeError("already primed: retract() first (a stroke is prime, extrude, retract)")
        self.wait()
        self._push(self.retract_steps)
        self.primed = True
        self.wait()

    def extrude(self, steps, duration=None):
        """Push `steps` more. With `duration` (s) the move is paced to take that long, otherwise it
        runs at `speed`. Blocks, polling the limit switch, until the move is done."""
        if not self.primed:
            raise SyringeError("not primed: prime() first, so the plunger has taken up the slack")
        if steps < 0:
            raise ValueError(f"steps must be >= 0, got {steps}")
        if steps < EPS:
            return
        self.wait()
        v, a = (self.speed, self.accel) if duration is None else flow_profile(steps, duration, self.accel)
        self._push(steps, v, a)
        self.wait()

    def retract(self):
        """Pull back by `retract_steps` (after the running flow has finished); returns when done."""
        if not self.primed:
            raise SyringeError("not primed: there is nothing to retract")
        self.wait()
        self._push(-self.retract_steps)
        self.primed = False
        self.wait()

    def _push(self, delta, v=None, a=None):
        if delta > 0 and self.motor.limit():
            self._limit_backoff()          # already on the switch: only moving away is allowed
        v, a = v or self.speed, a or self.accel
        target = self._target + delta
        if not -EPS <= target <= self.travel + EPS:
            raise SyringeError(f"plunger would go to {target:.0f} steps, outside its stroke 0..{self.travel:g}: "
                               "refill the syringe, or check the stroke / retract settings")
        if abs(delta) < EPS:
            return
        self.motor.set_z(min(max(target, 0.0), self.travel), vz=v, az=a)
        self._target, self._busy = target, trapezoid_time(abs(delta), v, a)
        self._dir = 1 if delta > 0 else -1

    def _limit_backoff(self):
        """The limit switch was hit going forward: stop, pull back `limit_backoff` steps, then raise."""
        self.stop()
        try:
            self.motor.wait(timeout=self.motor.STOP_TIMEOUT)
        except Exception:
            pass
        steps = min(self.limit_backoff, max(self._target, 0.0))
        if steps > EPS:
            self._push(-steps)             # _dir = -1: wait() does not treat the switch as a hit
            self.wait()
        if self.motor.limit():
            raise SyringeError(f"limit switch hit: backed off {steps:.0f} steps but it is still "
                               "pressed (or not wired): retract further by hand")
        raise SyringeError(f"limit switch hit: stopped and backed off {steps:.0f} steps; "
                           "the stroke was cut short")

    def _guard(self, state):
        """Back off if the plunger is pushing into the limit switch. Returns `state`."""
        if state.limit and self._dir > 0:
            self._limit_backoff()
        return state

    # ---- state ------------------------------------------------------------

    def wait(self, timeout=None):
        """Block until the plunger stands still (default timeout: twice the planned move time + 2 s).
        If a forward move hits the limit switch: stops, backs off, raises SyringeError."""
        timeout = 2 * self._busy + 2.0 if timeout is None else timeout
        deadline = None if timeout is None else time.monotonic() + timeout
        while True:
            state = self._guard(self.motor.get_states())
            if not state.is_moving:
                self._busy, self._dir = 0.0, 0
                return state
            if deadline is not None and time.monotonic() >= deadline:
                raise TimeoutError(f"syringe plunger still moving after {timeout} s")
            time.sleep(self.motor.poll_interval)

    @property
    def position(self):
        """Reported plunger position, steps."""
        state = self._guard(self.motor.get_states())
        return state.z

    def is_moving(self):
        state = self._guard(self.motor.get_states())
        return state.is_moving

    def limit(self):
        """True if the limit switch is currently hit."""
        state = self._guard(self.motor.get_states())
        return state.limit

    def stop(self):
        """Decelerate to a standstill as fast as the motor preset allows. The cycle state is then unknown."""
        self._busy, self._dir = 0.0, 0
        try:
            self._target = self.motor.get_z()
        except Exception:
            pass
        self.motor.stop()

    def close(self):
        """Stop, switch the coil off and disconnect. Safe to call twice."""
        self.motor.close()

    def __enter__(self):
        return self

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


class SyringeBank:
    """Several syringes (one per colour), used one at a time, addressed by name."""

    def __init__(self, syringes):
        self.syringes = dict(syringes)

    @classmethod
    def connect(cls, targets, *, expected_ids=None, **syringe_kwargs):
        """Open one Syringe per entry of `targets` {name: address}, checking each board's MOTOR_ID
        (`expected_ids` {name: id}). If one fails, those already open are closed."""
        ids = expected_ids or {}
        syringes = {}
        try:
            for name, target in targets.items():
                syringes[name] = Syringe(target, expected_id=ids.get(name), **syringe_kwargs)
        except BaseException:
            for s in syringes.values():
                s.close()
            raise
        return cls(syringes)

    def __getitem__(self, name):
        return self.syringes[name]

    def items(self):
        return self.syringes.items()

    @property
    def active(self):
        """Name of the syringe that is primed (mid-stroke), or None."""
        return next((n for n, s in self.syringes.items() if s.primed), None)

    def _use(self, name):
        if name not in self.syringes:
            raise SyringeError(f"no syringe '{name}' is connected (have: {sorted(self.syringes)})")
        busy = self.active
        if busy is not None and busy != name:
            raise SyringeError(f"syringe {busy} is still primed: retract it before using {name} "
                               "(one syringe at a time)")
        return self.syringes[name]

    def prime(self, name):
        self._use(name).prime()

    def extrude(self, name, steps, duration=None):
        self._use(name).extrude(steps, duration)

    def retract(self, name):
        self._use(name).retract()

    def limit(self, name=None):
        """True if the named syringe's limit switch (or any syringe if name is None) is hit."""
        if name is not None:
            return self.syringes[name].limit()
        return any(s.limit() for s in self.syringes.values())

    def wait(self, name=None, timeout=None):
        try:
            for n in [name] if name else list(self.syringes):
                self.syringes[n].wait(timeout)
        except BaseException:
            self.stop()
            raise

    def stop(self):
        """Stop every syringe. Best effort, never raises."""
        for s in self.syringes.values():
            try:
                s.stop()
            except Exception:
                pass

    def close(self):
        """Stop, switch every coil off and disconnect. Best effort."""
        for s in self.syringes.values():
            try:
                s.close()
            except Exception:
                pass
