"""A simulated stepper board, a stand-in for arduino/UFP/examples/ufp_stepper.

It exposes the functions the wrapper uses (get_id, set_target_velocity,
set_target_position, set_position, set_current, get_states, halt) with the
firmware's names, argument names and units (full steps). The motion follows the
firmware's logic in simplified form, integrated in 1 ms steps on demand.

Two hardware details are modelled because they matter to a host program:
  * set_position() redefines the *reported* position only; the carriage's real
    position, which decides the limit switch, is separate.
  * with the coil current at 0 there is no torque: the reported position changes
    but the carriage does not move.

The limit switch reads True (open) while the carriage is at or below `limit_at`.

    python examples/simulated_stepper.py            # serve on tcp://:9000
    python examples/simulated_stepper.py tcp://:9001
"""

import math
import sys
import threading
import time
from typing import Annotated, NamedTuple

import ufp
from ufp import f32, u8, u64, unit

Steps = Annotated[f32, unit("steps")]
StepsPerS = Annotated[f32, unit("steps/s")]
StepsPerS2 = Annotated[f32, unit("steps/s^2")]

SETTLE_EPSILON = 128 / 65536    # steps; same "there" window as the firmware


class States(NamedTuple):
    position: Steps
    velocity: StepsPerS
    acceleration: StepsPerS2
    is_moving: bool
    limit: bool
    time_ns: Annotated[u64, unit("ns")]


class SimulatedStepper:
    """Args:
        start_position: where the carriage really is, in steps relative to the
            switch position (the reported position starts at 0 regardless).
        limit_at: the switch reads open at or below this real position.
        reversed_wiring: positive steps move the carriage *towards* the switch, like a
            motor wired the other way round (the wrapper's `invert=True`).
    """

    DT = 0.001   # s, integration step

    def __init__(self, *, start_position=30.0, limit_at=..., motor_id=1, clock=time.monotonic,
                 reversed_wiring=False, limit_fn=None):
        if limit_at is ...:
            limit_at = 0.0 if start_position != 0.0 else None
        self.limit_at = limit_at
        self.limit_fn = limit_fn
        self._direction = -1.0 if reversed_wiring else 1.0
        self.calls = []                  # (function name, args) for every call received
        self._motor_id = motor_id
        self._clock = clock
        self._lock = threading.RLock()
        self._last = clock()
        self._pending = 0.0
        self._sim_time = 0.0
        self._pos = 0.0                  # reported position (steps)
        self._true = float(start_position)
        self._v = 0.0
        self._a = 0.0
        self._moving = False
        self._mode = "vel"
        self._vmax = 0.0                 # velocity target (vel mode) or speed limit (pos mode)
        self._amax = 0.0
        self._target = 0.0
        self._amplitude = 0              # 0..1024, like the firmware
        self.device = ufp.Device("simple_stepper")
        self._register()

    # ---- state for tests --------------------------------------------------

    @property
    def true_position(self):
        with self._lock:
            self._advance()
            return self._true

    @property
    def limit(self):
        if self.limit_fn is not None:
            try:
                return bool(self.limit_fn(self))
            except TypeError:
                return bool(self.limit_fn())
        with self._lock:
            self._advance()
            return self.limit_at is not None and self._true <= self.limit_at

    @property
    def amplitude(self):
        return self._amplitude

    # ---- motion model -----------------------------------------------------

    def _advance(self):
        now = self._clock()
        elapsed = now - self._last
        self._last = now
        self._sim_time += elapsed
        if not self._moving:
            self._pending = 0.0
            return
        self._pending += elapsed
        while self._pending >= self.DT and self._moving:
            self._integrate(self.DT)
            self._pending -= self.DT

    def _move(self, delta):
        self._pos += delta
        if self._amplitude > 0:          # no torque, no motion
            self._true += self._direction * delta

    def _finish(self, dist):
        self._v = self._a = 0.0
        self._moving = False
        self._move(dist)

    def _integrate(self, dt):
        step = self._amax * dt
        if self._mode == "vel":
            target = self._vmax
            if self._v < target:
                nv = min(self._v + step, target)
            elif self._v > target:
                nv = max(self._v - step, target)
            else:
                nv = self._v
            self._a = math.copysign(self._amax, nv - self._v) if nv != self._v else 0.0
            self._v = nv
            if target == 0 and abs(self._v) < max(1.0, 2 * step):
                self._v = self._a = 0.0
                self._moving = False
            self._move(self._v * dt)
            return

        dist = self._target - self._pos
        if self._vmax <= 0 or step <= 0:         # degenerate: the firmware ends the move without moving
            self._finish(0.0)
            return
        toward = dist * self._v > 0
        if toward:
            stop_dist = self._v ** 2 / (2 * self._amax)
            if stop_dist + abs(self._v) * dt >= abs(dist):
                acc = -math.copysign(self._amax, self._v)    # brake
            else:
                acc = math.copysign(self._amax, dist)
        elif dist != 0:
            acc = math.copysign(self._amax, dist)
        else:
            acc = -math.copysign(self._amax, self._v) if self._v else 0.0
        nv = self._v + acc * dt
        if abs(nv) >= self._vmax:
            acc = 0.0
            nv = math.copysign(self._vmax, nv)
        delta = nv * dt
        reaches = dist == 0 or (dist > 0 and delta >= dist) or (dist < 0 and delta <= dist)
        if abs(nv) <= 3 * step and (reaches or abs(dist) <= SETTLE_EPSILON):
            self._finish(dist)
            return
        self._v, self._a = nv, acc
        self._move(delta)

    # ---- UFP functions ----------------------------------------------------

    def _register(self):
        sim, dev = self, self.device

        def record(name, *args):
            sim.calls.append((name, args))
            sim._advance()

        @dev.function
        def get_id() -> u8:
            """Motor ID set at compile time"""
            with sim._lock:
                record("get_id")
                return sim._motor_id

        @dev.function
        def set_target_velocity(velocity: StepsPerS, max_accel: StepsPerS2):
            """Ramp to a velocity"""
            with sim._lock:
                record("set_target_velocity", velocity, max_accel)
                sim._mode = "vel"
                sim._moving = True
                sim._vmax, sim._amax = float(velocity), abs(float(max_accel))

        @dev.function
        def set_target_position(position: Steps, max_vel: StepsPerS, max_accel: StepsPerS2):
            """Move to a position"""
            with sim._lock:
                record("set_target_position", position, max_vel, max_accel)
                sim._mode = "pos"
                sim._moving = True
                sim._target = float(position)
                sim._vmax, sim._amax = abs(float(max_vel)), abs(float(max_accel))

        @dev.function
        def set_position(position: Steps):
            """Redefine the current position"""
            with sim._lock:
                record("set_position", position)
                sim._pos = float(position)

        @dev.function
        def set_current(current: f32):
            """Set the motor current"""
            with sim._lock:
                record("set_current", current)
                sim._amplitude = int(min(max(current, 0.0), 1.0) * 1024)

        @dev.function
        def get_states() -> States:
            """Motion state and limit switch"""
            with sim._lock:
                record("get_states")
                return States(sim._pos, sim._v, sim._a, sim._moving, sim.limit,
                              int(sim._sim_time * 1e9))

        @dev.function
        def halt(decel: StepsPerS2):
            """Clear the queue and decelerate to a stop"""
            with sim._lock:
                record("halt", decel)
                if sim._moving:
                    sim._mode = "vel"
                    sim._vmax = 0.0
                    sim._amax = abs(float(decel)) or 1000.0


if __name__ == "__main__":
    target = sys.argv[1] if len(sys.argv) > 1 else "tcp://:9000"
    sim = SimulatedStepper()
    print(f"{sim.device} serving on {target}  (Ctrl-C to stop)")
    try:
        sim.device.serve(target)
    except KeyboardInterrupt:
        pass
