"""Velocity profiles of a single axis: pure functions, no hardware and no `ufp` import.

Shared by the software planner (to predict how long a move takes) and the syringe wrapper
(to turn "n steps in T seconds" into a speed and an acceleration for the board).
"""
import math


def trapezoid_time(dist: float, vel: float, accel: float) -> float:
    """Time to go `dist` from rest to rest with top speed `vel` and acceleration `accel`."""
    if dist <= 0:
        return 0.0
    if dist >= vel * vel / accel:                 # reaches full speed
        return dist / vel + vel / accel
    return 2 * math.sqrt(dist / accel)            # triangle profile


def flow_profile(steps: float, duration: float, accel: float) -> tuple[float, float]:
    """(speed, accel) of a move of `steps` that takes `duration` s: solves steps/v + v/accel = duration.
    If the axis cannot be that fast with this acceleration, the fastest profile is used."""
    disc = accel * accel * duration * duration - 4 * accel * steps
    if duration <= 0 or disc < 0:
        return math.sqrt(accel * steps), accel    # triangle: as fast as the acceleration allows
    return (accel * duration - math.sqrt(disc)) / 2, accel
